extccomp.nim 44 KB

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