extccomp.nim 44 KB

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