testutil.lua 25 KB

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