extccomp.nim 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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
  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. props: TInfoCCProps] # properties of the C compiler
  49. # Configuration settings for various compilers.
  50. # When adding new compilers, the cmake sources could be a good reference:
  51. # http://cmake.org/gitweb?p=cmake.git;a=tree;f=Modules/Platform;
  52. template compiler(name, settings: untyped): untyped =
  53. proc name: TInfoCC {.compileTime.} = settings
  54. # GNU C and C++ Compiler
  55. compiler gcc:
  56. result = (
  57. name: "gcc",
  58. objExt: "o",
  59. optSpeed: " -O3 -ffast-math ",
  60. optSize: " -Os -ffast-math ",
  61. compilerExe: "gcc",
  62. cppCompiler: "g++",
  63. compileTmpl: "-c $options $include -o $objfile $file",
  64. buildGui: " -mwindows",
  65. buildDll: " -shared",
  66. buildLib: "ar rcs $libfile $objfiles",
  67. linkerExe: "",
  68. linkTmpl: "$buildgui $builddll -o $exefile $objfiles $options",
  69. includeCmd: " -I",
  70. linkDirCmd: " -L",
  71. linkLibCmd: " -l$1",
  72. debug: "",
  73. pic: "-fPIC",
  74. asmStmtFrmt: "asm($1);$n",
  75. structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name
  76. props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm,
  77. hasAttribute})
  78. # GNU C and C++ Compiler
  79. compiler nintendoSwitchGCC:
  80. result = (
  81. name: "switch_gcc",
  82. objExt: "o",
  83. optSpeed: " -O3 -ffast-math ",
  84. optSize: " -Os -ffast-math ",
  85. compilerExe: "aarch64-none-elf-gcc",
  86. cppCompiler: "aarch64-none-elf-g++",
  87. compileTmpl: "-w -MMD -MP -MF $dfile -c $options $include -o $objfile $file",
  88. buildGui: " -mwindows",
  89. buildDll: " -shared",
  90. buildLib: "aarch64-none-elf-gcc-ar rcs $libfile $objfiles",
  91. linkerExe: "aarch64-none-elf-gcc",
  92. linkTmpl: "$buildgui $builddll -Wl,-Map,$mapfile -o $exefile $objfiles $options",
  93. includeCmd: " -I",
  94. linkDirCmd: " -L",
  95. linkLibCmd: " -l$1",
  96. debug: "",
  97. pic: "-fPIE",
  98. asmStmtFrmt: "asm($1);$n",
  99. structStmtFmt: "$1 $3 $2 ", # struct|union [packed] $name
  100. props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard, hasGnuAsm,
  101. hasAttribute})
  102. # LLVM Frontend for GCC/G++
  103. compiler llvmGcc:
  104. result = gcc() # Uses settings from GCC
  105. result.name = "llvm_gcc"
  106. result.compilerExe = "llvm-gcc"
  107. result.cppCompiler = "llvm-g++"
  108. when defined(macosx):
  109. # OS X has no 'llvm-ar' tool:
  110. result.buildLib = "ar rcs $libfile $objfiles"
  111. else:
  112. result.buildLib = "llvm-ar rcs $libfile $objfiles"
  113. # Clang (LLVM) C/C++ Compiler
  114. compiler clang:
  115. result = llvmGcc() # Uses settings from llvmGcc
  116. result.name = "clang"
  117. result.compilerExe = "clang"
  118. result.cppCompiler = "clang++"
  119. # Microsoft Visual C/C++ Compiler
  120. compiler vcc:
  121. result = (
  122. name: "vcc",
  123. objExt: "obj",
  124. optSpeed: " /Ogityb2 /G7 ",
  125. optSize: " /O1 /G7 ",
  126. compilerExe: "cl",
  127. cppCompiler: "cl",
  128. compileTmpl: "/c $options $include /Fo$objfile $file",
  129. buildGui: " /link /SUBSYSTEM:WINDOWS ",
  130. buildDll: " /LD",
  131. buildLib: "lib /OUT:$libfile $objfiles",
  132. linkerExe: "cl",
  133. linkTmpl: "$options $builddll /Fe$exefile $objfiles $buildgui",
  134. includeCmd: " /I",
  135. linkDirCmd: " /LIBPATH:",
  136. linkLibCmd: " $1.lib",
  137. debug: " /RTC1 /Z7 ",
  138. pic: "",
  139. asmStmtFrmt: "__asm{$n$1$n}$n",
  140. structStmtFmt: "$3$n$1 $2",
  141. props: {hasCpp, hasAssume, hasDeclspec})
  142. compiler clangcl:
  143. result = vcc()
  144. result.name = "clang_cl"
  145. result.compilerExe = "clang-cl"
  146. result.cppCompiler = "clang-cl"
  147. result.linkerExe = "clang-cl"
  148. # Intel C/C++ Compiler
  149. compiler icl:
  150. result = vcc()
  151. result.name = "icl"
  152. result.compilerExe = "icl"
  153. result.linkerExe = "icl"
  154. # Intel compilers try to imitate the native ones (gcc and msvc)
  155. compiler icc:
  156. result = gcc()
  157. result.name = "icc"
  158. result.compilerExe = "icc"
  159. result.linkerExe = "icc"
  160. # Local C Compiler
  161. compiler lcc:
  162. result = (
  163. name: "lcc",
  164. objExt: "obj",
  165. optSpeed: " -O -p6 ",
  166. optSize: " -O -p6 ",
  167. compilerExe: "lcc",
  168. cppCompiler: "",
  169. compileTmpl: "$options $include -Fo$objfile $file",
  170. buildGui: " -subsystem windows",
  171. buildDll: " -dll",
  172. buildLib: "", # XXX: not supported yet
  173. linkerExe: "lcclnk",
  174. linkTmpl: "$options $buildgui $builddll -O $exefile $objfiles",
  175. includeCmd: " -I",
  176. linkDirCmd: "", # XXX: not supported yet
  177. linkLibCmd: "", # XXX: not supported yet
  178. debug: " -g5 ",
  179. pic: "",
  180. asmStmtFrmt: "_asm{$n$1$n}$n",
  181. structStmtFmt: "$1 $2",
  182. props: {})
  183. # Borland C Compiler
  184. compiler bcc:
  185. result = (
  186. name: "bcc",
  187. objExt: "obj",
  188. optSpeed: " -O3 -6 ",
  189. optSize: " -O1 -6 ",
  190. compilerExe: "bcc32c",
  191. cppCompiler: "cpp32c",
  192. compileTmpl: "-c $options $include -o$objfile $file",
  193. buildGui: " -tW",
  194. buildDll: " -tWD",
  195. buildLib: "", # XXX: not supported yet
  196. linkerExe: "bcc32",
  197. linkTmpl: "$options $buildgui $builddll -e$exefile $objfiles",
  198. includeCmd: " -I",
  199. linkDirCmd: "", # XXX: not supported yet
  200. linkLibCmd: "", # XXX: not supported yet
  201. debug: "",
  202. pic: "",
  203. asmStmtFrmt: "__asm{$n$1$n}$n",
  204. structStmtFmt: "$1 $2",
  205. props: {hasSwitchRange, hasComputedGoto, hasCpp, hasGcGuard,
  206. hasAttribute})
  207. # Digital Mars C Compiler
  208. compiler dmc:
  209. result = (
  210. name: "dmc",
  211. objExt: "obj",
  212. optSpeed: " -ff -o -6 ",
  213. optSize: " -ff -o -6 ",
  214. compilerExe: "dmc",
  215. cppCompiler: "",
  216. compileTmpl: "-c $options $include -o$objfile $file",
  217. buildGui: " -L/exet:nt/su:windows",
  218. buildDll: " -WD",
  219. buildLib: "", # XXX: not supported yet
  220. linkerExe: "dmc",
  221. linkTmpl: "$options $buildgui $builddll -o$exefile $objfiles",
  222. includeCmd: " -I",
  223. linkDirCmd: "", # XXX: not supported yet
  224. linkLibCmd: "", # XXX: not supported yet
  225. debug: " -g ",
  226. pic: "",
  227. asmStmtFrmt: "__asm{$n$1$n}$n",
  228. structStmtFmt: "$3$n$1 $2",
  229. props: {hasCpp})
  230. # Watcom C Compiler
  231. compiler wcc:
  232. result = (
  233. name: "wcc",
  234. objExt: "obj",
  235. optSpeed: " -ox -on -6 -d0 -fp6 -zW ",
  236. optSize: "",
  237. compilerExe: "wcl386",
  238. cppCompiler: "",
  239. compileTmpl: "-c $options $include -fo=$objfile $file",
  240. buildGui: " -bw",
  241. buildDll: " -bd",
  242. buildLib: "", # XXX: not supported yet
  243. linkerExe: "wcl386",
  244. linkTmpl: "$options $buildgui $builddll -fe=$exefile $objfiles ",
  245. includeCmd: " -i=",
  246. linkDirCmd: "", # XXX: not supported yet
  247. linkLibCmd: "", # XXX: not supported yet
  248. debug: " -d2 ",
  249. pic: "",
  250. asmStmtFrmt: "__asm{$n$1$n}$n",
  251. structStmtFmt: "$1 $2",
  252. props: {hasCpp})
  253. # Tiny C Compiler
  254. compiler tcc:
  255. result = (
  256. name: "tcc",
  257. objExt: "o",
  258. optSpeed: "",
  259. optSize: "",
  260. compilerExe: "tcc",
  261. cppCompiler: "",
  262. compileTmpl: "-c $options $include -o $objfile $file",
  263. buildGui: "-Wl,-subsystem=gui",
  264. buildDll: " -shared",
  265. buildLib: "", # XXX: not supported yet
  266. linkerExe: "tcc",
  267. linkTmpl: "-o $exefile $options $buildgui $builddll $objfiles",
  268. includeCmd: " -I",
  269. linkDirCmd: "", # XXX: not supported yet
  270. linkLibCmd: "", # XXX: not supported yet
  271. debug: " -g ",
  272. pic: "",
  273. asmStmtFrmt: "__asm{$n$1$n}$n",
  274. structStmtFmt: "$1 $2",
  275. props: {hasSwitchRange, hasComputedGoto})
  276. # Pelles C Compiler
  277. compiler pcc:
  278. # Pelles C
  279. result = (
  280. name: "pcc",
  281. objExt: "obj",
  282. optSpeed: " -Ox ",
  283. optSize: " -Os ",
  284. compilerExe: "cc",
  285. cppCompiler: "",
  286. compileTmpl: "-c $options $include -Fo$objfile $file",
  287. buildGui: " -SUBSYSTEM:WINDOWS",
  288. buildDll: " -DLL",
  289. buildLib: "", # XXX: not supported yet
  290. linkerExe: "cc",
  291. linkTmpl: "$options $buildgui $builddll -OUT:$exefile $objfiles",
  292. includeCmd: " -I",
  293. linkDirCmd: "", # XXX: not supported yet
  294. linkLibCmd: "", # XXX: not supported yet
  295. debug: " -Zi ",
  296. pic: "",
  297. asmStmtFrmt: "__asm{$n$1$n}$n",
  298. structStmtFmt: "$1 $2",
  299. props: {})
  300. # Your C Compiler
  301. compiler ucc:
  302. result = (
  303. name: "ucc",
  304. objExt: "o",
  305. optSpeed: " -O3 ",
  306. optSize: " -O1 ",
  307. compilerExe: "cc",
  308. cppCompiler: "",
  309. compileTmpl: "-c $options $include -o $objfile $file",
  310. buildGui: "",
  311. buildDll: " -shared ",
  312. buildLib: "", # XXX: not supported yet
  313. linkerExe: "cc",
  314. linkTmpl: "-o $exefile $buildgui $builddll $objfiles $options",
  315. includeCmd: " -I",
  316. linkDirCmd: "", # XXX: not supported yet
  317. linkLibCmd: "", # XXX: not supported yet
  318. debug: "",
  319. pic: "",
  320. asmStmtFrmt: "__asm{$n$1$n}$n",
  321. structStmtFmt: "$1 $2",
  322. props: {})
  323. const
  324. CC*: array[succ(low(TSystemCC))..high(TSystemCC), TInfoCC] = [
  325. gcc(),
  326. nintendoSwitchGCC(),
  327. llvmGcc(),
  328. clang(),
  329. lcc(),
  330. bcc(),
  331. dmc(),
  332. wcc(),
  333. vcc(),
  334. tcc(),
  335. pcc(),
  336. ucc(),
  337. icl(),
  338. icc(),
  339. clangcl()]
  340. hExt* = ".h"
  341. proc libNameTmpl(conf: ConfigRef): string {.inline.} =
  342. result = if conf.target.targetOS == osWindows: "$1.lib" else: "lib$1.a"
  343. proc nameToCC*(name: string): TSystemCC =
  344. ## Returns the kind of compiler referred to by `name`, or ccNone
  345. ## if the name doesn't refer to any known compiler.
  346. for i in countup(succ(ccNone), high(TSystemCC)):
  347. if cmpIgnoreStyle(name, CC[i].name) == 0:
  348. return i
  349. result = ccNone
  350. proc getConfigVar(conf: ConfigRef; c: TSystemCC, suffix: string): string =
  351. # use ``cpu.os.cc`` for cross compilation, unless ``--compileOnly`` is given
  352. # for niminst support
  353. let fullSuffix =
  354. if conf.cmd == cmdCompileToCpp:
  355. ".cpp" & suffix
  356. elif conf.cmd == cmdCompileToOC:
  357. ".objc" & suffix
  358. elif conf.cmd == cmdCompileToJS:
  359. ".js" & suffix
  360. else:
  361. suffix
  362. if (conf.target.hostOS != conf.target.targetOS or conf.target.hostCPU != conf.target.targetCPU) and
  363. optCompileOnly notin conf.globalOptions:
  364. let fullCCname = platform.CPU[conf.target.targetCPU].name & '.' &
  365. platform.OS[conf.target.targetOS].name & '.' &
  366. CC[c].name & fullSuffix
  367. result = getConfigVar(conf, fullCCname)
  368. if result.len == 0:
  369. # not overriden for this cross compilation setting?
  370. result = getConfigVar(conf, CC[c].name & fullSuffix)
  371. else:
  372. result = getConfigVar(conf, CC[c].name & fullSuffix)
  373. proc setCC*(conf: ConfigRef; ccname: string; info: TLineInfo) =
  374. conf.cCompiler = nameToCC(ccname)
  375. if conf.cCompiler == ccNone:
  376. localError(conf, info, "unknown C compiler: '$1'" % ccname)
  377. conf.compileOptions = getConfigVar(conf, conf.cCompiler, ".options.always")
  378. conf.linkOptions = ""
  379. conf.ccompilerpath = getConfigVar(conf, conf.cCompiler, ".path")
  380. for i in countup(low(CC), high(CC)): undefSymbol(conf.symbols, CC[i].name)
  381. defineSymbol(conf.symbols, CC[conf.cCompiler].name)
  382. proc addOpt(dest: var string, src: string) =
  383. if len(dest) == 0 or dest[len(dest)-1] != ' ': add(dest, " ")
  384. add(dest, src)
  385. proc addLinkOption*(conf: ConfigRef; option: string) =
  386. addOpt(conf.linkOptions, option)
  387. proc addCompileOption*(conf: ConfigRef; option: string) =
  388. if strutils.find(conf.compileOptions, option, 0) < 0:
  389. addOpt(conf.compileOptions, option)
  390. proc addLinkOptionCmd*(conf: ConfigRef; option: string) =
  391. addOpt(conf.linkOptionsCmd, option)
  392. proc addCompileOptionCmd*(conf: ConfigRef; option: string) =
  393. conf.compileOptionsCmd.add(option)
  394. proc initVars*(conf: ConfigRef) =
  395. # we need to define the symbol here, because ``CC`` may have never been set!
  396. for i in countup(low(CC), high(CC)): undefSymbol(conf.symbols, CC[i].name)
  397. defineSymbol(conf.symbols, CC[conf.cCompiler].name)
  398. addCompileOption(conf, getConfigVar(conf, conf.cCompiler, ".options.always"))
  399. #addLinkOption(getConfigVar(cCompiler, ".options.linker"))
  400. if len(conf.ccompilerpath) == 0:
  401. conf.ccompilerpath = getConfigVar(conf, conf.cCompiler, ".path")
  402. proc completeCFilePath*(conf: ConfigRef; cfile: AbsoluteFile,
  403. createSubDir: bool = true): AbsoluteFile =
  404. result = completeGeneratedFilePath(conf, cfile, createSubDir)
  405. proc toObjFile*(conf: ConfigRef; filename: AbsoluteFile): AbsoluteFile =
  406. # Object file for compilation
  407. result = AbsoluteFile(filename.string & "." & CC[conf.cCompiler].objExt)
  408. proc addFileToCompile*(conf: ConfigRef; cf: Cfile) =
  409. conf.toCompile.add(cf)
  410. proc resetCompilationLists*(conf: ConfigRef) =
  411. conf.toCompile.setLen 0
  412. ## XXX: we must associate these with their originating module
  413. # when the module is loaded/unloaded it adds/removes its items
  414. # That's because we still need to hash check the external files
  415. # Maybe we can do that in checkDep on the other hand?
  416. conf.externalToLink.setLen 0
  417. proc addExternalFileToLink*(conf: ConfigRef; filename: AbsoluteFile) =
  418. conf.externalToLink.insert(filename.string, 0)
  419. proc execWithEcho(conf: ConfigRef; cmd: string, msg = hintExecuting): int =
  420. rawMessage(conf, msg, cmd)
  421. result = execCmd(cmd)
  422. proc execExternalProgram*(conf: ConfigRef; cmd: string, msg = hintExecuting) =
  423. if execWithEcho(conf, cmd, msg) != 0:
  424. rawMessage(conf, errGenerated, "execution of an external program failed: '$1'" %
  425. cmd)
  426. proc generateScript(conf: ConfigRef; projectFile: AbsoluteFile, script: Rope) =
  427. let (_, name, _) = splitFile(projectFile)
  428. let filename = getNimcacheDir(conf) / RelativeFile(addFileExt("compile_" & name,
  429. platform.OS[conf.target.targetOS].scriptExt))
  430. if writeRope(script, filename):
  431. copyFile(conf.libpath / RelativeFile"nimbase.h",
  432. getNimcacheDir(conf) / RelativeFile"nimbase.h")
  433. else:
  434. rawMessage(conf, errGenerated, "could not write to file: " & filename.string)
  435. proc getOptSpeed(conf: ConfigRef; c: TSystemCC): string =
  436. result = getConfigVar(conf, c, ".options.speed")
  437. if result == "":
  438. result = CC[c].optSpeed # use default settings from this file
  439. proc getDebug(conf: ConfigRef; c: TSystemCC): string =
  440. result = getConfigVar(conf, c, ".options.debug")
  441. if result == "":
  442. result = CC[c].debug # use default settings from this file
  443. proc getOptSize(conf: ConfigRef; c: TSystemCC): string =
  444. result = getConfigVar(conf, c, ".options.size")
  445. if result == "":
  446. result = CC[c].optSize # use default settings from this file
  447. proc noAbsolutePaths(conf: ConfigRef): bool {.inline.} =
  448. # We used to check current OS != specified OS, but this makes no sense
  449. # really: Cross compilation from Linux to Linux for example is entirely
  450. # reasonable.
  451. # `optGenMapping` is included here for niminst.
  452. result = conf.globalOptions * {optGenScript, optGenMapping} != {}
  453. proc cFileSpecificOptions(conf: ConfigRef; cfilename: AbsoluteFile): string =
  454. result = conf.compileOptions
  455. for option in conf.compileOptionsCmd:
  456. if strutils.find(result, option, 0) < 0:
  457. addOpt(result, option)
  458. let trunk = splitFile(cfilename).name
  459. if optCDebug in conf.globalOptions:
  460. let key = trunk & ".debug"
  461. if existsConfigVar(conf, key): addOpt(result, getConfigVar(conf, key))
  462. else: addOpt(result, getDebug(conf, conf.cCompiler))
  463. if optOptimizeSpeed in conf.options:
  464. let key = trunk & ".speed"
  465. if existsConfigVar(conf, key): addOpt(result, getConfigVar(conf, key))
  466. else: addOpt(result, getOptSpeed(conf, conf.cCompiler))
  467. elif optOptimizeSize in conf.options:
  468. let key = trunk & ".size"
  469. if existsConfigVar(conf, key): addOpt(result, getConfigVar(conf, key))
  470. else: addOpt(result, getOptSize(conf, conf.cCompiler))
  471. let key = trunk & ".always"
  472. if existsConfigVar(conf, key): addOpt(result, getConfigVar(conf, key))
  473. proc getCompileOptions(conf: ConfigRef): string =
  474. result = cFileSpecificOptions(conf, AbsoluteFile"__dummy__")
  475. proc getLinkOptions(conf: ConfigRef): string =
  476. result = conf.linkOptions & " " & conf.linkOptionsCmd & " "
  477. for linkedLib in items(conf.cLinkedLibs):
  478. result.add(CC[conf.cCompiler].linkLibCmd % linkedLib.quoteShell)
  479. for libDir in items(conf.cLibs):
  480. result.add(join([CC[conf.cCompiler].linkDirCmd, libDir.quoteShell]))
  481. proc needsExeExt(conf: ConfigRef): bool {.inline.} =
  482. result = (optGenScript in conf.globalOptions and conf.target.targetOS == osWindows) or
  483. (conf.target.hostOS == osWindows)
  484. proc getCompilerExe(conf: ConfigRef; compiler: TSystemCC; cfile: AbsoluteFile): string =
  485. result = if conf.cmd == cmdCompileToCpp and not cfile.string.endsWith(".c"):
  486. CC[compiler].cppCompiler
  487. else:
  488. CC[compiler].compilerExe
  489. if result.len == 0:
  490. rawMessage(conf, errGenerated,
  491. "Compiler '$1' doesn't support the requested target" %
  492. CC[compiler].name)
  493. proc getLinkerExe(conf: ConfigRef; compiler: TSystemCC): string =
  494. result = if CC[compiler].linkerExe.len > 0: CC[compiler].linkerExe
  495. elif optMixedMode in conf.globalOptions and conf.cmd != cmdCompileToCpp: CC[compiler].cppCompiler
  496. else: getCompilerExe(conf, compiler, AbsoluteFile"")
  497. proc getCompileCFileCmd*(conf: ConfigRef; cfile: Cfile): string =
  498. var c = conf.cCompiler
  499. var options = cFileSpecificOptions(conf, cfile.cname)
  500. var exe = getConfigVar(conf, c, ".exe")
  501. if exe.len == 0: exe = getCompilerExe(conf, c, cfile.cname)
  502. if needsExeExt(conf): exe = addFileExt(exe, "exe")
  503. if optGenDynLib in conf.globalOptions and
  504. ospNeedsPIC in platform.OS[conf.target.targetOS].props:
  505. add(options, ' ' & CC[c].pic)
  506. var includeCmd, compilePattern: string
  507. if not noAbsolutePaths(conf):
  508. # compute include paths:
  509. includeCmd = CC[c].includeCmd & quoteShell(conf.libpath)
  510. for includeDir in items(conf.cIncludes):
  511. includeCmd.add(join([CC[c].includeCmd, includeDir.quoteShell]))
  512. compilePattern = joinPath(conf.ccompilerpath, exe)
  513. else:
  514. includeCmd = ""
  515. compilePattern = getCompilerExe(conf, c, cfile.cname)
  516. includeCmd.add(join([CC[c].includeCmd, quoteShell(conf.projectPath.string)]))
  517. var cf = if noAbsolutePaths(conf): AbsoluteFile extractFilename(cfile.cname.string)
  518. else: cfile.cname
  519. var objfile =
  520. if cfile.obj.isEmpty:
  521. if not cfile.flags.contains(CfileFlag.External) or noAbsolutePaths(conf):
  522. toObjFile(conf, cf).string
  523. else:
  524. completeCFilePath(conf, toObjFile(conf, cf)).string
  525. elif noAbsolutePaths(conf):
  526. extractFilename(cfile.obj.string)
  527. else:
  528. cfile.obj.string
  529. # D files are required by nintendo switch libs for
  530. # compilation. They are basically a list of all includes.
  531. let dfile = objfile.changeFileExt(".d").quoteShell()
  532. objfile = quoteShell(objfile)
  533. let cfsh = quoteShell(cf)
  534. result = quoteShell(compilePattern % [
  535. "dfile", dfile,
  536. "file", cfsh, "objfile", objfile, "options", options,
  537. "include", includeCmd, "nim", getPrefixDir(conf).string,
  538. "lib", conf.libpath.string])
  539. add(result, ' ')
  540. addf(result, CC[c].compileTmpl, [
  541. "dfile", dfile,
  542. "file", cfsh, "objfile", objfile,
  543. "options", options, "include", includeCmd,
  544. "nim", quoteShell(getPrefixDir(conf)),
  545. "lib", quoteShell(conf.libpath)])
  546. proc footprint(conf: ConfigRef; cfile: Cfile): SecureHash =
  547. result = secureHash(
  548. $secureHashFile(cfile.cname.string) &
  549. platform.OS[conf.target.targetOS].name &
  550. platform.CPU[conf.target.targetCPU].name &
  551. extccomp.CC[conf.cCompiler].name &
  552. getCompileCFileCmd(conf, cfile))
  553. proc externalFileChanged(conf: ConfigRef; cfile: Cfile): bool =
  554. if conf.cmd notin {cmdCompileToC, cmdCompileToCpp, cmdCompileToOC, cmdCompileToLLVM}:
  555. return false
  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. conf.toCompile.add(c)
  574. proc addExternalFileToCompile*(conf: ConfigRef; filename: AbsoluteFile) =
  575. var c = Cfile(cname: filename,
  576. obj: toObjFile(conf, completeCFilePath(conf, filename, false)),
  577. flags: {CfileFlag.External})
  578. addExternalFileToCompile(conf, c)
  579. proc compileCFile(conf: ConfigRef; list: CFileList, script: var Rope, cmds: var TStringSeq,
  580. prettyCmds: var TStringSeq) =
  581. for it in list:
  582. # call the C compiler for the .c file:
  583. if it.flags.contains(CfileFlag.Cached): continue
  584. var compileCmd = getCompileCFileCmd(conf, it)
  585. if optCompileOnly notin conf.globalOptions:
  586. add(cmds, compileCmd)
  587. let (_, name, _) = splitFile(it.cname)
  588. add(prettyCmds, if hintCC in conf.notes: "CC: " & name else: "")
  589. if optGenScript in conf.globalOptions:
  590. add(script, compileCmd)
  591. add(script, "\n")
  592. proc getLinkCmd(conf: ConfigRef; projectfile: AbsoluteFile, objfiles: string): string =
  593. if optGenStaticLib in conf.globalOptions:
  594. var libname: string
  595. if not conf.outFile.isEmpty:
  596. libname = conf.outFile.string.expandTilde
  597. if not libname.isAbsolute():
  598. libname = getCurrentDir() / libname
  599. else:
  600. libname = (libNameTmpl(conf) % splitFile(conf.projectName).name)
  601. result = CC[conf.cCompiler].buildLib % ["libfile", quoteShell(libname),
  602. "objfiles", objfiles]
  603. else:
  604. var linkerExe = getConfigVar(conf, conf.cCompiler, ".linkerexe")
  605. if len(linkerExe) == 0: linkerExe = getLinkerExe(conf, conf.cCompiler)
  606. # bug #6452: We must not use ``quoteShell`` here for ``linkerExe``
  607. if needsExeExt(conf): linkerExe = addFileExt(linkerExe, "exe")
  608. if noAbsolutePaths(conf): result = linkerExe
  609. else: result = joinPath(conf.cCompilerpath, linkerExe)
  610. let buildgui = if optGenGuiApp in conf.globalOptions and conf.target.targetOS == osWindows:
  611. CC[conf.cCompiler].buildGui
  612. else:
  613. ""
  614. var exefile, builddll: string
  615. if optGenDynLib in conf.globalOptions:
  616. exefile = platform.OS[conf.target.targetOS].dllFrmt % splitFile(projectfile).name
  617. builddll = CC[conf.cCompiler].buildDll
  618. else:
  619. exefile = splitFile(projectfile).name & platform.OS[conf.target.targetOS].exeExt
  620. builddll = ""
  621. if not conf.outFile.isEmpty:
  622. exefile = conf.outFile.string.expandTilde
  623. if not exefile.isAbsolute():
  624. exefile = getCurrentDir() / exefile
  625. if not noAbsolutePaths(conf):
  626. if not exefile.isAbsolute():
  627. exefile = string(splitFile(projectfile).dir / RelativeFile(exefile))
  628. when false:
  629. if optCDebug in conf.globalOptions:
  630. writeDebugInfo(exefile.changeFileExt("ndb"))
  631. exefile = quoteShell(exefile)
  632. # Map files are required by Nintendo Switch compilation. They are a list
  633. # of all function calls in the library and where they come from.
  634. let mapfile = quoteShell(getNimcacheDir(conf) / RelativeFile(splitFile(projectFile).name & ".map"))
  635. let linkOptions = getLinkOptions(conf) & " " &
  636. getConfigVar(conf, conf.cCompiler, ".options.linker")
  637. var linkTmpl = getConfigVar(conf, conf.cCompiler, ".linkTmpl")
  638. if linkTmpl.len == 0:
  639. linkTmpl = CC[conf.cCompiler].linkTmpl
  640. result = quoteShell(result % ["builddll", builddll,
  641. "mapfile", mapfile,
  642. "buildgui", buildgui, "options", linkOptions, "objfiles", objfiles,
  643. "exefile", exefile, "nim", getPrefixDir(conf).string, "lib", conf.libpath.string])
  644. result.add ' '
  645. addf(result, linkTmpl, ["builddll", builddll,
  646. "mapfile", mapfile,
  647. "buildgui", buildgui, "options", linkOptions,
  648. "objfiles", objfiles, "exefile", exefile,
  649. "nim", quoteShell(getPrefixDir(conf)),
  650. "lib", quoteShell(conf.libpath)])
  651. template tryExceptOSErrorMessage(conf: ConfigRef; errorPrefix: string = "", body: untyped): typed =
  652. try:
  653. body
  654. except OSError:
  655. let ose = (ref OSError)(getCurrentException())
  656. if errorPrefix.len > 0:
  657. rawMessage(conf, errGenerated, errorPrefix & " " & ose.msg & " " & $ose.errorCode)
  658. else:
  659. rawMessage(conf, errGenerated, "execution of an external program failed: '$1'" %
  660. (ose.msg & " " & $ose.errorCode))
  661. raise
  662. proc execLinkCmd(conf: ConfigRef; linkCmd: string) =
  663. tryExceptOSErrorMessage(conf, "invocation of external linker program failed."):
  664. execExternalProgram(conf, linkCmd,
  665. if optListCmd in conf.globalOptions or conf.verbosity > 1: hintExecuting else: hintLinking)
  666. proc execCmdsInParallel(conf: ConfigRef; cmds: seq[string]; prettyCb: proc (idx: int)) =
  667. let runCb = proc (idx: int, p: Process) =
  668. let exitCode = p.peekExitCode
  669. if exitCode != 0:
  670. rawMessage(conf, errGenerated, "execution of an external compiler program '" &
  671. cmds[idx] & "' failed with exit code: " & $exitCode & "\n\n" &
  672. p.outputStream.readAll.strip)
  673. if conf.numberOfProcessors == 0: conf.numberOfProcessors = countProcessors()
  674. var res = 0
  675. if conf.numberOfProcessors <= 1:
  676. for i in countup(0, high(cmds)):
  677. tryExceptOSErrorMessage(conf, "invocation of external compiler program failed."):
  678. res = execWithEcho(conf, cmds[i])
  679. if res != 0:
  680. rawMessage(conf, errGenerated, "execution of an external program failed: '$1'" %
  681. cmds[i])
  682. else:
  683. tryExceptOSErrorMessage(conf, "invocation of external compiler program failed."):
  684. if optListCmd in conf.globalOptions or conf.verbosity > 1:
  685. res = execProcesses(cmds, {poEchoCmd, poStdErrToStdOut, poUsePath},
  686. conf.numberOfProcessors, afterRunEvent=runCb)
  687. elif conf.verbosity == 1:
  688. res = execProcesses(cmds, {poStdErrToStdOut, poUsePath},
  689. conf.numberOfProcessors, prettyCb, afterRunEvent=runCb)
  690. else:
  691. res = execProcesses(cmds, {poStdErrToStdOut, poUsePath},
  692. conf.numberOfProcessors, afterRunEvent=runCb)
  693. if res != 0:
  694. if conf.numberOfProcessors <= 1:
  695. rawMessage(conf, errGenerated, "execution of an external program failed: '$1'" %
  696. cmds.join())
  697. proc linkViaResponseFile(conf: ConfigRef; cmd: string) =
  698. # Extracting the linker.exe here is a bit hacky but the best solution
  699. # given ``buildLib``'s design.
  700. var i = 0
  701. var last = 0
  702. if cmd.len > 0 and cmd[0] == '"':
  703. inc i
  704. while i < cmd.len and cmd[i] != '"': inc i
  705. last = i
  706. inc i
  707. else:
  708. while i < cmd.len and cmd[i] != ' ': inc i
  709. last = i
  710. while i < cmd.len and cmd[i] == ' ': inc i
  711. let linkerArgs = conf.projectName & "_" & "linkerArgs.txt"
  712. let args = cmd.substr(i)
  713. # GCC's response files don't support backslashes. Junk.
  714. if conf.cCompiler == ccGcc or conf.cCompiler == ccCLang:
  715. writeFile(linkerArgs, args.replace('\\', '/'))
  716. else:
  717. writeFile(linkerArgs, args)
  718. try:
  719. execLinkCmd(conf, cmd.substr(0, last) & " @" & linkerArgs)
  720. finally:
  721. removeFile(linkerArgs)
  722. proc callCCompiler*(conf: ConfigRef; projectfile: AbsoluteFile) =
  723. var
  724. linkCmd: string
  725. if conf.globalOptions * {optCompileOnly, optGenScript} == {optCompileOnly}:
  726. return # speed up that call if only compiling and no script shall be
  727. # generated
  728. #var c = cCompiler
  729. var script: Rope = nil
  730. var cmds: TStringSeq = @[]
  731. var prettyCmds: TStringSeq = @[]
  732. let prettyCb = proc (idx: int) =
  733. when declared(echo):
  734. let cmd = prettyCmds[idx]
  735. if cmd != "": echo cmd
  736. compileCFile(conf, conf.toCompile, script, cmds, prettyCmds)
  737. if optCompileOnly notin conf.globalOptions:
  738. execCmdsInParallel(conf, cmds, prettyCb)
  739. if optNoLinking notin conf.globalOptions:
  740. # call the linker:
  741. var objfiles = ""
  742. for it in conf.externalToLink:
  743. let objFile = if noAbsolutePaths(conf): it.extractFilename else: it
  744. add(objfiles, ' ')
  745. add(objfiles, quoteShell(
  746. addFileExt(objFile, CC[conf.cCompiler].objExt)))
  747. for x in conf.toCompile:
  748. let objFile = if noAbsolutePaths(conf): x.obj.extractFilename else: x.obj.string
  749. add(objfiles, ' ')
  750. add(objfiles, quoteShell(objFile))
  751. linkCmd = getLinkCmd(conf, projectfile, objfiles)
  752. if optCompileOnly notin conf.globalOptions:
  753. if defined(windows) and linkCmd.len > 8_000:
  754. # Windows's command line limit is about 8K (don't laugh...) so C compilers on
  755. # Windows support a feature where the command line can be passed via ``@linkcmd``
  756. # to them.
  757. linkViaResponseFile(conf, linkCmd)
  758. else:
  759. execLinkCmd(conf, linkCmd)
  760. else:
  761. linkCmd = ""
  762. if optGenScript in conf.globalOptions:
  763. add(script, linkCmd)
  764. add(script, "\n")
  765. generateScript(conf, projectfile, script)
  766. #from json import escapeJson
  767. import json
  768. proc writeJsonBuildInstructions*(conf: ConfigRef; projectfile: AbsoluteFile) =
  769. template lit(x: untyped) = f.write x
  770. template str(x: untyped) =
  771. when compiles(escapeJson(x, buf)):
  772. buf.setLen 0
  773. escapeJson(x, buf)
  774. f.write buf
  775. else:
  776. f.write escapeJson(x)
  777. proc cfiles(conf: ConfigRef; f: File; buf: var string; clist: CfileList, isExternal: bool) =
  778. var pastStart = false
  779. for it in clist:
  780. if CfileFlag.Cached in it.flags: continue
  781. let compileCmd = getCompileCFileCmd(conf, it)
  782. if pastStart: lit "],\L"
  783. lit "["
  784. str it.cname.string
  785. lit ", "
  786. str compileCmd
  787. pastStart = true
  788. lit "]\L"
  789. proc linkfiles(conf: ConfigRef; f: File; buf, objfiles: var string; clist: CfileList;
  790. llist: seq[string]) =
  791. var pastStart = false
  792. for it in llist:
  793. let objfile = if noAbsolutePaths(conf): it.extractFilename
  794. else: it
  795. let objstr = addFileExt(objfile, CC[conf.cCompiler].objExt)
  796. add(objfiles, ' ')
  797. add(objfiles, objstr)
  798. if pastStart: lit ",\L"
  799. str objstr
  800. pastStart = true
  801. for it in clist:
  802. let objstr = quoteShell(it.obj)
  803. add(objfiles, ' ')
  804. add(objfiles, objstr)
  805. if pastStart: lit ",\L"
  806. str objstr
  807. pastStart = true
  808. lit "\L"
  809. var buf = newStringOfCap(50)
  810. let jsonFile = toGeneratedFile(conf, projectfile, "json")
  811. var f: File
  812. if open(f, jsonFile.string, fmWrite):
  813. lit "{\"compile\":[\L"
  814. cfiles(conf, f, buf, conf.toCompile, false)
  815. lit "],\L\"link\":[\L"
  816. var objfiles = ""
  817. # XXX add every file here that is to link
  818. linkfiles(conf, f, buf, objfiles, conf.toCompile, conf.externalToLink)
  819. lit "],\L\"linkcmd\": "
  820. str getLinkCmd(conf, projectfile, objfiles)
  821. lit "\L}\L"
  822. close(f)
  823. proc runJsonBuildInstructions*(conf: ConfigRef; projectfile: AbsoluteFile) =
  824. let jsonFile = toGeneratedFile(conf, projectfile, "json")
  825. try:
  826. let data = json.parseFile(jsonFile.string)
  827. let toCompile = data["compile"]
  828. doAssert toCompile.kind == JArray
  829. var cmds: TStringSeq = @[]
  830. var prettyCmds: TStringSeq = @[]
  831. for c in toCompile:
  832. doAssert c.kind == JArray
  833. doAssert c.len >= 2
  834. add(cmds, c[1].getStr)
  835. let (_, name, _) = splitFile(c[0].getStr)
  836. add(prettyCmds, "CC: " & name)
  837. let prettyCb = proc (idx: int) =
  838. when declared(echo):
  839. echo prettyCmds[idx]
  840. execCmdsInParallel(conf, cmds, prettyCb)
  841. let linkCmd = data["linkcmd"]
  842. doAssert linkCmd.kind == JString
  843. execLinkCmd(conf, linkCmd.getStr)
  844. except:
  845. when declared(echo):
  846. echo getCurrentException().getStackTrace()
  847. quit "error evaluating JSON file: " & jsonFile.string
  848. proc genMappingFiles(conf: ConfigRef; list: CFileList): Rope =
  849. for it in list:
  850. addf(result, "--file:r\"$1\"$N", [rope(it.cname.string)])
  851. proc writeMapping*(conf: ConfigRef; symbolMapping: Rope) =
  852. if optGenMapping notin conf.globalOptions: return
  853. var code = rope("[C_Files]\n")
  854. add(code, genMappingFiles(conf, conf.toCompile))
  855. add(code, "\n[C_Compiler]\nFlags=")
  856. add(code, strutils.escape(getCompileOptions(conf)))
  857. add(code, "\n[Linker]\nFlags=")
  858. add(code, strutils.escape(getLinkOptions(conf) & " " &
  859. getConfigVar(conf, conf.cCompiler, ".options.linker")))
  860. add(code, "\n[Environment]\nlibpath=")
  861. add(code, strutils.escape(conf.libpath.string))
  862. addf(code, "\n[Symbols]$n$1", [symbolMapping])
  863. let filename = conf.projectPath / RelativeFile"mapping.txt"
  864. if not writeRope(code, filename):
  865. rawMessage(conf, errGenerated, "could not write to file: " & filename.string)