extccomp.nim 43 KB

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