testutil.lua 25 KB

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