extccomp.nim 44 KB

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