如何调试 Lua 扩展随机崩溃

我现在正在尝试编写一个小的 Lua 扩展来处理矩阵乘法。 矩阵部分比较容易且我成功地将其暴露给 Lua。但现在我面临一个奇怪的问题,我写的 Lua 脚本随机崩溃并出现不同的错误。

以下是一个概览

(lldb) run
Process 44058 launched: '/usr/local/bin/luad' (x86_64)
Process 44058 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x1f8)
    frame #0: 0x000000010001cd19 luad`luaH_getn(t=0x00000001002024f0) at ltable.c:643
   640  */
   641  int luaH_getn (Table *t) {
   642    unsigned int j = t->sizearray;
-> 643    if (j > 0 && ttisnil(&t->array[j - 1])) {
   644      /* there is a boundary in the array part: (binary) search for it */
   645      unsigned int i = 0;
   646      while (j - i > 1) {
Target 0: (luad) stopped.
(lldb) run
Process 44062 launched: '/usr/local/bin/luad' (x86_64)
Process 44062 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x100503bbe)
    frame #0: 0x00007fff513e8e87 libsystem_malloc.dylib`tiny_free_list_add_ptr + 108
libsystem_malloc.dylib`tiny_free_list_add_ptr:
->  0x7fff513e8e87 <+108>: movw   %r11w, -0x2(%rdx,%rax)
    0x7fff513e8e8d <+114>: movw   %r11w, 0x10(%rdx)
    0x7fff513e8e92 <+119>: jmp    0x7fff513e8ea0            ; <+133>
    0x7fff513e8e94 <+121>: testw  %r11w, %r11w
Target 0: (luad) stopped.(lldb) run
Process 45023 launched: '/usr/local/bin/luad' (x86_64)
Process 45023 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
    frame #0: 0x000000010000e79e luad`sweeplist(L=0x0000000101000008, p=0x00000001003059a0, count=51) at lgc.c:740
   737    int white = luaC_white(g);  /* current white */
   738    while (*p != NULL && count-- > 0) {
   739      GCObject *curr = *p;
-> 740      int marked = curr->marked;
   741      if (isdeadm(ow, marked)) {  /* is 'curr' dead? */
   742        *p = curr->next;  /* remove 'curr' from list */
   743        freeobj(L, curr);  /* erase 'curr' */
Target 0: (luad) stopped.

这似乎与内存管理和垃圾回收有关,但我已经按照规范操作了。那么我该如何找到我的错误呢?由于随机性,我似乎不能编写最小代码。除了阅读所有 Lua 源代码外,我看不到还能做什么。

如果您好奇,可以查看我的库在Github上,其中有少量可供阅读的代码

任何形式的帮助都将不胜感激。

点赞