c - libc stat 函数和 LuaJIT

标签 c lua luajit

我一整天都在研究 LuaJIT 的一个神秘的不当行为。 libc stat函数在其 stat 中返回错误值缓冲区。

LuaJIT 脚本:

-- definitions for sys/types.h
 typedef uint32_t      mode_t;
 typedef uint64_t      dev_t;
 typedef uint64_t      ino_t;
 typedef unsigned int  nlink_t;
 typedef int           pid_t;
 typedef unsigned int  id_t;
 typedef unsigned int  uid_t;
 typedef unsigned int  gid_t;
 typedef int64_t       off_t;
 typedef long          blksize_t;
 typedef int64_t       blkcnt_t;
 typedef uint64_t      fsblkcnt_t;
 typedef uint64_t      fsfilcnt_t;

-- for sys/stat.h
  struct stat {
   dev_t      st_dev;         /* Device */
   ino_t      st_ino; /* File serial number. */
   nlink_t    st_nlink;     /* Link count.  */
   mode_t     st_mode; /* File mode.  */
   uid_t      st_uid; /* User ID of the file's owner. */
   gid_t      st_gid; /* Group ID of the file's group.*/
   int        __pad0;
   dev_t      st_rdev; /* Device number, if device.  */
   off_t      st_size;     /* Size of file, in bytes.  */
   blksize_t  st_blksize; /* Optimal block size for I/O.  */
   blkcnt_t   st_blocks; /* Number 512-byte blocks allocated. */
   /* __USE_XOPEN2K8 */
   struct timespec st_atim; /* Time of last access.  */
   struct timespec st_mtim; /* Time of last modification.  */
   struct timespec st_ctim; /* Time of last status change.  */
   long   __unused[3];
  };
  /* luajit calls this */
  int __xstat(int ver, const char *path, struct stat *buf); 

-- lua stat function part
stat = function(path, buf) return ffi.C.__xstat(_STAT_VER, path, buf) end;

以上内容取 self 的系统 C 头文件。现在 LuaJIT 调用是:

local buf = ffi.new("struct stat[1]")
local res = stat('main.c', buf)
ffi.cdef [[
 int printf(const char *fmt, ...);
]]
ffi.C.printf("size: %lu, ino: %lu, mode: %d\n", buf[0].st_size, buf[0].st_ino, buf[0].st_mode);

struct stat[1]ffi.new luajit 邮件列表友情建议。

更新

这个想法是调用 linux __xtat。已添加声明。

__xstat方法取自 https://github.com/Wiladams/LJIT2libc 。否则 C 中的定义太多了给我的标题。

输出正常,直到 st_mode field 。场为零。我用 C 做了测试语言,一切都很顺利。所以问题出在 LuaJIT stat给我错误的结果。请告知该怎么做。一整天都在那个东西上。

最佳答案

我在 ffi.cdef 中犯了一些拼写错误类型声明。在luajit用户的帮助下,问题现已解决。邮件列表。要快速制作简历:

  1. 输出 clang -E <some_c_file>.cC 上调用的命令源文件,包含 #include <sys/stat.h> .
  2. 制作适当的 struct stat定义。
  3. 我的系统 stat函数有太多级别的宏垃圾。最后,stat函数调用__xstat 。对我来说唯一明智的方式是调用 stat功能是制作一个syscall .
  4. 请记住 Lua print函数不知道cdata类型。和printf不知道Lua类型。但是luajit关于如何来回转换常见数据类型有一个很好且简单的解释。

关于c - libc stat 函数和 LuaJIT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60175500/

相关文章:

lua - 如何获取无符号整数组成的字节?

lua - wrk 执行 Lua 脚本

luajit - Torch Cuda - 在两个 GPU 内核上生成两个进程

c - fwrite 查找到文件末尾后写入文件末尾

c - 在 cortex m3(裸机)上使用 arm-none-eabi 禁用默认 malloc

c - 为什么 lua_newlib 在这个例子中不起作用?

apache - 如何配置 mod_lua (apache) 以使用 LuaJIT?

c++ - 如何静态构建和链接 LuaJIT (VS 2013)

C::在函数中转换指针会丢失数据吗?

c - 用 C 语言编写递归二分查找