robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
25.6 KiB931 linesraw
1local ffi = require('ffi')
2local formatc = require('test.unit.formatc')
3local Set = require('test.unit.set')
4local Preprocess = require('test.unit.preprocess')
5local t_global = require('test.testutil')
6local paths = t_global.paths
7local assert = require('test.assert')
8local harness = require('test.harness')
9
10local check_cores = t_global.check_cores
11local dedent = t_global.dedent
12local neq = t_global.neq
13local map = vim.tbl_map
14local eq = t_global.eq
15local trim = vim.trim
16
17local testutil_source = debug.getinfo(1, 'S').source
18
19-- add some standard header locations
20for _, p in ipairs(paths.include_paths) do
21  Preprocess.add_to_include_path(p)
22end
23
24-- add some nonstandard header locations
25if paths.apple_sysroot ~= '' then
26  Preprocess.add_apple_sysroot(paths.apple_sysroot)
27end
28
29local child_pid = nil --- @type integer?
30--- @generic F: function
31--- @param func F
32--- @return F
33local function only_separate(func)
34  return function(...)
35    if child_pid ~= 0 then
36      error('This function must be run in a separate process only')
37    end
38    return func(...)
39  end
40end
41
42--- @class ChildCall
43--- @field func function
44--- @field args any[]
45
46--- @class ChildCallLog
47--- @field func string
48--- @field args any[]
49--- @field ret any?
50
51local child_calls_init = {} --- @type ChildCall[]
52local child_calls_mod = nil --- @type ChildCall[]
53local child_calls_mod_once = nil --- @type ChildCall[]?
54
55local function child_call(func, ret)
56  return function(...)
57    local child_calls = child_calls_mod or child_calls_init
58    if child_pid ~= 0 then
59      child_calls[#child_calls + 1] = { func = func, args = { ... } }
60      return ret
61    else
62      return func(...)
63    end
64  end
65end
66
67-- Run some code at the start of the child process, before running the test
68-- itself. Is supposed to be run in `before_each`.
69--- @param func function
70local function child_call_once(func, ...)
71  if child_pid ~= 0 then
72    child_calls_mod_once[#child_calls_mod_once + 1] = { func = func, args = { ... } }
73  else
74    func(...)
75  end
76end
77
78local child_cleanups_mod_once = nil --- @type ChildCall[]?
79
80-- Run some code at the end of the child process, before exiting. Is supposed to
81-- be run in `before_each` because `after_each` is run after child has exited.
82local function child_cleanup_once(func, ...)
83  local child_cleanups = child_cleanups_mod_once
84  if child_pid ~= 0 then
85    child_cleanups[#child_cleanups + 1] = { func = func, args = { ... } }
86  else
87    func(...)
88  end
89end
90
91-- Unittests are run from debug nvim binary in lua interpreter mode.
92local libnvim = ffi.C
93
94local lib = setmetatable({}, {
95  __index = only_separate(function(_, idx)
96    return libnvim[idx]
97  end),
98  __newindex = child_call(function(_, idx, val)
99    libnvim[idx] = val
100  end),
101})
102
103local init = only_separate(function()
104  for _, c in ipairs(child_calls_init) do
105    c.func(unpack(c.args))
106  end
107  libnvim.event_init()
108  if child_calls_mod then
109    for _, c in ipairs(child_calls_mod) do
110      c.func(unpack(c.args))
111    end
112  end
113  if child_calls_mod_once then
114    for _, c in ipairs(child_calls_mod_once) do
115      c.func(unpack(c.args))
116    end
117    child_calls_mod_once = nil
118  end
119end)
120
121local deinit = only_separate(function()
122  if child_cleanups_mod_once then
123    for _, c in ipairs(child_cleanups_mod_once) do
124      c.func(unpack(c.args))
125    end
126    child_cleanups_mod_once = nil
127  end
128end)
129
130-- a Set that keeps around the lines we've already seen
131local cdefs_init = Set:new()
132local cdefs_mod = nil
133local imported = Set:new()
134local pragma_pack_id = 1
135
136-- some things are just too complex for the LuaJIT C parser to digest. We
137-- usually don't need them anyway.
138--- @param body string
139local function filter_complex_blocks(body)
140  local result = {} --- @type string[]
141
142  for line in body:gmatch('[^\r\n]+') do
143    if
144      not (
145        string.find(line, '(^)', 1, true) ~= nil
146        or string.find(line, '_ISwupper', 1, true)
147        or string.find(line, '_Float')
148        or string.find(line, '__s128')
149        or string.find(line, '__u128')
150        or string.find(line, '__SVFloat32_t')
151        or string.find(line, '__SVFloat64_t')
152        or string.find(line, '__SVBool_t')
153        or string.find(line, '__f32x4_t')
154        or string.find(line, '__f64x2_t')
155        or string.find(line, '__sv_f32_t')
156        or string.find(line, '__sv_f64_t')
157        or string.find(line, 'extern __typeof')
158        or string.find(line, 'msgpack_zone_push_finalizer')
159        or string.find(line, 'msgpack_unpacker_reserve_buffer')
160        or string.find(line, 'value_init_')
161        or string.find(line, 'UUID_NULL') -- static const uuid_t UUID_NULL = {...}
162        or string.find(line, 'inline _Bool')
163        -- used by musl libc headers on 32-bit arches via __REDIR marco
164        or string.find(line, '__typeof__')
165        -- used by macOS headers
166        or string.find(line, 'typedef enum : ')
167        or string.find(line, 'mach_vm_range_recipe')
168        or string.find(line, 'ipc_info_object_type_t')
169        or string.find(line, '__Reply__mach_port_kobject_t')
170        -- C11 keyword, not understood by LuaJIT FFI. Emitted by some libc headers (e.g. ARM/clang glibc).
171        or string.find(line, '_Static_assert', 1, true)
172      )
173    then
174      -- Remove GCC's extension keyword which is just used to disable warnings.
175      line = string.gsub(line, '__extension__', '')
176
177      -- HACK: remove bitfields from specific structs as luajit can't seem to handle them.
178      if line:find('struct VTermState') then
179        line = string.gsub(line, 'state : 8;', 'state;')
180      end
181      if line:find('VTermStringFragment') then
182        line = string.gsub(line, 'size_t.*len : 30;', 'size_t len;')
183      end
184      result[#result + 1] = line
185    end
186  end
187
188  return table.concat(result, '\n')
189end
190
191local cdef = ffi.cdef
192
193local cimportstr
194
195local previous_defines_init = [[
196typedef struct { char bytes[16]; } __attribute__((aligned(16))) __uint128_t;
197typedef struct { char bytes[16]; } __attribute__((aligned(16))) __float128;
198]]
199
200local preprocess_cache_init = {} --- @type table<string,string>
201local previous_defines_mod = ''
202local preprocess_cache_mod = nil --- @type table<string,string>
203
204local function is_child_cdefs()
205  return os.getenv('NVIM_TEST_MAIN_CDEFS') ~= '1'
206end
207
208--- use this helper to import C files, you can pass multiple paths at once,
209--- this helper will return the C namespace of the nvim library.
210---
211--- @param ... string
212local function cimport(...)
213  local previous_defines --- @type string
214  local preprocess_cache --- @type table<string,string>
215  local cdefs
216  if is_child_cdefs() and preprocess_cache_mod then
217    preprocess_cache = preprocess_cache_mod
218    previous_defines = previous_defines_mod
219    cdefs = cdefs_mod
220  else
221    preprocess_cache = preprocess_cache_init
222    previous_defines = previous_defines_init
223    cdefs = cdefs_init
224  end
225  for _, path in ipairs({ ... }) do
226    if not (path:sub(1, 1) == '/' or path:sub(1, 1) == '.' or path:sub(2, 2) == ':') then
227      path = './' .. path
228    end
229    if not preprocess_cache[path] then
230      local body --- @type string
231      body, previous_defines = Preprocess.preprocess(previous_defines, path)
232      -- format it (so that the lines are "unique" statements), also filter out
233      -- Objective-C blocks
234      if os.getenv('NVIM_TEST_PRINT_I') == '1' then
235        local lnum = 0
236        for line in body:gmatch('[^\n]+') do
237          lnum = lnum + 1
238          print(lnum, line)
239        end
240      end
241      body = formatc(body)
242      body = filter_complex_blocks(body)
243      -- add the formatted lines to a set
244      local new_cdefs = Set:new()
245      for line in body:gmatch('[^\r\n]+') do
246        line = trim(line)
247        -- give each #pragma pack a unique id, so that they don't get removed
248        -- if they are inserted into the set
249        -- (they are needed in the right order with the struct definitions,
250        -- otherwise luajit has wrong memory layouts for the structs)
251        if line:match('#pragma%s+pack') then
252          --- @type string
253          line = line .. ' // ' .. pragma_pack_id
254          pragma_pack_id = pragma_pack_id + 1
255        end
256        new_cdefs:add(line)
257      end
258
259      -- subtract the lines we've already imported from the new lines, then add
260      -- the new unique lines to the old lines (so they won't be imported again)
261      new_cdefs:diff(cdefs)
262      cdefs:union(new_cdefs)
263      -- request a sorted version of the new lines (same relative order as the
264      -- original preprocessed file) and feed that to the LuaJIT ffi
265      local new_lines = new_cdefs:to_table()
266      if os.getenv('NVIM_TEST_PRINT_CDEF') == '1' then
267        for lnum, line in ipairs(new_lines) do
268          print(lnum, line)
269        end
270      end
271      body = table.concat(new_lines, '\n')
272
273      preprocess_cache[path] = body
274    end
275    cimportstr(preprocess_cache, path)
276  end
277  return lib
278end
279
280local function cimport_immediate(...)
281  local saved_pid = child_pid
282  child_pid = 0
283  local err, emsg = pcall(cimport, ...)
284  child_pid = saved_pid
285  if not err then
286    io.stderr:write(tostring(emsg) .. '\n')
287    assert(false)
288  else
289    return lib
290  end
291end
292
293--- @param preprocess_cache table<string,string[]>
294--- @param path string
295local function _cimportstr(preprocess_cache, path)
296  if imported:contains(path) then
297    return lib
298  end
299  local body = preprocess_cache[path]
300  if body == '' then
301    return lib
302  end
303  cdef(body)
304  imported:add(path)
305
306  return lib
307end
308
309if is_child_cdefs() then
310  cimportstr = child_call(_cimportstr, lib)
311else
312  cimportstr = _cimportstr
313end
314
315local function alloc_log_new()
316  local log = {
317    log = {}, --- @type ChildCallLog[]
318    lib = cimport('./src/nvim/memory.h'), --- @type table<string,function>
319    original_functions = {}, --- @type table<string,function>
320    null = { ['\0:is_null'] = true },
321  }
322
323  local allocator_functions = { 'malloc', 'free', 'calloc', 'realloc' }
324
325  function log:save_original_functions()
326    for _, funcname in ipairs(allocator_functions) do
327      if not self.original_functions[funcname] then
328        self.original_functions[funcname] = self.lib['mem_' .. funcname]
329      end
330    end
331  end
332
333  log.save_original_functions = child_call(log.save_original_functions)
334
335  function log:set_mocks()
336    for _, k in ipairs(allocator_functions) do
337      do
338        local kk = k
339        self.lib['mem_' .. k] = function(...)
340          --- @type ChildCallLog
341          local log_entry = { func = kk, args = { ... } }
342          self.log[#self.log + 1] = log_entry
343          if kk == 'free' then
344            self.original_functions[kk](...)
345          else
346            log_entry.ret = self.original_functions[kk](...)
347          end
348          for i, v in ipairs(log_entry.args) do
349            if v == nil then
350              -- XXX This thing thinks that {NULL} ~= {NULL}.
351              log_entry.args[i] = self.null
352            end
353          end
354          if self.hook then
355            self:hook(log_entry)
356          end
357          if log_entry.ret then
358            return log_entry.ret
359          end
360        end
361      end
362    end
363    -- JIT-compiled FFI calls cannot call back into Lua, so disable JIT.
364    -- Ref: https://luajit.org/ext_ffi_semantics.html#callback
365    jit.off()
366  end
367
368  log.set_mocks = child_call(log.set_mocks)
369
370  function log:clear()
371    self.log = {}
372  end
373
374  function log:check(exp)
375    eq(exp, self.log)
376    self:clear()
377  end
378
379  function log:clear_tmp_allocs(clear_null_frees)
380    local toremove = {} --- @type integer[]
381    local allocs = {} --- @type table<string,integer>
382    for i, v in ipairs(self.log) do
383      if v.func == 'malloc' or v.func == 'calloc' then
384        allocs[tostring(v.ret)] = i
385      elseif v.func == 'realloc' or v.func == 'free' then
386        if allocs[tostring(v.args[1])] then
387          toremove[#toremove + 1] = allocs[tostring(v.args[1])]
388          if v.func == 'free' then
389            toremove[#toremove + 1] = i
390          end
391        elseif clear_null_frees and v.args[1] == self.null then
392          toremove[#toremove + 1] = i
393        end
394        if v.func == 'realloc' then
395          allocs[tostring(v.ret)] = i
396        end
397      end
398    end
399    table.sort(toremove)
400    for i = #toremove, 1, -1 do
401      table.remove(self.log, toremove[i])
402    end
403  end
404
405  function log:setup()
406    log:save_original_functions()
407    log:set_mocks()
408  end
409
410  function log:before_each() end
411
412  function log:after_each() end
413
414  log:setup()
415
416  return log
417end
418
419-- take a pointer to a C-allocated string and return an interned
420-- version while also freeing the memory
421local function internalize(cdata, len)
422  ffi.gc(cdata, ffi.C.free)
423  return ffi.string(cdata, len)
424end
425
426local cstr = ffi.typeof('char[?]')
427local function to_cstr(string)
428  return cstr(#string + 1, string)
429end
430
431cimport_immediate('./test/unit/fixtures/posix.h')
432
433local sc = {}
434
435function sc.fork()
436  return tonumber(ffi.C.fork())
437end
438
439function sc.pipe()
440  local ret = ffi.new('int[2]', { -1, -1 })
441  ffi.errno(0)
442  local res = ffi.C.pipe(ret)
443  if res ~= 0 then
444    local err = ffi.errno(0)
445    assert(res == 0, ('pipe() error: %u: %s'):format(err, ffi.string(ffi.C.strerror(err))))
446  end
447  assert(ret[0] ~= -1 and ret[1] ~= -1)
448  return ret[0], ret[1]
449end
450
451--- @return string
452function sc.read(rd, len)
453  local ret = ffi.new('char[?]', len, { 0 })
454  local total_bytes_read = 0
455  ffi.errno(0)
456  while total_bytes_read < len do
457    local bytes_read =
458      tonumber(ffi.C.read(rd, ffi.cast('void*', ret + total_bytes_read), len - total_bytes_read))
459    if bytes_read == -1 then
460      local err = ffi.errno(0)
461      if err ~= ffi.C.kPOSIXErrnoEINTR then
462        assert(false, ('read() error: %u: %s'):format(err, ffi.string(ffi.C.strerror(err))))
463      end
464    elseif bytes_read == 0 then
465      break
466    else
467      total_bytes_read = total_bytes_read + bytes_read
468    end
469  end
470  return ffi.string(ret, total_bytes_read)
471end
472
473function sc.write(wr, s)
474  local wbuf = to_cstr(s)
475  local total_bytes_written = 0
476  ffi.errno(0)
477  while total_bytes_written < #s do
478    local bytes_written = tonumber(
479      ffi.C.write(wr, ffi.cast('void*', wbuf + total_bytes_written), #s - total_bytes_written)
480    )
481    if bytes_written == -1 then
482      local err = ffi.errno(0)
483      if err ~= ffi.C.kPOSIXErrnoEINTR then
484        assert(
485          false,
486          ("write() error: %u: %s ('%s')"):format(err, ffi.string(ffi.C.strerror(err)), s)
487        )
488      end
489    elseif bytes_written == 0 then
490      break
491    else
492      total_bytes_written = total_bytes_written + bytes_written
493    end
494  end
495  return total_bytes_written
496end
497
498sc.close = ffi.C.close
499
500--- @param pid integer
501--- @return integer
502function sc.wait(pid)
503  ffi.errno(0)
504  local stat_loc = ffi.new('int[1]', { 0 })
505  while true do
506    local r = ffi.C.waitpid(pid, stat_loc, ffi.C.kPOSIXWaitWUNTRACED)
507    if r == -1 then
508      local err = ffi.errno(0)
509      if err == ffi.C.kPOSIXErrnoECHILD then
510        break
511      elseif err ~= ffi.C.kPOSIXErrnoEINTR then
512        assert(false, ('waitpid() error: %u: %s'):format(err, ffi.string(ffi.C.strerror(err))))
513      end
514    else
515      assert(r == pid)
516    end
517  end
518  return stat_loc[0]
519end
520
521sc.exit = ffi.C._exit
522
523--- @param lst string[]
524--- @return string
525local function format_list(lst)
526  local ret = {} --- @type string[]
527  for _, v in ipairs(lst) do
528    ret[#ret + 1] = assert:format({ v, n = 1 })[1]
529  end
530  return table.concat(ret, ', ')
531end
532
533if os.getenv('NVIM_TEST_PRINT_SYSCALLS') == '1' then
534  for k_, v_ in pairs(sc) do
535    (function(k, v)
536      sc[k] = function(...)
537        local rets = { v(...) }
538        io.stderr:write(('%s(%s) = %s\n'):format(k, format_list({ ... }), format_list(rets)))
539        return unpack(rets)
540      end
541    end)(k_, v_)
542  end
543end
544
545local hook_fnamelen = 30
546local hook_sfnamelen = 30
547local hook_numlen = 5
548local hook_msglen = 1 + 1 + 1 + (1 + hook_fnamelen) + (1 + hook_sfnamelen) + (1 + hook_numlen) + 1
549
550local tracehelp = dedent([[
551  Trace: either in the format described below or custom debug output starting
552  with `>`. Latter lines still have the same width in byte.
553
554  ┌ Trace type: _r_eturn from function , function _c_all, _l_ine executed,
555  │             _t_ail return, _C_ount (should not actually appear),
556  │             _s_aved from previous run for reference, _>_ for custom debug
557  │             output.
558  │┏ Function type: _L_ua function, _C_ function, _m_ain part of chunk,
559  │┃                function that did _t_ail call.
560  │┃┌ Function name type: _g_lobal, _l_ocal, _m_ethod, _f_ield, _u_pvalue,
561  │┃│                     space for unknown.
562  │┃│ ┏ Source file name             ┌ Function name                ┏ Line
563  │┃│ ┃ (trunc to 30 bytes, no .lua) │ (truncated to last 30 bytes) ┃ number
564  CWN SSSSSSSSSSSSSSSSSSSSSSSSSSSSSS:FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF:LLLLL\n
565]])
566
567local function child_sethook(wr)
568  local trace_level_str = os.getenv('NVIM_TEST_TRACE_LEVEL')
569  local trace_level = 0
570  if trace_level_str and trace_level_str ~= '' then
571    --- @type number
572    trace_level = assert(tonumber(trace_level_str))
573  end
574
575  if trace_level <= 0 then
576    return
577  end
578
579  local trace_only_c = trace_level <= 1
580  --- @type debuginfo?, string?, integer
581  local prev_info, prev_reason, prev_lnum
582
583  --- @param reason string
584  --- @param lnum integer
585  --- @param use_prev boolean
586  local function hook(reason, lnum, use_prev)
587    local info = nil --- @type debuginfo?
588    if use_prev then
589      info = prev_info
590    elseif reason ~= 'tail return' then -- tail return
591      info = debug.getinfo(2, 'nSl')
592    end
593
594    if trace_only_c and (not info or info.what ~= 'C') and not use_prev then
595      --- @cast info -nil
596      if info.source:sub(-9) == '_spec.lua' then
597        prev_info = info
598        prev_reason = 'saved'
599        prev_lnum = lnum
600      end
601      return
602    end
603    if trace_only_c and not use_prev and prev_reason then
604      hook(prev_reason, prev_lnum, true)
605      prev_reason = nil
606    end
607
608    local whatchar = ' '
609    local namewhatchar = ' '
610    local funcname = ''
611    local source = ''
612    local msgchar = reason:sub(1, 1)
613
614    if reason == 'count' then
615      msgchar = 'C'
616    end
617
618    if info then
619      funcname = (info.name or ''):sub(1, hook_fnamelen)
620      whatchar = info.what:sub(1, 1)
621      namewhatchar = info.namewhat:sub(1, 1)
622      if namewhatchar == '' then
623        namewhatchar = ' '
624      end
625      source = info.source
626      if source:sub(1, 1) == '@' then
627        if source:sub(-4, -1) == '.lua' then
628          source = source:sub(1, -5)
629        end
630        source = source:sub(-hook_sfnamelen, -1)
631      end
632      lnum = lnum or info.currentline
633    end
634
635    -- assert(-1 <= lnum and lnum <= 99999)
636    local lnum_s = lnum == -1 and 'nknwn' or ('%u'):format(lnum)
637    --- @type string
638    local msg = ( -- lua does not support %*
639      ''
640      .. msgchar
641      .. whatchar
642      .. namewhatchar
643      .. ' '
644      .. source
645      .. (' '):rep(hook_sfnamelen - #source)
646      .. ':'
647      .. funcname
648      .. (' '):rep(hook_fnamelen - #funcname)
649      .. ':'
650      .. ('0'):rep(hook_numlen - #lnum_s)
651      .. lnum_s
652      .. '\n'
653    )
654    -- eq(hook_msglen, #msg)
655    sc.write(wr, msg)
656  end
657  debug.sethook(hook, 'crl')
658end
659
660local trace_end_msg = ('E%s\n'):format((' '):rep(hook_msglen - 2))
661
662--- @type function
663local _debug_log
664
665local debug_log = only_separate(function(...)
666  return _debug_log(...)
667end)
668
669local function exception_handler(err)
670  if type(err) == 'table' and err.__harness_pending then
671    --- @cast err test.harness.ErrorPayload
672    return err
673  end
674  local traceback = harness.build_error_traceback(testutil_source) or debug.traceback('', 2)
675  local message = harness.format_error_value(err)
676  return message .. '\nchild ' .. traceback
677end
678
679local function itp_child(wr, func)
680  --- @param s string
681  _debug_log = function(s)
682    s = s:sub(1, hook_msglen - 2)
683    sc.write(wr, '>' .. s .. (' '):rep(hook_msglen - 2 - #s) .. '\n')
684  end
685  local status, result = pcall(init)
686  if status then
687    collectgarbage('stop')
688    child_sethook(wr)
689    status, result = xpcall(func, exception_handler)
690    debug.sethook()
691  end
692  sc.write(wr, trace_end_msg)
693  if not status then
694    local emsg = tostring(result)
695    if #emsg > 99999 then
696      emsg = emsg:sub(1, 99999)
697    end
698    sc.write(wr, ('-\n%05u\n%s'):format(#emsg, emsg))
699    deinit()
700  else
701    sc.write(wr, '+\n')
702    deinit()
703  end
704  collectgarbage('restart')
705  collectgarbage()
706  sc.write(wr, '$\n')
707  sc.close(wr)
708  sc.exit(status and 0 or 1)
709end
710
711local function check_child_err(rd)
712  local trace = {} --- @type string[]
713  local did_traceline = false
714  local maxtrace = tonumber(os.getenv('NVIM_TEST_MAXTRACE')) or 1024
715  while true do
716    local traceline = sc.read(rd, hook_msglen)
717    if #traceline ~= hook_msglen then
718      if #traceline == 0 then
719        break
720      else
721        trace[#trace + 1] = 'Partial read: <' .. trace .. '>\n'
722      end
723    end
724    if traceline == trace_end_msg then
725      did_traceline = true
726      break
727    end
728    trace[#trace + 1] = traceline
729    if #trace > maxtrace then
730      table.remove(trace, 1)
731    end
732  end
733  local res = sc.read(rd, 2)
734  if #res == 2 then
735    local err = ''
736    if res ~= '+\n' then
737      eq('-\n', res)
738      local len_s = sc.read(rd, 5)
739      local len = tonumber(len_s)
740      neq(0, len)
741      if os.getenv('NVIM_TEST_TRACE_ON_ERROR') == '1' and #trace ~= 0 then
742        --- @type string
743        err = '\nTest failed, trace:\n' .. tracehelp
744        for _, traceline in ipairs(trace) do
745          --- @type string
746          err = err .. traceline
747        end
748      end
749      --- @type string
750      err = err .. sc.read(rd, len + 1)
751    end
752    local eres = sc.read(rd, 2)
753    if eres ~= '$\n' then
754      if #trace == 0 then
755        err = '\nTest crashed, no trace available (check NVIM_TEST_TRACE_LEVEL)\n'
756      else
757        err = '\nTest crashed, trace:\n' .. tracehelp
758        for i = 1, #trace do
759          err = err .. trace[i]
760        end
761      end
762      if not did_traceline then
763        --- @type string
764        err = err .. '\nNo end of trace occurred'
765      end
766      local cc_err, cc_emsg = pcall(check_cores, paths.test_luajit_prg, true)
767      if not cc_err then
768        --- @type string
769        err = err .. '\ncheck_cores failed: ' .. cc_emsg
770      end
771    end
772    if err ~= '' then
773      error(err, 0)
774    end
775  end
776end
777
778local function itp_parent(rd, pid, allow_failure, location)
779  local ok, emsg = pcall(check_child_err, rd)
780  local status = sc.wait(pid)
781  sc.close(rd)
782  if not ok then
783    if allow_failure then
784      io.stderr:write('Errorred out (' .. status .. '):\n' .. tostring(emsg) .. '\n')
785      os.execute([[
786        sh -c "source ci/common/test.sh
787        check_core_dumps --delete \"]] .. paths.test_luajit_prg .. [[\""]])
788    else
789      error(tostring(emsg) .. '\nexit code: ' .. status)
790    end
791  elseif status ~= 0 then
792    if not allow_failure then
793      error('child process errored out with status ' .. status .. '!\n\n' .. location)
794    end
795  end
796end
797
798local function gen_itp(it)
799  child_calls_mod = {}
800  child_calls_mod_once = {}
801  child_cleanups_mod_once = {}
802  preprocess_cache_mod = map(function(v)
803    return v
804  end, preprocess_cache_init)
805  previous_defines_mod = previous_defines_init
806  cdefs_mod = cdefs_init:copy()
807  local function itp(name, func, allow_failure)
808    if allow_failure and os.getenv('NVIM_TEST_RUN_FAILING_TESTS') ~= '1' then
809      -- FIXME Fix tests with this true
810      return
811    end
812
813    -- Pre-emptively calculating error location, wasteful, ugh!
814    -- But the way this code wraps the local harness means the real location is strictly
815    -- not available in the parent when an actual error occurs. so we have to do this here.
816    local location = debug.traceback()
817    it(name, function()
818      local rd, wr = sc.pipe()
819      child_pid = sc.fork()
820      if child_pid == 0 then
821        sc.close(rd)
822        itp_child(wr, func)
823      else
824        sc.close(wr)
825        local saved_child_pid = child_pid
826        child_pid = nil
827        itp_parent(rd, saved_child_pid, allow_failure, location)
828      end
829    end)
830  end
831  return itp
832end
833
834local function cppimport(path)
835  return cimport(paths.test_source_path .. '/test/includes/pre/' .. path)
836end
837
838cimport(
839  './src/nvim/types_defs.h',
840  './src/nvim/main.h',
841  './src/nvim/os/time.h',
842  './src/nvim/os/fs.h'
843)
844
845local function conv_enum(etab, eval)
846  local n = tonumber(eval)
847  return etab[n] or n
848end
849
850local function array_size(arr)
851  return ffi.sizeof(arr) / ffi.sizeof(arr[0])
852end
853
854local function kvi_size(kvi)
855  return array_size(kvi.init_array)
856end
857
858local function kvi_init(kvi)
859  kvi.capacity = kvi_size(kvi)
860  kvi.items = kvi.init_array
861  return kvi
862end
863
864local function kvi_destroy(kvi)
865  if kvi.items ~= kvi.init_array then
866    lib.xfree(kvi.items)
867  end
868end
869
870local function kvi_new(ct)
871  return kvi_init(ffi.new(ct))
872end
873
874local function make_enum_conv_tab(m, values, skip_pref, set_cb)
875  child_call_once(function()
876    local ret = {}
877    for _, v in ipairs(values) do
878      local str_v = v
879      if v:sub(1, #skip_pref) == skip_pref then
880        str_v = v:sub(#skip_pref + 1)
881      end
882      ret[tonumber(m[v])] = str_v
883    end
884    set_cb(ret)
885  end)
886end
887
888local function ptr2addr(ptr)
889  return tonumber(ffi.cast('intptr_t', ffi.cast('void *', ptr)))
890end
891
892local s = ffi.new('char[64]', { 0 })
893
894local function ptr2key(ptr)
895  ffi.C.snprintf(s, ffi.sizeof(s), '%p', ffi.cast('void *', ptr))
896  return ffi.string(s)
897end
898
899--- @class test.unit.testutil.module
900local M = {
901  cimport = cimport,
902  cppimport = cppimport,
903  internalize = internalize,
904  ffi = ffi,
905  lib = lib,
906  cstr = cstr,
907  to_cstr = to_cstr,
908  NULL = ffi.cast('void*', 0),
909  OK = 1,
910  FAIL = 0,
911  alloc_log_new = alloc_log_new,
912  gen_itp = gen_itp,
913  only_separate = only_separate,
914  child_call_once = child_call_once,
915  child_cleanup_once = child_cleanup_once,
916  sc = sc,
917  conv_enum = conv_enum,
918  array_size = array_size,
919  kvi_destroy = kvi_destroy,
920  kvi_size = kvi_size,
921  kvi_init = kvi_init,
922  kvi_new = kvi_new,
923  make_enum_conv_tab = make_enum_conv_tab,
924  ptr2addr = ptr2addr,
925  ptr2key = ptr2key,
926  debug_log = debug_log,
927}
928--- @class test.unit.testutil: test.unit.testutil.module, test.testutil
929M = vim.tbl_extend('error', M, t_global)
930
931return M