extccomp.nim 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # Module providing functions for calling the different external C compilers
  10. # Uses some hard-wired facts about each C/C++ compiler, plus options read
  11. # from a lineinfos file, to provide generalized procedures to compile
  12. # nim files.
  13. import ropes, platform, condsyms, options, msgs, lineinfos, pathutils, modulepaths
  14. import std/[os, osproc, streams, sequtils, times, strtabs, json, jsonutils, sugar, parseutils]
  15. import std / strutils except addf
  16. when defined(nimPreviewSlimSystem):
  17. import std/[syncio, assertions]
  18. import ../dist/checksums/src/checksums/sha1
  19. type
  20. TInfoCCProp* = enum # properties of the C compiler:
  21. hasSwitchRange, # CC allows ranges in switch statements (GNU C)
  22. hasComputedGoto, # CC has computed goto (GNU C extension)
  23. hasCpp, # CC is/contains a C++ compiler
  24. hasAssume, # CC has __assume (Visual C extension)
  25. hasGcGuard, # CC supports GC_GUARD to keep stack roots
  26. hasGnuAsm, # CC's asm uses the absurd GNU assembler syntax
  27. hasDeclspec, # CC has __declspec(X)
  28. hasAttribute, # CC has __attribute__((X))
  29. hasBuiltinUnreachable # CC has __builtin_unreachable
  30. TInfoCCProps* = set[TInfoCCProp]
  31. TInfoCC* = tuple[
  32. name: string, # the short name of the compiler
  33. objExt: string, # the compiler's object file extension
  34. optSpeed: string, # the options for optimization for speed
  35. optSize: string, # the options for optimization for size
  36. compilerExe: string, # the compiler's executable
  37. cppCompiler: string, # name of the C++ compiler's executable (if supported)
  38. compileTmpl: string, # the compile command template
  39. buildGui: string, # command to build a GUI application
  40. buildDll: string, # command to build a shared library
  41. buildLib: string, # command to build a static library
  42. linkerExe: string, # the linker's executable (if not matching compiler's)
  43. linkTmpl: string, # command to link files to produce an exe
  44. includeCmd: string, # command to add an include dir
  45. linkDirCmd: string, # command to add a lib dir
  46. linkLibCmd: string, # command to link an external library
  47. debug: string, # flags for debug build
  48. pic: string, # command for position independent code
  49. # used on some platforms
  50. asmStmtFrmt: string, # format of ASM statement
  51. structStmtFmt: string, # Format for struct statement
  52. produceAsm: string, # Format how to produce assembler listings
  53. cppXsupport: string, # what to do to enable C++X support
  54. props: TInfoCCProps] # properties of the C compiler
  55. # Configuration settings for various compilers.
  56. # When adding new compilers, the cmake sources could be a good reference:
  57. # http://cmake.org/gitweb?p=cmake.git;a=tree;f=Modules/Platform;
  58. template compiler(name, settings: untyped): untyped =
  59. proc name: TInfoCC {.compileTime.} = settings
  60. const
  61. gnuAsmListing = "-Wa,-acdl=$asmfile -g -fverbose-asm -masm=intel"
  62. # GNU C and C++ Compiler
  63. compiler gcc:
  64. result = (
  65. name: "gcc",
  66. objExt: "o",
  67. optSpeed: " -O3 -fno-ident",
  68. optSize: " -Os -fno-ident",
  69. compilerExe: "gcc",
  70. cppCompiler: "g++",
  71. compileTmpl: "-c $options $include -o $objfile $file",
  72. buildGui: " -mwindows",
  73. buildDll: " -shared",
  74. buildLib: "ar rcs $libfile $objfiles",
  75. linkerExe: "",
  76. linkTmpl: "$buildgui $builddll -o $exefile $objfiles $options",
  77. includeCmd: " -I",
  78. linkDirCmd: " -L",
  79. linkLibCmd: " -l$1",
  80. debug: "",
  81. pic: "-fPIC",
  82. asmStmtFrmt: "__asm__($1);$n",
  83. structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name
  84. produceAsm: gnuAsmListing,
  85. cppXsupport: "-std=gnu++17 -funsigned-char",
  86. props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm,
  87. hasAttribute, hasBuiltinUnreachable})
  88. # GNU C and C++ Compiler
  89. compiler nintendoSwitchGCC:
  90. result = (
  91. name: "switch_gcc",
  92. objExt: "o",
  93. optSpeed: " -O3 ",
  94. optSize: " -Os ",
  95. compilerExe: "aarch64-none-elf-gcc",
  96. cppCompiler: "aarch64-none-elf-g++",
  97. compileTmpl: "-w -MMD -MP -MF $dfile -c $options $include -o $objfile $file",
  98. buildGui: " -mwindows",
  99. buildDll: " -shared",
  100. buildLib: "aarch64-none-elf-gcc-ar rcs $libfile $objfiles",
  101. linkerExe: "aarch64-none-elf-gcc",
  102. linkTmpl: "$buildgui $builddll -Wl,-Map,$mapfile -o $exefile $objfiles $options",
  103. includeCmd: " -I",
  104. linkDirCmd: " -L",
  105. linkLibCmd: " -l$1",
  106. debug: "",
  107. pic: "-fPIE",
  108. asmStmtFrmt: "asm($1);$n",
  109. structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name
  110. produceAsm: gnuAsmListing,
  111. cppXsupport: "-std=gnu++17 -funsigned-char",
  112. props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm,
  113. hasAttribute, hasBuiltinUnreachable})
  114. # LLVM Frontend for GCC/G++
  115. compiler llvmGcc:
  116. result = gcc() # Uses settings from GCC
  117. result.name = "llvm_gcc"
  118. result.compilerExe = "llvm-gcc"
  119. result.cppCompiler = "llvm-g++"
  120. when defined(macosx) or defined(openbsd):
  121. # `llvm-ar` not available
  122. result.buildLib = "ar rcs $libfile $objfiles"
  123. else:
  124. result.buildLib = "llvm-ar rcs $libfile $objfiles"
  125. # Clang (LLVM) C/C++ Compiler
  126. compiler clang:
  127. result = llvmGcc() # Uses settings from llvmGcc
  128. result.name = "clang"
  129. result.compilerExe = "clang"
  130. result.cppCompiler = "clang++"
  131. # Microsoft Visual C/C++ Compiler
  132. compiler vcc:
  133. result = (
  134. name: "vcc",
  135. objExt: "obj",
  136. optSpeed: " /Ogityb2 ",
  137. optSize: " /O1 ",
  138. compilerExe: "cl",
  139. cppCompiler: "cl",
  140. compileTmpl: "/c$vccplatform $options $include /nologo /Fo$objfile $file",
  141. buildGui: " /SUBSYSTEM:WINDOWS user32.lib ",
  142. buildDll: " /LD",
  143. buildLib: "vccexe --command:lib$vccplatform /nologo /OUT:$libfile $objfiles",
  144. linkerExe: "cl",
  145. linkTmpl: "$builddll$vccplatform /Fe$exefile $objfiles $buildgui /nologo $options",
  146. includeCmd: " /I",
  147. linkDirCmd: " /LIBPATH:",
  148. linkLibCmd: " $1.lib",
  149. debug: " /RTC1 /Z7 ",
  150. pic: "",
  151. asmStmtFrmt: "__asm{$n$1$n}$n",
  152. structStmtFmt: "$3$n$1 $2",
  153. produceAsm: "/Fa$asmfile",
  154. cppXsupport: "",
  155. props: {hasCpp, hasAssume, hasDeclspec})
  156. compiler clangcl:
  157. result = vcc()
  158. result.name = "clang_cl"
  159. result.compilerExe = "clang-cl"
  160. result.cppCompiler = "clang-cl"
  161. result.linkerExe = "clang-cl"
  162. result.linkTmpl = "-fuse-ld=lld " & result.linkTmpl
  163. # Intel C/C++ Compiler
  164. compiler icl:
  165. result = vcc()
  166. result.name = "icl"
  167. result.compilerExe = "icl"
  168. result.linkerExe = "icl"
  169. # Intel compilers try to imitate the native ones (gcc and msvc)
  170. compiler icc:
  171. result = gcc()
  172. result.name = "icc"
  173. result.compilerExe = "icc"
  174. result.linkerExe = "icc"
  175. # Borland C Compiler
  176. compiler bcc:
  177. result = (
  178. name: "bcc",
  179. objExt: "obj",
  180. optSpeed: " -O3 -6 ",
  181. optSize: " -O1 -6 ",
  182. compilerExe: "bcc32c",
  183. cppCompiler: "cpp32c",
  184. compileTmpl: "-c $options $include -o$objfile $file",
  185. buildGui: " -tW",
  186. buildDll: " -tWD",
  187. buildLib: "", # XXX: not supported yet
  188. linkerExe: "bcc32",
  189. linkTmpl: "$options $buildgui $builddll -e$exefile $objfiles",
  190. includeCmd: " -I",
  191. linkDirCmd: "", # XXX: not supported yet
  192. linkLibCmd: "", # XXX: not supported yet
  193. debug: "",
  194. pic: "",
  195. asmStmtFrmt: "__asm{$n$1$n}$n",
  196. structStmtFmt: "$1 $2",
  197. produceAsm: "",
  198. cppXsupport: "",
  199. props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard,
  200. hasAttribute})
  201. # Tiny C Compiler
  202. compiler tcc:
  203. result = (
  204. name: "tcc",
  205. objExt: "o",
  206. optSpeed: "",
  207. optSize: "",
  208. compilerExe: "tcc",
  209. cppCompiler: "",
  210. compileTmpl: "-c $options $include -o $objfile $file",
  211. buildGui: "-Wl,-subsystem=gui",
  212. buildDll: " -shared",
  213. buildLib: "", # XXX: not supported yet
  214. linkerExe: "tcc",
  215. linkTmpl: "-o $exefile $options $buildgui $builddll $objfiles",
  216. includeCmd: " -I",
  217. linkDirCmd: "", # XXX: not supported yet
  218. linkLibCmd: "", # XXX: not supported yet
  219. debug: " -g ",
  220. pic: "",
  221. asmStmtFrmt: "asm($1);$n",
  222. structStmtFmt: "$1 $2",
  223. produceAsm: gnuAsmListing,
  224. cppXsupport: "",
  225. props: {hasSwitchRange, hasComputedGoto, hasGnuAsm})
  226. # Your C Compiler
  227. compiler envcc:
  228. result = (
  229. name: "env",
  230. objExt: "o",
  231. optSpeed: " -O3 ",
  232. optSize: " -O1 ",
  233. compilerExe: "",
  234. cppCompiler: "",
  235. compileTmpl: "-c $ccenvflags $options $include -o $objfile $file",
  236. buildGui: "",
  237. buildDll: " -shared ",
  238. buildLib: "", # XXX: not supported yet
  239. linkerExe: "",
  240. linkTmpl: "-o $exefile $buildgui $builddll $objfiles $options",
  241. includeCmd: " -I",
  242. linkDirCmd: "", # XXX: not supported yet
  243. linkLibCmd: "", # XXX: not supported yet
  244. debug: "",
  245. pic: "",
  246. asmStmtFrmt: "__asm{$n$1$n}$n",
  247. structStmtFmt: "$1 $2",
  248. produceAsm: "",
  249. cppXsupport: "",
  250. props: {hasGnuAsm})
  251. const
  252. CC*: array[succ(low(TSystemCC))..high(TSystemCC), TInfoCC] = [
  253. gcc(),
  254. nintendoSwitchGCC(),
  255. llvmGcc(),
  256. clang(),
  257. bcc(),
  258. vcc(),
  259. tcc(),
  260. envcc(),
  261. icl(),
  262. icc(),
  263. clangcl()]
  264. hExt* = ".h"
  265. template writePrettyCmdsStderr(cmd) =
  266. if cmd.len > 0:
  267. flushDot(conf)
  268. stderr.writeLine(cmd)
  269. proc nameToCC*(name: string): TSystemCC =
  270. ## Returns the kind of compiler referred to by `name`, or ccNone
  271. ## if the name doesn't refer to any known compiler.
  272. for i in succ(ccNone)..high(TSystemCC):
  273. if cmpIgnoreStyle(name, CC[i].name) == 0:
  274. return i
  275. result = ccNone
  276. proc listCCnames(): string =
  277. result = ""
  278. for i in succ(ccNone)..high(TSystemCC):
  279. if i > succ(ccNone): result.add ", "
  280. result.add CC[i].name
  281. proc isVSCompatible*(conf: ConfigRef): bool =
  282. return conf.cCompiler == ccVcc or
  283. conf.cCompiler == ccClangCl or
  284. (conf.cCompiler == ccIcl and conf.target.hostOS in osDos..osWindows)
  285. proc getConfigVar(conf: ConfigRef; c: TSystemCC, suffix: string): string =
  286. # use ``cpu.os.cc`` for cross compilation, unless ``--compileOnly`` is given
  287. # for niminst support
  288. var fullSuffix = suffix
  289. case conf.backend
  290. of backendCpp, backendJs, backendObjc: fullSuffix = "." & $conf.backend & suffix
  291. of backendC, backendNir: discard
  292. of backendInvalid:
  293. # during parsing of cfg files; we don't know the backend yet, no point in
  294. # guessing wrong thing
  295. return ""
  296. if (conf.target.hostOS != conf.target.targetOS or conf.target.hostCPU != conf.target.targetCPU) and
  297. optCompileOnly notin conf.globalOptions:
  298. let fullCCname = platform.CPU[conf.target.targetCPU].name & '.' &
  299. platform.OS[conf.target.targetOS].name & '.' &
  300. CC[c].name & fullSuffix
  301. result = getConfigVar(conf, fullCCname)
  302. if existsConfigVar(conf, fullCCname):
  303. result = getConfigVar(conf, fullCCname)
  304. else:
  305. # not overridden for this cross compilation setting?
  306. result = getConfigVar(conf, CC[c].name & fullSuffix)
  307. else:
  308. result = getConfigVar(conf, CC[c].name & fullSuffix)
  309. proc setCC*(conf: ConfigRef; ccname: string; info: TLineInfo) =
  310. conf.cCompiler = nameToCC(ccname)
  311. if conf.cCompiler == ccNone:
  312. localError(conf, info, "unknown C compiler: '$1'. Available options are: $2" % [ccname, listCCnames()])
  313. conf.compileOptions = getConfigVar(conf, conf.cCompiler, ".options.always")
  314. conf.linkOptions = ""
  315. conf.cCompilerPath = getConfigVar(conf, conf.cCompiler, ".path")
  316. for c in CC: undefSymbol(conf.symbols, c.name)
  317. defineSymbol(conf.symbols, CC[conf.cCompiler].name)
  318. proc addOpt(dest: var string, src: string) =
  319. if dest.len == 0 or dest[^1] != ' ': dest.add(" ")
  320. dest.add(src)
  321. proc addLinkOption*(conf: ConfigRef; option: string) =
  322. addOpt(conf.linkOptions, option)
  323. proc addCompileOption*(conf: ConfigRef; option: string) =
  324. if strutils.find(conf.compileOptions, option, 0) < 0:
  325. addOpt(conf.compileOptions, option)
  326. proc addLinkOptionCmd*(conf: ConfigRef; option: string) =
  327. addOpt(conf.linkOptionsCmd, option)
  328. proc addCompileOptionCmd*(conf: ConfigRef; option: string) =
  329. conf.compileOptionsCmd.add(option)
  330. proc initVars*(conf: ConfigRef) =
  331. # we need to define the symbol here, because ``CC`` may have never been set!
  332. for c in CC: undefSymbol(conf.symbols, c.name)
  333. defineSymbol(conf.symbols, CC[conf.cCompiler].name)
  334. addCompileOption(conf, getConfigVar(conf, conf.cCompiler, ".options.always"))
  335. #addLinkOption(getConfigVar(cCompiler, ".options.linker"))
  336. if conf.cCompilerPath.len == 0:
  337. conf.cCompilerPath = getConfigVar(conf, conf.cCompiler, ".path")
  338. proc completeCfilePath*(conf: ConfigRef; cfile: AbsoluteFile,
  339. createSubDir: bool = true): AbsoluteFile =
  340. ## Generate the absolute file path to the generated modules.
  341. result = completeGeneratedFilePath(conf, cfile, createSubDir)
  342. proc toObjFile*(conf: ConfigRef; filename: AbsoluteFile): AbsoluteFile =
  343. # Object file for compilation
  344. result = AbsoluteFile(filename.string & "." & CC[conf.cCompiler].objExt)
  345. proc addFileToCompile*(conf: ConfigRef; cf: Cfile) =
  346. conf.toCompile.add(cf)
  347. proc addLocalCompileOption*(conf: ConfigRef; option: string; nimfile: AbsoluteFile) =
  348. let key = completeCfilePath(conf, mangleModuleName(conf, nimfile).AbsoluteFile).string
  349. var value = conf.cfileSpecificOptions.getOrDefault(key)
  350. if strutils.find(value, option, 0) < 0:
  351. addOpt(value, option)
  352. conf.cfileSpecificOptions[key] = value
  353. proc resetCompilationLists*(conf: ConfigRef) =
  354. conf.toCompile.setLen 0
  355. ## XXX: we must associate these with their originating module
  356. # when the module is loaded/unloaded it adds/removes its items
  357. # That's because we still need to hash check the external files
  358. # Maybe we can do that in checkDep on the other hand?
  359. conf.externalToLink.setLen 0
  360. proc addExternalFileToLink*(conf: ConfigRef; filename: AbsoluteFile) =
  361. conf.externalToLink.insert(filename.string, 0)
  362. proc execWithEcho(conf: ConfigRef; cmd: string, msg = hintExecuting): int =
  363. rawMessage(conf, msg, if msg == hintLinking and not(optListCmd in conf.globalOptions or conf.verbosity > 1): "" else: cmd)
  364. result = execCmd(cmd)
  365. proc execExternalProgram*(conf: ConfigRef; cmd: string, msg = hintExecuting) =
  366. if execWithEcho(conf, cmd, msg) != 0:
  367. rawMessage(conf, errGenerated, "execution of an external program failed: '$1'" %
  368. cmd)
  369. proc generateScript(conf: ConfigRef; script: Rope) =
  370. let (_, name, _) = splitFile(conf.outFile.string)
  371. let filename = getNimcacheDir(conf) / RelativeFile(addFileExt("compile_" & name,
  372. platform.OS[conf.target.targetOS].scriptExt))
  373. if not writeRope(script, filename):
  374. rawMessage(conf, errGenerated, "could not write to file: " & filename.string)
  375. proc getOptSpeed(conf: ConfigRef; c: TSystemCC): string =
  376. result = getConfigVar(conf, c, ".options.speed")
  377. if result == "":
  378. result = CC[c].optSpeed # use default settings from this file
  379. proc getDebug(conf: ConfigRef; c: TSystemCC): string =
  380. result = getConfigVar(conf, c, ".options.debug")
  381. if result == "":
  382. result = CC[c].debug # use default settings from this file
  383. proc getOptSize(conf: ConfigRef; c: TSystemCC): string =
  384. result = getConfigVar(conf, c, ".options.size")
  385. if result == "":
  386. result = CC[c].optSize # use default settings from this file
  387. proc noAbsolutePaths(conf: ConfigRef): bool {.inline.} =
  388. # We used to check current OS != specified OS, but this makes no sense
  389. # really: Cross compilation from Linux to Linux for example is entirely
  390. # reasonable.
  391. # `optGenMapping` is included here for niminst.
  392. # We use absolute paths for vcc / cl, see issue #19883.
  393. let options =
  394. if conf.cCompiler == ccVcc:
  395. {optGenMapping}
  396. else:
  397. {optGenScript, optGenMapping}
  398. result = conf.globalOptions * options != {}
  399. proc cFileSpecificOptions(conf: ConfigRef; nimname, fullNimFile: string): string =
  400. result = conf.compileOptions
  401. for option in conf.compileOptionsCmd:
  402. if strutils.find(result, option, 0) < 0:
  403. addOpt(result, option)
  404. if optCDebug in conf.globalOptions:
  405. let key = nimname & ".debug"
  406. if existsConfigVar(conf, key): addOpt(result, getConfigVar(conf, key))
  407. else: addOpt(result, getDebug(conf, conf.cCompiler))
  408. if optOptimizeSpeed in conf.options:
  409. let key = nimname & ".speed"
  410. if existsConfigVar(conf, key): addOpt(result, getConfigVar(conf, key))
  411. else: addOpt(result, getOptSpeed(conf, conf.cCompiler))
  412. elif optOptimizeSize in conf.options:
  413. let key = nimname & ".size"
  414. if existsConfigVar(conf, key): addOpt(result, getConfigVar(conf, key))
  415. else: addOpt(result, getOptSize(conf, conf.cCompiler))
  416. let key = nimname & ".always"
  417. if existsConfigVar(conf, key): addOpt(result, getConfigVar(conf, key))
  418. addOpt(result, conf.cfileSpecificOptions.getOrDefault(fullNimFile))
  419. proc getCompileOptions(conf: ConfigRef): string =
  420. result = cFileSpecificOptions(conf, "__dummy__", "__dummy__")
  421. proc vccplatform(conf: ConfigRef): string =
  422. # VCC specific but preferable over the config hacks people
  423. # had to do before, see #11306
  424. if conf.cCompiler == ccVcc:
  425. let exe = getConfigVar(conf, conf.cCompiler, ".exe")
  426. if "vccexe.exe" == extractFilename(exe):
  427. result = case conf.target.targetCPU
  428. of cpuI386: " --platform:x86"
  429. of cpuArm: " --platform:arm"
  430. of cpuAmd64: " --platform:amd64"
  431. else: ""
  432. else:
  433. result = ""
  434. else:
  435. result = ""
  436. proc getLinkOptions(conf: ConfigRef): string =
  437. result = conf.linkOptions & " " & conf.linkOptionsCmd & " "
  438. for linkedLib in items(conf.cLinkedLibs):
  439. result.add(CC[conf.cCompiler].linkLibCmd % linkedLib.quoteShell)
  440. for libDir in items(conf.cLibs):
  441. result.add(join([CC[conf.cCompiler].linkDirCmd, libDir.quoteShell]))
  442. proc needsExeExt(conf: ConfigRef): bool {.inline.} =
  443. result = (optGenScript in conf.globalOptions and conf.target.targetOS == osWindows) or
  444. (conf.target.hostOS == osWindows)
  445. proc useCpp(conf: ConfigRef; cfile: AbsoluteFile): bool =
  446. # List of possible file extensions taken from gcc
  447. for ext in [".C", ".cc", ".cpp", ".CPP", ".c++", ".cp", ".cxx"]:
  448. if cfile.string.endsWith(ext): return true
  449. false
  450. proc envFlags(conf: ConfigRef): string =
  451. result = if conf.backend == backendCpp:
  452. getEnv("CXXFLAGS")
  453. else:
  454. getEnv("CFLAGS")
  455. proc getCompilerExe(conf: ConfigRef; compiler: TSystemCC; isCpp: bool): string =
  456. if compiler == ccEnv:
  457. result = if isCpp:
  458. getEnv("CXX")
  459. else:
  460. getEnv("CC")
  461. else:
  462. result = if isCpp:
  463. CC[compiler].cppCompiler
  464. else:
  465. CC[compiler].compilerExe
  466. if result.len == 0:
  467. rawMessage(conf, errGenerated,
  468. "Compiler '$1' doesn't support the requested target" %
  469. CC[compiler].name)
  470. proc ccHasSaneOverflow*(conf: ConfigRef): bool =
  471. if conf.cCompiler == ccGcc:
  472. result = false # assume an old or crappy GCC
  473. var exe = getConfigVar(conf, conf.cCompiler, ".exe")
  474. if exe.len == 0: exe = CC[conf.cCompiler].compilerExe
  475. # NOTE: should we need the full version, use -dumpfullversion
  476. let (s, exitCode) = try: execCmdEx(exe & " -dumpversion") except IOError, OSError, ValueError: ("", 1)
  477. if exitCode == 0:
  478. var major: int = 0
  479. discard parseInt(s, major)
  480. result = major >= 5
  481. else:
  482. result = conf.cCompiler == ccCLang
  483. proc getLinkerExe(conf: ConfigRef; compiler: TSystemCC): string =
  484. result = if CC[compiler].linkerExe.len > 0: CC[compiler].linkerExe
  485. else: getCompilerExe(conf, compiler, optMixedMode in conf.globalOptions or conf.backend == backendCpp)
  486. proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile,
  487. isMainFile = false; produceOutput = false): string =
  488. let
  489. c = conf.cCompiler
  490. isCpp = useCpp(conf, cfile.cname)
  491. # We produce files like module.nim.cpp, so the absolute Nim filename is not
  492. # cfile.name but `cfile.cname.changeFileExt("")`:
  493. var options = cFileSpecificOptions(conf, cfile.nimname, cfile.cname.changeFileExt("").string)
  494. if isCpp:
  495. # needs to be prepended so that --passc:-std=c++17 can override default.
  496. # we could avoid allocation by making cFileSpecificOptions inplace
  497. options = CC[c].cppXsupport & ' ' & options
  498. # If any C++ file was compiled, we need to use C++ driver for linking as well
  499. incl conf.globalOptions, optMixedMode
  500. var exe = getConfigVar(conf, c, ".exe")
  501. if exe.len == 0: exe = getCompilerExe(conf, c, isCpp)
  502. if needsExeExt(conf): exe = addFileExt(exe, "exe")
  503. if (optGenDynLib in conf.globalOptions or (conf.hcrOn and not isMainFile)) and
  504. ospNeedsPIC in platform.OS[conf.target.targetOS].props:
  505. options.add(' ' & CC[c].pic)
  506. if cfile.customArgs != "":
  507. options.add ' '
  508. options.add cfile.customArgs
  509. var compilePattern: string
  510. # compute include paths:
  511. var includeCmd = CC[c].includeCmd & quoteShell(conf.libpath)
  512. if not noAbsolutePaths(conf):
  513. for includeDir in items(conf.cIncludes):
  514. includeCmd.add(join([CC[c].includeCmd, includeDir.quoteShell]))
  515. compilePattern = joinPath(conf.cCompilerPath, exe)
  516. else:
  517. compilePattern = exe
  518. includeCmd.add(join([CC[c].includeCmd, quoteShell(conf.projectPath.string)]))
  519. let cf = if noAbsolutePaths(conf): AbsoluteFile extractFilename(cfile.cname.string)
  520. else: cfile.cname
  521. let objfile =
  522. if cfile.obj.isEmpty:
  523. if CfileFlag.External notin cfile.flags or noAbsolutePaths(conf):
  524. toObjFile(conf, cf).string
  525. else:
  526. completeCfilePath(conf, toObjFile(conf, cf)).string
  527. elif noAbsolutePaths(conf):
  528. extractFilename(cfile.obj.string)
  529. else:
  530. cfile.obj.string
  531. # D files are required by nintendo switch libs for
  532. # compilation. They are basically a list of all includes.
  533. let dfile = objfile.changeFileExt(".d").quoteShell
  534. let cfsh = quoteShell(cf)
  535. result = quoteShell(compilePattern % [
  536. "dfile", dfile,
  537. "file", cfsh, "objfile", quoteShell(objfile), "options", options,
  538. "include", includeCmd, "nim", getPrefixDir(conf).string,
  539. "lib", conf.libpath.string,
  540. "ccenvflags", envFlags(conf)])
  541. if optProduceAsm in conf.globalOptions:
  542. if CC[conf.cCompiler].produceAsm.len > 0:
  543. let asmfile = objfile.changeFileExt(".asm").quoteShell
  544. addOpt(result, CC[conf.cCompiler].produceAsm % ["asmfile", asmfile])
  545. if produceOutput:
  546. rawMessage(conf, hintUserRaw, "Produced assembler here: " & asmfile)
  547. else:
  548. if produceOutput:
  549. rawMessage(conf, hintUserRaw, "Couldn't produce assembler listing " &
  550. "for the selected C compiler: " & CC[conf.cCompiler].name)
  551. result.add(' ')
  552. strutils.addf(result, CC[c].compileTmpl, [
  553. "dfile", dfile,
  554. "file", cfsh, "objfile", quoteShell(objfile),
  555. "options", options, "include", includeCmd,
  556. "nim", quoteShell(getPrefixDir(conf)),
  557. "lib", quoteShell(conf.libpath),
  558. "vccplatform", vccplatform(conf),
  559. "ccenvflags", envFlags(conf)])
  560. proc footprint(conf: ConfigRef; cfile: Cfile): SecureHash =
  561. result = secureHash(
  562. $secureHashFile(cfile.cname.string) &
  563. platform.OS[conf.target.targetOS].name &
  564. platform.CPU[conf.target.targetCPU].name &
  565. extccomp.CC[conf.cCompiler].name &
  566. getCompileCFileCmd(conf, cfile))
  567. proc externalFileChanged(conf: ConfigRef; cfile: Cfile): bool =
  568. if conf.backend == backendJs: return false # pre-existing behavior, but not sure it's good
  569. let hashFile = toGeneratedFile(conf, conf.mangleModuleName(cfile.cname).AbsoluteFile, "sha1")
  570. let currentHash = footprint(conf, cfile)
  571. var f: File = default(File)
  572. if open(f, hashFile.string, fmRead):
  573. let oldHash = parseSecureHash(f.readLine())
  574. close(f)
  575. result = oldHash != currentHash
  576. else:
  577. result = true
  578. if result:
  579. if open(f, hashFile.string, fmWrite):
  580. f.writeLine($currentHash)
  581. close(f)
  582. proc addExternalFileToCompile*(conf: ConfigRef; c: var Cfile) =
  583. # we want to generate the hash file unconditionally
  584. let extFileChanged = externalFileChanged(conf, c)
  585. if optForceFullMake notin conf.globalOptions and fileExists(c.obj) and
  586. not extFileChanged:
  587. c.flags.incl CfileFlag.Cached
  588. else:
  589. # make sure Nim keeps recompiling the external file on reruns
  590. # if compilation is not successful
  591. discard tryRemoveFile(c.obj.string)
  592. conf.toCompile.add(c)
  593. proc addExternalFileToCompile*(conf: ConfigRef; filename: AbsoluteFile) =
  594. var c = Cfile(nimname: splitFile(filename).name, cname: filename,
  595. obj: toObjFile(conf, completeCfilePath(conf, filename, false)),
  596. flags: {CfileFlag.External})
  597. addExternalFileToCompile(conf, c)
  598. proc getLinkCmd(conf: ConfigRef; output: AbsoluteFile,
  599. objfiles: string, isDllBuild: bool, removeStaticFile: bool): string =
  600. if optGenStaticLib in conf.globalOptions:
  601. if removeStaticFile:
  602. removeFile output # fixes: bug #16947
  603. result = CC[conf.cCompiler].buildLib % ["libfile", quoteShell(output),
  604. "objfiles", objfiles,
  605. "vccplatform", vccplatform(conf)]
  606. else:
  607. var linkerExe = getConfigVar(conf, conf.cCompiler, ".linkerexe")
  608. if linkerExe.len == 0: linkerExe = getLinkerExe(conf, conf.cCompiler)
  609. # bug #6452: We must not use ``quoteShell`` here for ``linkerExe``
  610. if needsExeExt(conf): linkerExe = addFileExt(linkerExe, "exe")
  611. if noAbsolutePaths(conf): result = linkerExe
  612. else: result = joinPath(conf.cCompilerPath, linkerExe)
  613. let buildgui = if optGenGuiApp in conf.globalOptions and conf.target.targetOS == osWindows:
  614. CC[conf.cCompiler].buildGui
  615. else:
  616. ""
  617. let builddll = if isDllBuild: CC[conf.cCompiler].buildDll else: ""
  618. let exefile = quoteShell(output)
  619. when false:
  620. if optCDebug in conf.globalOptions:
  621. writeDebugInfo(exefile.changeFileExt("ndb"))
  622. # Map files are required by Nintendo Switch compilation. They are a list
  623. # of all function calls in the library and where they come from.
  624. let mapfile = quoteShell(getNimcacheDir(conf) / RelativeFile(splitFile(output).name & ".map"))
  625. let linkOptions = getLinkOptions(conf) & " " &
  626. getConfigVar(conf, conf.cCompiler, ".options.linker")
  627. var linkTmpl = getConfigVar(conf, conf.cCompiler, ".linkTmpl")
  628. if linkTmpl.len == 0:
  629. linkTmpl = CC[conf.cCompiler].linkTmpl
  630. result = quoteShell(result % ["builddll", builddll,
  631. "mapfile", mapfile,
  632. "buildgui", buildgui, "options", linkOptions, "objfiles", objfiles,
  633. "exefile", exefile, "nim", getPrefixDir(conf).string, "lib", conf.libpath.string])
  634. result.add ' '
  635. strutils.addf(result, linkTmpl, ["builddll", builddll,
  636. "mapfile", mapfile,
  637. "buildgui", buildgui, "options", linkOptions,
  638. "objfiles", objfiles, "exefile", exefile,
  639. "nim", quoteShell(getPrefixDir(conf)),
  640. "lib", quoteShell(conf.libpath),
  641. "vccplatform", vccplatform(conf)])
  642. # On windows the debug information for binaries is emitted in a separate .pdb
  643. # file and the binaries (.dll and .exe) contain a full path to that .pdb file.
  644. # This is a problem for hot code reloading because even when we copy the .dll
  645. # and load the copy so the build process may overwrite the original .dll on
  646. # the disk (windows locks the files of running binaries) the copy still points
  647. # to the original .pdb (and a simple copy of the .pdb won't help). This is a
  648. # problem when a debugger is attached to the program we are hot-reloading.
  649. # This problem is nonexistent on Unix since there by default debug symbols
  650. # are embedded in the binaries so loading a copy of a .so will be fine. There
  651. # is the '/Z7' flag for the MSVC compiler to embed the debug info of source
  652. # files into their respective .obj files but the linker still produces a .pdb
  653. # when a final .dll or .exe is linked so the debug info isn't embedded.
  654. # There is also the issue that even when a .dll is unloaded the debugger
  655. # still keeps the .pdb for that .dll locked. This is a major problem and
  656. # because of this we cannot just alternate between 2 names for a .pdb file
  657. # when rebuilding a .dll - instead we need to accumulate differently named
  658. # .pdb files in the nimcache folder - this is the easiest and most reliable
  659. # way of being able to debug and rebuild the program at the same time. This
  660. # is accomplished using the /PDB:<filename> flag (there also exists the
  661. # /PDBALTPATH:<filename> flag). The only downside is that the .pdb files are
  662. # at least 300kb big (when linking statically to the runtime - or else 5mb+)
  663. # and will quickly accumulate. There is a hacky solution: we could try to
  664. # delete all .pdb files with a pattern and swallow exceptions.
  665. #
  666. # links about .pdb files and hot code reloading:
  667. # https://ourmachinery.com/post/dll-hot-reloading-in-theory-and-practice/
  668. # https://ourmachinery.com/post/little-machines-working-together-part-2/
  669. # https://github.com/fungos/cr
  670. # https://fungos.github.io/blog/2017/11/20/cr.h-a-simple-c-hot-reload-header-only-library/
  671. # on forcing the debugger to unlock a locked .pdb of an unloaded library:
  672. # https://blog.molecular-matters.com/2017/05/09/deleting-pdb-files-locked-by-visual-studio/
  673. # and a bit about the .pdb format in case that is ever needed:
  674. # https://github.com/crosire/blink
  675. # http://www.debuginfo.com/articles/debuginfomatch.html#pdbfiles
  676. if conf.hcrOn and isVSCompatible(conf):
  677. let t = now()
  678. let pdb = output.string & "." & format(t, "MMMM-yyyy-HH-mm-") & $t.nanosecond & ".pdb"
  679. result.add " /link /PDB:" & pdb
  680. if optCDebug in conf.globalOptions and conf.cCompiler == ccVcc:
  681. result.add " /Zi /FS /Od"
  682. template getLinkCmd(conf: ConfigRef; output: AbsoluteFile, objfiles: string,
  683. removeStaticFile = false): string =
  684. getLinkCmd(conf, output, objfiles, optGenDynLib in conf.globalOptions, removeStaticFile)
  685. template tryExceptOSErrorMessage(conf: ConfigRef; errorPrefix: string = "", body: untyped) =
  686. try:
  687. body
  688. except OSError:
  689. let ose = (ref OSError)(getCurrentException())
  690. if errorPrefix.len > 0:
  691. rawMessage(conf, errGenerated, errorPrefix & " " & ose.msg & " " & $ose.errorCode)
  692. else:
  693. rawMessage(conf, errGenerated, "execution of an external program failed: '$1'" %
  694. (ose.msg & " " & $ose.errorCode))
  695. raise
  696. proc getExtraCmds(conf: ConfigRef; output: AbsoluteFile): seq[string] =
  697. result = @[]
  698. when defined(macosx):
  699. if optCDebug in conf.globalOptions and optGenStaticLib notin conf.globalOptions:
  700. # if needed, add an option to skip or override location
  701. result.add "dsymutil " & $(output).quoteShell
  702. proc execLinkCmd(conf: ConfigRef; linkCmd: string) =
  703. tryExceptOSErrorMessage(conf, "invocation of external linker program failed."):
  704. execExternalProgram(conf, linkCmd, hintLinking)
  705. proc execCmdsInParallel(conf: ConfigRef; cmds: seq[string]; prettyCb: proc (idx: int)) =
  706. let runCb = proc (idx: int, p: Process) =
  707. let exitCode = p.peekExitCode
  708. if exitCode != 0:
  709. rawMessage(conf, errGenerated, "execution of an external compiler program '" &
  710. cmds[idx] & "' failed with exit code: " & $exitCode & "\n\n")
  711. if conf.numberOfProcessors == 0: conf.numberOfProcessors = countProcessors()
  712. var res = 0
  713. if conf.numberOfProcessors <= 1:
  714. for i in 0..high(cmds):
  715. tryExceptOSErrorMessage(conf, "invocation of external compiler program failed."):
  716. res = execWithEcho(conf, cmds[i])
  717. if res != 0:
  718. rawMessage(conf, errGenerated, "execution of an external program failed: '$1'" %
  719. cmds[i])
  720. else:
  721. tryExceptOSErrorMessage(conf, "invocation of external compiler program failed."):
  722. res = execProcesses(cmds, {poStdErrToStdOut, poUsePath, poParentStreams},
  723. conf.numberOfProcessors, prettyCb, afterRunEvent=runCb)
  724. if res != 0:
  725. if conf.numberOfProcessors <= 1:
  726. rawMessage(conf, errGenerated, "execution of an external program failed: '$1'" %
  727. cmds.join())
  728. proc linkViaResponseFile(conf: ConfigRef; cmd: string) =
  729. # Extracting the linker.exe here is a bit hacky but the best solution
  730. # given ``buildLib``'s design.
  731. var i = 0
  732. var last = 0
  733. if cmd.len > 0 and cmd[0] == '"':
  734. inc i
  735. while i < cmd.len and cmd[i] != '"': inc i
  736. last = i
  737. inc i
  738. else:
  739. while i < cmd.len and cmd[i] != ' ': inc i
  740. last = i
  741. while i < cmd.len and cmd[i] == ' ': inc i
  742. let linkerArgs = conf.projectName & "_" & "linkerArgs.txt"
  743. let args = cmd.substr(i)
  744. # GCC's response files don't support backslashes. Junk.
  745. if conf.cCompiler == ccGcc or conf.cCompiler == ccCLang:
  746. writeFile(linkerArgs, args.replace('\\', '/'))
  747. else:
  748. writeFile(linkerArgs, args)
  749. try:
  750. when defined(macosx):
  751. execLinkCmd(conf, "xargs " & cmd.substr(0, last) & " < " & linkerArgs)
  752. else:
  753. execLinkCmd(conf, cmd.substr(0, last) & " @" & linkerArgs)
  754. finally:
  755. removeFile(linkerArgs)
  756. proc linkViaShellScript(conf: ConfigRef; cmd: string) =
  757. let linkerScript = conf.projectName & "_" & "linkerScript.sh"
  758. writeFile(linkerScript, cmd)
  759. let shell = getEnv("SHELL")
  760. try:
  761. execLinkCmd(conf, shell & " " & linkerScript)
  762. finally:
  763. removeFile(linkerScript)
  764. proc getObjFilePath(conf: ConfigRef, f: Cfile): string =
  765. if noAbsolutePaths(conf): f.obj.extractFilename
  766. else: f.obj.string
  767. proc hcrLinkTargetName(conf: ConfigRef, objFile: string, isMain = false): AbsoluteFile =
  768. let basename = splitFile(objFile).name
  769. let targetName = if isMain: basename & ".exe"
  770. else: platform.OS[conf.target.targetOS].dllFrmt % basename
  771. result = conf.getNimcacheDir / RelativeFile(targetName)
  772. proc displayProgressCC(conf: ConfigRef, path, compileCmd: string): string =
  773. result = ""
  774. if conf.hasHint(hintCC):
  775. if optListCmd in conf.globalOptions or conf.verbosity > 1:
  776. result = MsgKindToStr[hintCC] % (demangleModuleName(path.splitFile.name) & ": " & compileCmd)
  777. else:
  778. result = MsgKindToStr[hintCC] % demangleModuleName(path.splitFile.name)
  779. proc preventLinkCmdMaxCmdLen(conf: ConfigRef, linkCmd: string) =
  780. # Prevent linkcmd from exceeding the maximum command line length.
  781. # Windows's command line limit is about 8K (8191 characters) so C compilers on
  782. # Windows support a feature where the command line can be passed via ``@linkcmd``
  783. # to them.
  784. const MaxCmdLen = when defined(windows): 8_000 elif defined(macosx): 260_000 else: 32_000
  785. if linkCmd.len > MaxCmdLen:
  786. when defined(macosx):
  787. linkViaShellScript(conf, linkCmd)
  788. else:
  789. linkViaResponseFile(conf, linkCmd)
  790. else:
  791. execLinkCmd(conf, linkCmd)
  792. proc callCCompiler*(conf: ConfigRef) =
  793. var
  794. linkCmd: string = ""
  795. extraCmds: seq[string]
  796. if conf.globalOptions * {optCompileOnly, optGenScript} == {optCompileOnly}:
  797. return # speed up that call if only compiling and no script shall be
  798. # generated
  799. #var c = cCompiler
  800. var script: Rope = ""
  801. var cmds: TStringSeq = default(TStringSeq)
  802. var prettyCmds: TStringSeq = default(TStringSeq)
  803. let prettyCb = proc (idx: int) = writePrettyCmdsStderr(prettyCmds[idx])
  804. for idx, it in conf.toCompile:
  805. # call the C compiler for the .c file:
  806. if CfileFlag.Cached in it.flags: continue
  807. let compileCmd = getCompileCFileCmd(conf, it, idx == conf.toCompile.len - 1, produceOutput=true)
  808. if optCompileOnly notin conf.globalOptions:
  809. cmds.add(compileCmd)
  810. prettyCmds.add displayProgressCC(conf, $it.cname, compileCmd)
  811. if optGenScript in conf.globalOptions:
  812. script.add(compileCmd)
  813. script.add("\n")
  814. if optCompileOnly notin conf.globalOptions:
  815. execCmdsInParallel(conf, cmds, prettyCb)
  816. if optNoLinking notin conf.globalOptions:
  817. # call the linker:
  818. var objfiles = ""
  819. for it in conf.externalToLink:
  820. let objFile = if noAbsolutePaths(conf): it.extractFilename else: it
  821. objfiles.add(' ')
  822. objfiles.add(quoteShell(
  823. addFileExt(objFile, CC[conf.cCompiler].objExt)))
  824. if conf.hcrOn: # lets assume that optCompileOnly isn't on
  825. cmds = @[]
  826. let mainFileIdx = conf.toCompile.len - 1
  827. for idx, x in conf.toCompile:
  828. # don't relink each of the many binaries (one for each source file) if the nim code is
  829. # cached because that would take too much time for small changes - the only downside to
  830. # this is that if an external-to-link file changes the final target wouldn't be relinked
  831. if CfileFlag.Cached in x.flags: continue
  832. # we pass each object file as if it is the project file - a .dll will be created for each such
  833. # object file in the nimcache directory, and only in the case of the main project file will
  834. # there be probably an executable (if the project is such) which will be copied out of the nimcache
  835. let objFile = conf.getObjFilePath(x)
  836. let buildDll = idx != mainFileIdx
  837. let linkTarget = conf.hcrLinkTargetName(objFile, not buildDll)
  838. cmds.add(getLinkCmd(conf, linkTarget, objfiles & " " & quoteShell(objFile), buildDll, removeStaticFile = true))
  839. # try to remove all .pdb files for the current binary so they don't accumulate endlessly in the nimcache
  840. # for more info check the comment inside of getLinkCmd() where the /PDB:<filename> MSVC flag is used
  841. if isVSCompatible(conf):
  842. for pdb in walkFiles(objFile & ".*.pdb"):
  843. discard tryRemoveFile(pdb)
  844. # execute link commands in parallel - output will be a bit different
  845. # if it fails than that from execLinkCmd() but that doesn't matter
  846. prettyCmds = map(prettyCmds, proc (curr: string): string = return curr.replace("CC", "Link"))
  847. execCmdsInParallel(conf, cmds, prettyCb)
  848. # only if not cached - copy the resulting main file from the nimcache folder to its originally intended destination
  849. if CfileFlag.Cached notin conf.toCompile[mainFileIdx].flags:
  850. let mainObjFile = getObjFilePath(conf, conf.toCompile[mainFileIdx])
  851. let src = conf.hcrLinkTargetName(mainObjFile, true)
  852. let dst = conf.prepareToWriteOutput
  853. copyFileWithPermissions(src.string, dst.string)
  854. else:
  855. for x in conf.toCompile:
  856. let objFile = if noAbsolutePaths(conf): x.obj.extractFilename else: x.obj.string
  857. objfiles.add(' ')
  858. objfiles.add(quoteShell(objFile))
  859. let mainOutput = if optGenScript notin conf.globalOptions: conf.prepareToWriteOutput
  860. else: AbsoluteFile(conf.outFile)
  861. linkCmd = getLinkCmd(conf, mainOutput, objfiles, removeStaticFile = true)
  862. extraCmds = getExtraCmds(conf, mainOutput)
  863. if optCompileOnly notin conf.globalOptions:
  864. preventLinkCmdMaxCmdLen(conf, linkCmd)
  865. for cmd in extraCmds:
  866. execExternalProgram(conf, cmd, hintExecuting)
  867. else:
  868. linkCmd = ""
  869. if optGenScript in conf.globalOptions:
  870. script.add(linkCmd)
  871. script.add("\n")
  872. generateScript(conf, script)
  873. template hashNimExe(): string = $secureHashFile(os.getAppFilename())
  874. proc jsonBuildInstructionsFile*(conf: ConfigRef): AbsoluteFile =
  875. # `outFile` is better than `projectName`, as it allows having different json
  876. # files for a given source file compiled with different options; it also
  877. # works out of the box with `hashMainCompilationParams`.
  878. result = getNimcacheDir(conf) / conf.outFile.changeFileExt("json")
  879. const cacheVersion = "D20210525T193831" # update when `BuildCache` spec changes
  880. type BuildCache = object
  881. cacheVersion: string
  882. outputFile: string
  883. compile: seq[(string, string)]
  884. link: seq[string]
  885. linkcmd: string
  886. extraCmds: seq[string]
  887. configFiles: seq[string] # the hash shouldn't be needed
  888. stdinInput: bool
  889. projectIsCmd: bool
  890. cmdInput: string
  891. currentDir: string
  892. cmdline: string
  893. depfiles: seq[(string, string)]
  894. nimexe: string
  895. proc writeJsonBuildInstructions*(conf: ConfigRef; deps: StringTableRef) =
  896. var linkFiles = collect(for it in conf.externalToLink:
  897. var it = it
  898. if conf.noAbsolutePaths: it = it.extractFilename
  899. it.addFileExt(CC[conf.cCompiler].objExt))
  900. for it in conf.toCompile: linkFiles.add it.obj.string
  901. var bcache = BuildCache(
  902. cacheVersion: cacheVersion,
  903. outputFile: conf.absOutFile.string,
  904. compile: collect(for i, it in conf.toCompile:
  905. if CfileFlag.Cached notin it.flags: (it.cname.string, getCompileCFileCmd(conf, it))),
  906. link: linkFiles,
  907. linkcmd: getLinkCmd(conf, conf.absOutFile, linkFiles.quoteShellCommand),
  908. extraCmds: getExtraCmds(conf, conf.absOutFile),
  909. stdinInput: conf.projectIsStdin,
  910. projectIsCmd: conf.projectIsCmd,
  911. cmdInput: conf.cmdInput,
  912. configFiles: conf.configFiles.mapIt(it.string),
  913. currentDir: getCurrentDir())
  914. if optRun in conf.globalOptions or isDefined(conf, "nimBetterRun"):
  915. bcache.cmdline = conf.commandLine
  916. for it in conf.m.fileInfos:
  917. let path = it.fullPath.string
  918. if isAbsolute(path): # TODO: else?
  919. if path in deps:
  920. bcache.depfiles.add (path, deps[path])
  921. else: # backup for configs etc.
  922. bcache.depfiles.add (path, $secureHashFile(path))
  923. bcache.nimexe = hashNimExe()
  924. conf.jsonBuildFile = conf.jsonBuildInstructionsFile
  925. conf.jsonBuildFile.string.writeFile(bcache.toJson.pretty)
  926. proc changeDetectedViaJsonBuildInstructions*(conf: ConfigRef; jsonFile: AbsoluteFile): bool =
  927. result = false
  928. if not fileExists(jsonFile) or not fileExists(conf.absOutFile): return true
  929. var bcache: BuildCache = default(BuildCache)
  930. try: bcache.fromJson(jsonFile.string.parseFile)
  931. except IOError, OSError, ValueError:
  932. stderr.write "Warning: JSON processing failed for: $#\n" % jsonFile.string
  933. return true
  934. if bcache.currentDir != getCurrentDir() or # fixes bug #16271
  935. bcache.configFiles != conf.configFiles.mapIt(it.string) or
  936. bcache.cacheVersion != cacheVersion or bcache.outputFile != conf.absOutFile.string or
  937. bcache.cmdline != conf.commandLine or bcache.nimexe != hashNimExe() or
  938. bcache.projectIsCmd != conf.projectIsCmd or conf.cmdInput != bcache.cmdInput: return true
  939. if bcache.stdinInput or conf.projectIsStdin: return true
  940. # xxx optimize by returning false if stdin input was the same
  941. for (file, hash) in bcache.depfiles:
  942. if $secureHashFile(file) != hash: return true
  943. proc runJsonBuildInstructions*(conf: ConfigRef; jsonFile: AbsoluteFile) =
  944. var bcache: BuildCache = default(BuildCache)
  945. try: bcache.fromJson(jsonFile.string.parseFile)
  946. except ValueError, KeyError, JsonKindError:
  947. let e = getCurrentException()
  948. conf.quitOrRaise "\ncaught exception:\n$#\nstacktrace:\n$#error evaluating JSON file: $#" %
  949. [e.msg, e.getStackTrace(), jsonFile.string]
  950. let output = bcache.outputFile
  951. createDir output.parentDir
  952. let outputCurrent = $conf.absOutFile
  953. if output != outputCurrent or bcache.cacheVersion != cacheVersion:
  954. globalError(conf, gCmdLineInfo,
  955. "jsonscript command outputFile '$1' must match '$2' which was specified during --compileOnly, see \"outputFile\" entry in '$3' " %
  956. [outputCurrent, output, jsonFile.string])
  957. var cmds: TStringSeq = default(TStringSeq)
  958. var prettyCmds: TStringSeq= default(TStringSeq)
  959. let prettyCb = proc (idx: int) = writePrettyCmdsStderr(prettyCmds[idx])
  960. for (name, cmd) in bcache.compile:
  961. cmds.add cmd
  962. prettyCmds.add displayProgressCC(conf, name, cmd)
  963. execCmdsInParallel(conf, cmds, prettyCb)
  964. preventLinkCmdMaxCmdLen(conf, bcache.linkcmd)
  965. for cmd in bcache.extraCmds: execExternalProgram(conf, cmd, hintExecuting)
  966. proc genMappingFiles(conf: ConfigRef; list: CfileList): Rope =
  967. result = ""
  968. for it in list:
  969. result.addf("--file:r\"$1\"$N", [rope(it.cname.string)])
  970. proc writeMapping*(conf: ConfigRef; symbolMapping: Rope) =
  971. if optGenMapping notin conf.globalOptions: return
  972. var code = rope("[C_Files]\n")
  973. code.add(genMappingFiles(conf, conf.toCompile))
  974. code.add("\n[C_Compiler]\nFlags=")
  975. code.add(strutils.escape(getCompileOptions(conf)))
  976. code.add("\n[Linker]\nFlags=")
  977. code.add(strutils.escape(getLinkOptions(conf) & " " &
  978. getConfigVar(conf, conf.cCompiler, ".options.linker")))
  979. code.add("\n[Environment]\nlibpath=")
  980. code.add(strutils.escape(conf.libpath.string))
  981. code.addf("\n[Symbols]$n$1", [symbolMapping])
  982. let filename = conf.projectPath / RelativeFile"mapping.txt"
  983. if not writeRope(code, filename):
  984. rawMessage(conf, errGenerated, "could not write to file: " & filename.string)