extccomp.nim 43 KB

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