nimhcr.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. discard """
  2. batchable: false
  3. """
  4. #
  5. #
  6. # Nim's Runtime Library
  7. # (c) Copyright 2018 Nim Contributors
  8. #
  9. # See the file "copying.txt", included in this
  10. # distribution, for details about the copyright.
  11. #
  12. # This is the Nim hot code reloading run-time for the native targets.
  13. #
  14. # This minimal dynamic library is not subject to reloading when the
  15. # `hotCodeReloading` build mode is enabled. It's responsible for providing
  16. # a permanent memory location for all globals and procs within a program
  17. # and orchestrating the reloading. For globals, this is easily achieved
  18. # by storing them on the heap. For procs, we produce on the fly simple
  19. # trampolines that can be dynamically overwritten to jump to a different
  20. # target. In the host program, all globals and procs are first registered
  21. # here with `hcrRegisterGlobal` and `hcrRegisterProc` and then the
  22. # returned permanent locations are used in every reference to these symbols
  23. # onwards.
  24. #
  25. # Detailed description:
  26. #
  27. # When code is compiled with the hotCodeReloading option for native targets
  28. # a couple of things happen for all modules in a project:
  29. # - the useNimRtl option is forced (including when building the HCR runtime too)
  30. # - all modules of a target get built into separate shared libraries
  31. # - the smallest granularity of reloads is modules
  32. # - for each .c (or .cpp) in the corresponding nimcache folder of the project
  33. # a shared object is built with the name of the source file + DLL extension
  34. # - only the main module produces whatever the original project type intends
  35. # (again in nimcache) and is then copied to its original destination
  36. # - linking is done in parallel - just like compilation
  37. # - function calls to functions from the same project go through function pointers:
  38. # - with a few exceptions - see the nonReloadable pragma
  39. # - the forward declarations of the original functions become function
  40. # pointers as static globals with the same names
  41. # - the original function definitions get suffixed with <name>_actual
  42. # - the function pointers get initialized with the address of the corresponding
  43. # function in the DatInit of their module through a call to either hcrRegisterProc
  44. # or hcrGetProc. When being registered, the <name>_actual address is passed to
  45. # hcrRegisterProc and a permanent location is returned and assigned to the pointer.
  46. # This way the implementation (<name>_actual) can change but the address for it
  47. # will be the same - this works by just updating a jump instruction (trampoline).
  48. # For functions from other modules hcrGetProc is used (after they are registered).
  49. # - globals are initialized only once and their state is preserved
  50. # - including locals with the {.global.} pragma
  51. # - their definitions are changed into pointer definitions which are initialized
  52. # in the DatInit() of their module with calls to hcrRegisterGlobal (supplying the
  53. # size of the type that this HCR runtime should allocate) and a bool is returned
  54. # which when true triggers the initialization code for the global (only once).
  55. # Globals from other modules: a global pointer coupled with a hcrGetGlobal call.
  56. # - globals which have already been initialized cannot have their values changed
  57. # by changing their initialization - use a handler or some other mechanism
  58. # - new globals can be introduced when reloading
  59. # - top-level code (global scope) is executed only once - at the first module load
  60. # - the runtime knows every symbol's module owner (globals and procs)
  61. # - both the RTL and HCR shared libraries need to be near the program for execution
  62. # - same folder, in the PATH or LD_LIBRARY_PATH env var, etc (depending on OS)
  63. # - the main module is responsible for initializing the HCR runtime
  64. # - the main module loads the RTL and HCR shared objects
  65. # - after that a call to hcrInit() is done in the main module which triggers
  66. # the loading of all modules the main one imports, and doing that for the
  67. # dependencies of each module recursively. Basically a DFS traversal.
  68. # - then initialization takes place with several passes over all modules:
  69. # - HcrInit - initializes the pointers for HCR procs such as hcrRegisterProc
  70. # - HcrCreateTypeInfos - creates globals which will be referenced in the next pass
  71. # - DatInit - usual dat init + register/get procs and get globals
  72. # - Init - it does the following multiplexed operations:
  73. # - register globals (if already registered - then just retrieve pointer)
  74. # - execute top level scope (only if loaded for the first time)
  75. # - when modules are loaded the originally built shared libraries get copied in
  76. # the same folder and the copies are loaded instead of the original files
  77. # - a module import tree is built in the runtime (and maintained when reloading)
  78. # - hcrPerformCodeReload
  79. # - named `performCodeReload`, requires the hotcodereloading module
  80. # - explicitly called by the user - the current active callstack shouldn't contain
  81. # any functions which are defined in modules that will be reloaded (or crash!).
  82. # The reason is that old dynamic libraries get unloaded.
  83. # Example:
  84. # if A is the main module and it imports B, then only B is reloadable and only
  85. # if when calling hcrPerformCodeReload there is no function defined in B in the
  86. # current active callstack at the point of the call (it has to be done from A)
  87. # - for reloading to take place the user has to have rebuilt parts of the application
  88. # without changes affecting the main module in any way - it shouldn't be rebuilt.
  89. # - to determine what needs to be reloaded the runtime starts traversing the import
  90. # tree from the root and checks the timestamps of the loaded shared objects
  91. # - modules that are no longer referenced are unloaded and cleaned up properly
  92. # - symbols (procs/globals) that have been removed in the code are also cleaned up
  93. # - so changing the init of a global does nothing, but removing it, reloading,
  94. # and then re-introducing it with a new initializer works
  95. # - new modules can be imported, and imports can also be reodereded/removed
  96. # - hcrReloadNeeded() can be used to determine if any module needs reloading
  97. # - named `hasAnyModuleChanged`, requires the hotcodereloading module
  98. # - code in the beforeCodeReload/afterCodeReload handlers is executed on each reload
  99. # - require the hotcodereloading module
  100. # - such handlers can be added and removed
  101. # - before each reload all "beforeCodeReload" handlers are executed and after
  102. # that all handlers (including "after") from the particular module are deleted
  103. # - the order of execution is the same as the order of top-level code execution.
  104. # Example: if A imports B which imports C, then all handlers in C will be executed
  105. # first (from top to bottom) followed by all from B and lastly all from A
  106. # - after the reload all "after" handlers are executed the same way as "before"
  107. # - the handlers for a reloaded module are always removed when reloading and then
  108. # registered when the top-level scope is executed (thanks to `executeOnReload`)
  109. #
  110. # TODO next:
  111. #
  112. # - implement the before/after handlers and hasModuleChanged for the javascript target
  113. # - ARM support for the trampolines
  114. # - investigate:
  115. # - soon the system module might be importing other modules - the init order...?
  116. # (revert https://github.com/nim-lang/Nim/pull/11971 when working on this)
  117. # - rethink the closure iterators
  118. # - ability to keep old versions of dynamic libraries alive
  119. # - because of async server code
  120. # - perhaps with refcounting of .dlls for unfinished closures
  121. # - linking with static libs
  122. # - all shared objects for each module will (probably) have to link to them
  123. # - state in static libs gets duplicated
  124. # - linking is slow and therefore iteration time suffers
  125. # - have just a single .dll for all .nim files and bulk reload?
  126. # - think about the compile/link/passc/passl/emit/injectStmt pragmas
  127. # - if a passc pragma is introduced (either written or dragged in by a new
  128. # import) the whole command line for compilation changes - for example:
  129. # winlean.nim: {.passc: "-DWIN32_LEAN_AND_MEAN".}
  130. # - play with plugins/dlls/lfIndirect/lfDynamicLib/lfExportLib - shouldn't add an extra '*'
  131. # - everything thread-local related
  132. # - tests
  133. # - add a new travis build matrix entry which builds everything with HCR enabled
  134. # - currently building with useNimRtl is problematic - lots of problems...
  135. # - how to supply the nimrtl/nimhcr shared objects to all test binaries...?
  136. # - think about building to C++ instead of only to C - added type safety
  137. # - run tests through valgrind and the sanitizers!
  138. #
  139. # TODO - nice to have cool stuff:
  140. #
  141. # - separate handling of global state for much faster reloading and manipulation
  142. # - imagine sliders in an IDE for tweaking variables
  143. # - perhaps using shared memory
  144. # - multi-dll projects - how everything can be reloaded..?
  145. # - a single HCR instance shared across multiple .dlls
  146. # - instead of having to call hcrPerformCodeReload from a function in each dll
  147. # - which currently renders the main module of each dll not reloadable
  148. # - ability to check with the current callstack if a reload is "legal"
  149. # - if it is in any function which is in a module about to be reloaded ==> error
  150. # - pragma annotations for files - to be excluded from dll shenanigans
  151. # - for such file-global pragmas look at codeReordering or injectStmt
  152. # - how would the initialization order be kept? messy...
  153. # - C code calling stable exportc interface of nim code (for bindings)
  154. # - generate proxy functions with the stable names
  155. # - in a non-reloadable part (the main binary) that call the function pointers
  156. # - parameter passing/forwarding - how? use the same trampoline jumping?
  157. # - extracting the dependencies for these stubs/proxies will be hard...
  158. # - changing memory layout of types - detecting this..?
  159. # - implement with registerType() call to HCR runtime...?
  160. # - and checking if a previously registered type matches
  161. # - issue an error
  162. # - or let the user handle this by transferring the state properly
  163. # - perhaps in the before/afterCodeReload handlers
  164. # - implement executeOnReload for global vars too - not just statements (and document!)
  165. # - cleanup at shutdown - freeing all globals
  166. # - fallback mechanism if the program crashes (the program should detect crashes
  167. # by itself using SEH/signals on Windows/Unix) - should be able to revert to
  168. # previous versions of the .dlls by calling some function from HCR
  169. # - improve runtime performance - possibilities
  170. # - implement a way for multiple .nim files to be bundled into the same dll
  171. # and have all calls within that domain to use the "_actual" versions of
  172. # procs so there are no indirections (or the ability to just bundle everything
  173. # except for a few unreloadable modules into a single mega reloadable dll)
  174. # - try to load the .dlls at specific addresses of memory (close to each other)
  175. # allocated with execution flags - check this: https://github.com/fancycode/MemoryModule
  176. #
  177. # TODO - unimportant:
  178. #
  179. # - have a "bad call" trampoline that all no-longer-present functions are routed to call there
  180. # - so the user gets some error msg if he calls a dangling pointer instead of a crash
  181. # - before/afterCodeReload and hasModuleChanged should be accessible only where appropriate
  182. # - nim_program_result is inaccessible in HCR mode from external C code (see nimbase.h)
  183. # - proper .json build file - but the format is different... multiple link commands...
  184. # - avoid registering globals on each loop when using an iterator in global scope
  185. #
  186. # TODO - REPL:
  187. # - proper way (as proposed by Zahary):
  188. # - parse the input code and put everything in global scope except for
  189. # statements with side effects only - those go in afterCodeReload blocks
  190. # - my very hacky idea: just append to a closure iterator the new statements
  191. # followed by a yield statement. So far I can think of 2 problems:
  192. # - import and some other code cannot be written inside of a proc -
  193. # has to be parsed and extracted in the outer scope
  194. # - when new variables are created they are actually locals to the closure
  195. # so the struct for the closure state grows in memory, but it has already
  196. # been allocated when the closure was created with the previous smaller size.
  197. # That would lead to working with memory outside of the initially allocated
  198. # block. Perhaps something can be done about this - some way of re-allocating
  199. # the state and transferring the old...
  200. when not defined(js) and (defined(hotcodereloading) or
  201. defined(createNimHcr) or
  202. defined(testNimHcr)):
  203. const
  204. dllExt = when defined(windows): "dll"
  205. elif defined(macosx): "dylib"
  206. else: "so"
  207. type
  208. HcrProcGetter* = proc (libHandle: pointer, procName: cstring): pointer {.nimcall.}
  209. HcrGcMarkerProc = proc () {.nimcall, raises: [].}
  210. HcrModuleInitializer* = proc () {.nimcall.}
  211. when defined(createNimHcr):
  212. when system.appType != "lib":
  213. {.error: "This file has to be compiled as a library!".}
  214. import os, tables, sets, times, strutils, reservedmem, dynlib
  215. template trace(args: varargs[untyped]) =
  216. when defined(testNimHcr) or defined(traceHcr):
  217. echo args
  218. proc sanitize(arg: Time): string =
  219. when defined(testNimHcr): return "<time>"
  220. else: return $arg
  221. proc sanitize(arg: string|cstring): string =
  222. when defined(testNimHcr): return ($arg).splitFile.name.splitFile.name
  223. else: return $arg
  224. {.pragma: nimhcr, compilerproc, exportc, dynlib.}
  225. # XXX these types are CPU specific and need ARM etc support
  226. type
  227. ShortJumpInstruction {.packed.} = object
  228. opcode: byte
  229. offset: int32
  230. LongJumpInstruction {.packed.} = object
  231. opcode1: byte
  232. opcode2: byte
  233. offset: int32
  234. absoluteAddr: pointer
  235. proc writeJump(jumpTableEntry: ptr LongJumpInstruction, targetFn: pointer) =
  236. let
  237. jumpFrom = jumpTableEntry.shift(sizeof(ShortJumpInstruction))
  238. jumpDistance = distance(jumpFrom, targetFn)
  239. if abs(jumpDistance) < 0x7fff0000:
  240. let shortJump = cast[ptr ShortJumpInstruction](jumpTableEntry)
  241. shortJump.opcode = 0xE9 # relative jump
  242. shortJump.offset = int32(jumpDistance)
  243. else:
  244. jumpTableEntry.opcode1 = 0xff # indirect absolute jump
  245. jumpTableEntry.opcode2 = 0x25
  246. when hostCPU == "i386":
  247. # on x86 we write the absolute address of the following pointer
  248. jumpTableEntry.offset = cast[int32](addr jumpTableEntry.absoluteAddr)
  249. else:
  250. # on x64, we use a relative address for the same location
  251. jumpTableEntry.offset = 0
  252. jumpTableEntry.absoluteAddr = targetFn
  253. if hostCPU == "arm":
  254. const jumpSize = 8
  255. elif hostCPU == "arm64":
  256. const jumpSize = 16
  257. const defaultJumpTableSize = case hostCPU
  258. of "i386": 50
  259. of "amd64": 500
  260. else: 50
  261. let jumpTableSizeStr = getEnv("HOT_CODE_RELOADING_JUMP_TABLE_SIZE")
  262. let jumpTableSize = if jumpTableSizeStr.len > 0: parseInt(jumpTableSizeStr)
  263. else: defaultJumpTableSize
  264. # TODO: perhaps keep track of free slots due to removed procs using a free list
  265. var jumpTable = ReservedMemSeq[LongJumpInstruction].init(
  266. memStart = cast[pointer](0x10000000),
  267. maxLen = jumpTableSize * 1024 * 1024 div sizeof(LongJumpInstruction),
  268. accessFlags = memExecReadWrite)
  269. type
  270. ProcSym = object
  271. jump: ptr LongJumpInstruction
  272. gen: int
  273. GlobalVarSym = object
  274. p: pointer
  275. markerProc: HcrGcMarkerProc
  276. gen: int
  277. ModuleDesc = object
  278. procs: Table[string, ProcSym]
  279. globals: Table[string, GlobalVarSym]
  280. imports: seq[string]
  281. handle: LibHandle
  282. hash: string
  283. gen: int
  284. lastModification: Time
  285. handlers: seq[tuple[isBefore: bool, cb: proc ()]]
  286. proc newModuleDesc(): ModuleDesc =
  287. result.procs = initTable[string, ProcSym]()
  288. result.globals = initTable[string, GlobalVarSym]()
  289. result.handle = nil
  290. result.gen = -1
  291. result.lastModification = low(Time)
  292. # the global state necessary for traversing and reloading the module import tree
  293. var modules = initTable[string, ModuleDesc]()
  294. var root: string
  295. var system: string
  296. var mainDatInit: HcrModuleInitializer
  297. var generation = 0
  298. # necessary for queries such as "has module X changed" - contains all but the main module
  299. var hashToModuleMap = initTable[string, string]()
  300. # necessary for registering handlers and keeping them up-to-date
  301. var currentModule: string
  302. # supplied from the main module - used by others to initialize pointers to this runtime
  303. var hcrDynlibHandle: pointer
  304. var getProcAddr: HcrProcGetter
  305. proc hcrRegisterProc*(module: cstring, name: cstring, fn: pointer): pointer {.nimhcr.} =
  306. trace " register proc: ", module.sanitize, " ", name
  307. # Please note: We must allocate a local copy of the strings, because the supplied
  308. # `cstring` will reside in the data segment of a DLL that will be later unloaded.
  309. let name = $name
  310. let module = $module
  311. var jumpTableEntryAddr: ptr LongJumpInstruction
  312. modules[module].procs.withValue(name, p):
  313. trace " update proc: ", name
  314. jumpTableEntryAddr = p.jump
  315. p.gen = generation
  316. do:
  317. let len = jumpTable.len
  318. jumpTable.setLen(len + 1)
  319. jumpTableEntryAddr = addr jumpTable[len]
  320. modules[module].procs[name] = ProcSym(jump: jumpTableEntryAddr, gen: generation)
  321. writeJump jumpTableEntryAddr, fn
  322. return jumpTableEntryAddr
  323. proc hcrGetProc*(module: cstring, name: cstring): pointer {.nimhcr.} =
  324. trace " get proc: ", module.sanitize, " ", name
  325. return modules[$module].procs.getOrDefault($name, ProcSym()).jump
  326. proc hcrRegisterGlobal*(module: cstring,
  327. name: cstring,
  328. size: Natural,
  329. gcMarker: HcrGcMarkerProc,
  330. outPtr: ptr pointer): bool {.nimhcr.} =
  331. trace " register global: ", module.sanitize, " ", name
  332. # Please note: We must allocate local copies of the strings, because the supplied
  333. # `cstring` will reside in the data segment of a DLL that will be later unloaded.
  334. # Also using a ptr pointer instead of a var pointer (an output parameter)
  335. # because for the C++ backend var parameters use references and in this use case
  336. # it is not possible to cast an int* (for example) to a void* and then pass it
  337. # to void*& since the casting yields an rvalue and references bind only to lvalues.
  338. let name = $name
  339. let module = $module
  340. modules[module].globals.withValue(name, global):
  341. trace " update global: ", name
  342. outPtr[] = global.p
  343. global.gen = generation
  344. global.markerProc = gcMarker
  345. return false
  346. do:
  347. outPtr[] = alloc0(size)
  348. modules[module].globals[name] = GlobalVarSym(p: outPtr[],
  349. gen: generation,
  350. markerProc: gcMarker)
  351. return true
  352. proc hcrGetGlobal*(module: cstring, name: cstring): pointer {.nimhcr.} =
  353. trace " get global: ", module.sanitize, " ", name
  354. return modules[$module].globals[$name].p
  355. proc getListOfModules(cstringArray: ptr pointer): seq[string] =
  356. var curr = cast[ptr cstring](cstringArray)
  357. while len(curr[]) > 0:
  358. result.add($curr[])
  359. curr = cast[ptr cstring](cast[int64](curr) + sizeof(ptr cstring))
  360. template cleanup(collection, body) =
  361. var toDelete: seq[string]
  362. for name, data in collection.pairs:
  363. if data.gen < generation:
  364. toDelete.add(name)
  365. trace "HCR Cleaning ", astToStr(collection), " :: ", name, " ", data.gen
  366. for name {.inject.} in toDelete:
  367. body
  368. proc cleanupGlobal(module: string, name: string) =
  369. var g: GlobalVarSym
  370. if modules[module].globals.take(name, g):
  371. dealloc g.p
  372. proc cleanupSymbols(module: string) =
  373. cleanup modules[module].globals:
  374. cleanupGlobal(module, name)
  375. cleanup modules[module].procs:
  376. modules[module].procs.del(name)
  377. proc unloadDll(name: string) =
  378. if modules[name].handle != nil:
  379. unloadLib(modules[name].handle)
  380. proc loadDll(name: cstring) {.nimhcr.} =
  381. let name = $name
  382. trace "HCR LOADING: ", name.sanitize
  383. if modules.contains(name):
  384. unloadDll(name)
  385. else:
  386. modules[name] = newModuleDesc()
  387. let copiedName = name & ".copy." & dllExt
  388. copyFileWithPermissions(name, copiedName)
  389. let lib = loadLib(copiedName)
  390. assert lib != nil
  391. modules[name].handle = lib
  392. modules[name].gen = generation
  393. modules[name].lastModification = getLastModificationTime(name)
  394. # update the list of imports by the module
  395. let getImportsProc = cast[proc (): ptr pointer {.nimcall.}](
  396. checkedSymAddr(lib, "HcrGetImportedModules"))
  397. modules[name].imports = getListOfModules(getImportsProc())
  398. # get the hash of the module
  399. let getHashProc = cast[proc (): cstring {.nimcall.}](
  400. checkedSymAddr(lib, "HcrGetSigHash"))
  401. modules[name].hash = $getHashProc()
  402. hashToModuleMap[modules[name].hash] = name
  403. # Remove handlers for this module if reloading - they will be re-registered.
  404. # In order for them to be re-registered we need to de-register all globals
  405. # that trigger the registering of handlers through calls to hcrAddEventHandler
  406. modules[name].handlers.setLen(0)
  407. proc initHcrData(name: cstring) {.nimhcr.} =
  408. trace "HCR Hcr init: ", name.sanitize
  409. cast[proc (h: pointer, gpa: HcrProcGetter) {.nimcall.}](
  410. checkedSymAddr(modules[$name].handle, "HcrInit000"))(hcrDynlibHandle, getProcAddr)
  411. proc initTypeInfoGlobals(name: cstring) {.nimhcr.} =
  412. trace "HCR TypeInfo globals init: ", name.sanitize
  413. cast[HcrModuleInitializer](checkedSymAddr(modules[$name].handle, "HcrCreateTypeInfos"))()
  414. proc initPointerData(name: cstring) {.nimhcr.} =
  415. trace "HCR Dat init: ", name.sanitize
  416. cast[HcrModuleInitializer](checkedSymAddr(modules[$name].handle, "DatInit000"))()
  417. proc initGlobalScope(name: cstring) {.nimhcr.} =
  418. trace "HCR Init000: ", name.sanitize
  419. # set the currently inited module - necessary for registering the before/after HCR handlers
  420. currentModule = $name
  421. cast[HcrModuleInitializer](checkedSymAddr(modules[$name].handle, "Init000"))()
  422. var modulesToInit: seq[string] = @[]
  423. var allModulesOrderedByDFS: seq[string] = @[]
  424. proc recursiveDiscovery(dlls: seq[string]) =
  425. for curr in dlls:
  426. if modules.contains(curr):
  427. # skip updating modules that have already been updated to the latest generation
  428. if modules[curr].gen >= generation:
  429. trace "HCR SKIP: ", curr.sanitize, " gen is already: ", modules[curr].gen
  430. continue
  431. # skip updating an unmodified module but continue traversing its dependencies
  432. if modules[curr].lastModification >= getLastModificationTime(curr):
  433. trace "HCR SKIP (not modified): ", curr.sanitize, " ", modules[curr].lastModification.sanitize
  434. # update generation so module doesn't get collected
  435. modules[curr].gen = generation
  436. # recurse to imported modules - they might be changed
  437. recursiveDiscovery(modules[curr].imports)
  438. allModulesOrderedByDFS.add(curr)
  439. continue
  440. loadDll(curr.cstring)
  441. # first load all dependencies of the current module and init it after that
  442. recursiveDiscovery(modules[curr].imports)
  443. allModulesOrderedByDFS.add(curr)
  444. modulesToInit.add(curr)
  445. proc initModules() =
  446. # first init the pointers to hcr functions and also do the registering of typeinfo globals
  447. for curr in modulesToInit:
  448. initHcrData(curr.cstring)
  449. initTypeInfoGlobals(curr.cstring)
  450. # for now system always gets fully inited before any other module (including when reloading)
  451. initPointerData(system.cstring)
  452. initGlobalScope(system.cstring)
  453. # proceed with the DatInit calls - for all modules - including the main one!
  454. for curr in allModulesOrderedByDFS:
  455. if curr != system:
  456. initPointerData(curr.cstring)
  457. mainDatInit()
  458. # execute top-level code (in global scope)
  459. for curr in modulesToInit:
  460. if curr != system:
  461. initGlobalScope(curr.cstring)
  462. # cleanup old symbols which are gone now
  463. for curr in modulesToInit:
  464. cleanupSymbols(curr)
  465. proc hcrInit*(moduleList: ptr pointer, main, sys: cstring,
  466. datInit: HcrModuleInitializer, handle: pointer, gpa: HcrProcGetter) {.nimhcr.} =
  467. trace "HCR INITING: ", main.sanitize, " gen: ", generation
  468. # initialize globals
  469. root = $main
  470. system = $sys
  471. mainDatInit = datInit
  472. hcrDynlibHandle = handle
  473. getProcAddr = gpa
  474. # the root is already added and we need it because symbols from it will also be registered in the HCR system
  475. modules[root].imports = getListOfModules(moduleList)
  476. modules[root].gen = high(int) # something huge so it doesn't get collected
  477. # recursively initialize all modules
  478. recursiveDiscovery(modules[root].imports)
  479. initModules()
  480. # the next module to be inited will be the root
  481. currentModule = root
  482. proc hcrHasModuleChanged*(moduleHash: string): bool {.nimhcr.} =
  483. let module = hashToModuleMap[moduleHash]
  484. return modules[module].lastModification < getLastModificationTime(module)
  485. proc hcrReloadNeeded*(): bool {.nimhcr.} =
  486. for hash, _ in hashToModuleMap:
  487. if hcrHasModuleChanged(hash):
  488. return true
  489. return false
  490. proc hcrPerformCodeReload*() {.nimhcr.} =
  491. if not hcrReloadNeeded():
  492. trace "HCR - no changes"
  493. return
  494. # We disable the GC during the reload, because the reloading procedures
  495. # will replace type info objects and GC marker procs. This seems to create
  496. # problems when the GC is executed while the reload is underway.
  497. # Future versions of NIMHCR won't use the GC, because all globals and the
  498. # metadata needed to access them will be placed in shared memory, so they
  499. # can be manipulated from external programs without reloading.
  500. GC_disable()
  501. defer: GC_enable()
  502. inc(generation)
  503. trace "HCR RELOADING: ", generation
  504. var traversedHandlerModules = initHashSet[string]()
  505. proc recursiveExecuteHandlers(isBefore: bool, module: string) =
  506. # do not process an already traversed module
  507. if traversedHandlerModules.containsOrIncl(module): return
  508. traversedHandlerModules.incl module
  509. # first recurse to do a DFS traversal
  510. for curr in modules[module].imports:
  511. recursiveExecuteHandlers(isBefore, curr)
  512. # and then execute the handlers - from leaf modules all the way up to the root module
  513. for curr in modules[module].handlers:
  514. if curr.isBefore == isBefore:
  515. curr.cb()
  516. # first execute the before reload handlers
  517. traversedHandlerModules.clear()
  518. recursiveExecuteHandlers(true, root)
  519. # do the reloading
  520. modulesToInit = @[]
  521. allModulesOrderedByDFS = @[]
  522. recursiveDiscovery(modules[root].imports)
  523. initModules()
  524. # execute the after reload handlers
  525. traversedHandlerModules.clear()
  526. recursiveExecuteHandlers(false, root)
  527. # collecting no longer referenced modules - based on their generation
  528. cleanup modules:
  529. cleanupSymbols(name)
  530. unloadDll(name)
  531. hashToModuleMap.del(modules[name].hash)
  532. modules.del(name)
  533. proc hcrAddEventHandler*(isBefore: bool, cb: proc ()) {.nimhcr.} =
  534. modules[currentModule].handlers.add(
  535. (isBefore: isBefore, cb: cb))
  536. proc hcrAddModule*(module: cstring) {.nimhcr.} =
  537. if not modules.contains($module):
  538. modules[$module] = newModuleDesc()
  539. proc hcrGeneration*(): int {.nimhcr.} =
  540. generation
  541. proc hcrMarkGlobals*() {.compilerproc, exportc, dynlib, nimcall, gcsafe.} =
  542. # This is gcsafe, because it will be registered
  543. # only in the GC of the main thread.
  544. {.gcsafe.}:
  545. for _, module in modules:
  546. for _, global in module.globals:
  547. if global.markerProc != nil:
  548. global.markerProc()
  549. elif defined(hotcodereloading) or defined(testNimHcr):
  550. when not defined(js):
  551. const
  552. nimhcrLibname = when defined(windows): "nimhcr." & dllExt
  553. elif defined(macosx): "libnimhcr." & dllExt
  554. else: "libnimhcr." & dllExt
  555. {.pragma: nimhcr, compilerproc, importc, dynlib: nimhcrLibname.}
  556. proc hcrRegisterProc*(module: cstring, name: cstring, fn: pointer): pointer {.nimhcr.}
  557. proc hcrGetProc*(module: cstring, name: cstring): pointer {.nimhcr.}
  558. proc hcrRegisterGlobal*(module: cstring, name: cstring, size: Natural,
  559. gcMarker: HcrGcMarkerProc, outPtr: ptr pointer): bool {.nimhcr.}
  560. proc hcrGetGlobal*(module: cstring, name: cstring): pointer {.nimhcr.}
  561. proc hcrInit*(moduleList: ptr pointer,
  562. main, sys: cstring,
  563. datInit: HcrModuleInitializer,
  564. handle: pointer,
  565. gpa: HcrProcGetter) {.nimhcr.}
  566. proc hcrAddModule*(module: cstring) {.nimhcr.}
  567. proc hcrHasModuleChanged*(moduleHash: string): bool {.nimhcr.}
  568. proc hcrReloadNeeded*(): bool {.nimhcr.}
  569. proc hcrPerformCodeReload*() {.nimhcr.}
  570. proc hcrAddEventHandler*(isBefore: bool, cb: proc ()) {.nimhcr.}
  571. proc hcrMarkGlobals*() {.raises: [], nimhcr, nimcall, gcsafe.}
  572. when declared(nimRegisterGlobalMarker):
  573. nimRegisterGlobalMarker(cast[GlobalMarkerProc](hcrMarkGlobals))
  574. else:
  575. proc hcrHasModuleChanged*(moduleHash: string): bool =
  576. # TODO
  577. false
  578. proc hcrAddEventHandler*(isBefore: bool, cb: proc ()) =
  579. # TODO
  580. discard