jcomp.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "platform.h"
  14. #include "jlib.hpp"
  15. #include "jmisc.hpp"
  16. #include "jcomp.hpp"
  17. #include "jsem.hpp"
  18. #include "jexcept.hpp"
  19. #ifdef _WIN32
  20. #include <windows.h>
  21. #include <winbase.h>
  22. #include <io.h>
  23. #else
  24. #include <sys/wait.h>
  25. #endif
  26. #include <fcntl.h>
  27. #include <sys/types.h>
  28. #include <sys/stat.h>
  29. #include <stdio.h>
  30. #include "jfile.hpp"
  31. #include "jdebug.hpp"
  32. #include "jcomp.ipp"
  33. #define CC_EXTRA_OPTIONS ""
  34. #ifdef GENERATE_LISTING
  35. #undef CC_EXTRA_OPTIONS
  36. #define CC_EXTRA_OPTIONS " /FAs"
  37. #endif
  38. #ifdef _WIN32
  39. #define DEFAULT_COMPILER Vs6CppCompiler
  40. #else
  41. #define DEFAULT_COMPILER GccCppCompiler
  42. #endif
  43. //---------------------------------------------------------------------------
  44. #define BASE_ADDRESS "0x00480000"
  45. //#define BASE_ADDRESS "0x10000000"
  46. static const char * CC_NAME[] = { "\"#" PATHSEPSTR "bin" PATHSEPSTR "cl.bat\"", "\"#" PATHSEPSTR "bin" PATHSEPSTR "g++\"" };
  47. static const char * LINK_NAME[] = { "\"#" PATHSEPSTR "bin" PATHSEPSTR "link.bat\"", "\"#" PATHSEPSTR "bin" PATHSEPSTR "g++\"" };
  48. static const char * LIB_DIR[] = { "\"#\\lib\"", "\"#/lib\"" };
  49. static const char * LIB_OPTION_PREFIX[] = { "", "-Wl," };
  50. static const char * USE_LIBPATH_FLAG[] = { "/libpath:\"", "-L" };
  51. static const char * USE_LIBPATH_TAIL[] = { "\"", "" };
  52. static const char * USE_LIBRPATH_FLAG[] = { NULL, "-Wl,-rpath," };
  53. static const char * USE_LIB_FLAG[] = { "", "-l" };
  54. static const char * USE_LIB_TAIL[] = { ".lib", "" };
  55. static const char * USE_INCLUDE_FLAG[] = { "/I\"", "\"-I" };
  56. static const char * USE_DEFINE_FLAG[] = { "/D", "-D" };
  57. static const char * USE_INCLUDE_TAIL[] = { "\"", "\"" };
  58. static const char * INCLUDEPATH[] = { "\"#\\include\"", "\"#/include\"" };
  59. static const char * LINK_SEPARATOR[] = { " /link ", " " };
  60. static const char * OBJECT_FILE_EXT[] = { "obj", "o" };
  61. static const char * PCH_FILE_EXT[] = { "", "gch" };
  62. static const char * LIBFLAG_DEBUG[] = { "/MDd", "" };
  63. static const char * LIBFLAG_RELEASE[] = { "/MD", "" };
  64. static const char * COMPILE_ONLY[] = { "/c", "-c" };
  65. static const char * CC_OPTION_CORE[] = { "", "-fvisibility=hidden -DUSE_VISIBILITY=1" };
  66. static const char * LINK_OPTION_CORE[] = { "/DLL /libpath:." , "" };
  67. static const char * CC_OPTION_DEBUG[] = { "/Zm500 /EHsc /GR /Zi /nologo /bigobj", "-g -fPIC -pipe -O0" };
  68. static const char * DLL_LINK_OPTION_DEBUG[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO /DEBUG /DEBUGTYPE:CV", "-g -shared -L. -fPIC -pipe -O0" };
  69. static const char * EXE_LINK_OPTION_DEBUG[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO /DEBUG /DEBUGTYPE:CV", "-g -L. -Wl,-E -fPIC -pipe -O0" };
  70. static const char * CC_OPTION_RELEASE[] = { "/Zm500 /EHsc /GR /Oi /Ob1 /GF /nologo /bigobj", "-fPIC -pipe -O0" };
  71. static const char * CC_OPTION_PRECOMPILEHEADER[] = { "", " -x c++-header" };
  72. static const char * DLL_LINK_OPTION_RELEASE[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO", "-shared -L. -fPIC -pipe -O0" };
  73. static const char * EXE_LINK_OPTION_RELEASE[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO", "-L. -Wl,-E -fPIC -pipe -O0" };
  74. static const char * LINK_TARGET[] = { " /out:", " -o " };
  75. static const char * DEFAULT_CC_LOCATION[] = { ".", "." };
  76. //===========================================================================
  77. static StringAttr compilerRoot;
  78. static StringAttr stdIncludes;
  79. static StringBuffer stdLibs;
  80. static StringBuffer &dequote(StringBuffer &in)
  81. {
  82. if (in.length() >= 2 && in.charAt(0)=='"' && in.charAt(in.length()-1)=='"')
  83. {
  84. in.remove(in.length()-1, 1);
  85. in.remove(0, 1);
  86. }
  87. return in;
  88. }
  89. static void doSetCompilerPath(const char * path, const char * includes, const char * libs, const char * tmpdir, unsigned targetCompiler, bool verbose)
  90. {
  91. if (!includes)
  92. includes = INCLUDEPATH[targetCompiler];
  93. if (!libs)
  94. libs = LIB_DIR[targetCompiler];
  95. if (verbose)
  96. {
  97. PrintLog("Include directory set to %s", includes);
  98. PrintLog("Library directory set to %s", libs);
  99. }
  100. compilerRoot.set(path ? path : targetCompiler==GccCppCompiler ? "/usr" : ".\\CL");
  101. stdIncludes.set(includes);
  102. stdLibs.clear();
  103. for (;;)
  104. {
  105. StringBuffer thislib;
  106. while (*libs && *libs != ENVSEPCHAR)
  107. thislib.append(*libs++);
  108. if (thislib.length())
  109. {
  110. stdLibs.append(" ").append(USE_LIBPATH_FLAG[targetCompiler]).append(thislib).append(USE_LIBPATH_TAIL[targetCompiler]);
  111. if (USE_LIBRPATH_FLAG[targetCompiler])
  112. stdLibs.append(" ").append(USE_LIBRPATH_FLAG[targetCompiler]).append(thislib);
  113. }
  114. if (!*libs)
  115. break;
  116. libs++;
  117. }
  118. StringBuffer fname;
  119. if (path)
  120. {
  121. const char *finger = CC_NAME[targetCompiler];
  122. while (*finger)
  123. {
  124. if (*finger == '#')
  125. fname.append(path);
  126. else
  127. fname.append(*finger);
  128. finger++;
  129. }
  130. #if defined(__linux__)
  131. StringBuffer clbin_dir;
  132. const char* dir_end = strrchr(fname, '/');
  133. if(dir_end == NULL)
  134. clbin_dir.append(".");
  135. else
  136. clbin_dir.append((dir_end - fname.str()) + 1, fname.str());
  137. StringBuffer pathenv(clbin_dir.str());
  138. const char* oldpath = getenv("PATH");
  139. if(oldpath != NULL && *oldpath != '\0')
  140. pathenv.append(":").append(oldpath);
  141. setenv("PATH", pathenv.str(), 1);
  142. #endif
  143. }
  144. else
  145. {
  146. fname.append(compilerRoot).append(CC_NAME[targetCompiler]);
  147. fname.replaceString("#",NULL);
  148. }
  149. if (verbose)
  150. PrintLog("Compiler path set to %s", fname.str());
  151. dequote(fname);
  152. #ifdef _WIN32
  153. if (_access(fname.str(), 4))
  154. {
  155. #else
  156. #if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
  157. struct stat filestatus;
  158. int r = stat(fname.str(), &filestatus);
  159. if ( (r != 0)
  160. || (!S_ISREG(filestatus.st_mode))
  161. || ((filestatus.st_mode&(S_IXOTH|S_IXGRP|S_IXUSR))==0))
  162. {
  163. if (r == -1) errno = ENOENT;
  164. #endif
  165. #endif
  166. if (verbose)
  167. PrintLog("SetCompilerPath - no compiler found");
  168. throw makeOsExceptionV(GetLastError(), "setCompilerPath could not locate compiler %s", fname.str());
  169. }
  170. if(tmpdir && *tmpdir)
  171. {
  172. //MORE: this should be done for the child process instead of the parent but invoke does not let me do it
  173. #if defined(__linux__)
  174. setenv("TMPDIR", tmpdir, 1);
  175. #endif
  176. #ifdef _WIN32
  177. StringBuffer tmpbuf;
  178. tmpbuf.append("TMP=").append(tmpdir);
  179. _putenv(tmpbuf.str());
  180. #endif
  181. }
  182. }
  183. //===========================================================================
  184. class CCompilerThreadParam : CInterface
  185. {
  186. public:
  187. IMPLEMENT_IINTERFACE;
  188. CCompilerThreadParam(const StringBuffer & _cmdline, Semaphore & _finishedCompiling, const StringBuffer & _logfile) : cmdline(_cmdline), finishedCompiling(_finishedCompiling), logfile(_logfile) {};
  189. StringBuffer cmdline;
  190. StringBuffer logfile;
  191. Semaphore & finishedCompiling;
  192. };
  193. //===========================================================================
  194. static void setDirectoryPrefix(StringAttr & target, const char * source)
  195. {
  196. if (source && *source)
  197. {
  198. StringBuffer temp;
  199. target.set(addDirectoryPrefix(temp, source));
  200. }
  201. }
  202. CppCompiler::CppCompiler(const char * _coreName, const char * _sourceDir, const char * _targetDir, unsigned _targetCompiler, bool _verbose)
  203. {
  204. #define CORE_NAME allSources.item(0)
  205. if (_coreName)
  206. addSourceFile(_coreName);
  207. targetCompiler = _targetCompiler;
  208. createDLL = true;
  209. #ifdef _DEBUG
  210. setDebug(true);
  211. setDebugLibrary(true);
  212. #else
  213. setDebug(false);
  214. setDebugLibrary(false);
  215. #endif
  216. setDirectoryPrefix(sourceDir, _sourceDir);
  217. setDirectoryPrefix(targetDir, _targetDir);
  218. maxCompileThreads = 1;
  219. onlyCompile = false;
  220. verbose = _verbose;
  221. saveTemps = false;
  222. abortChecker = NULL;
  223. precompileHeader = false;
  224. }
  225. void CppCompiler::addCompileOption(const char * option)
  226. {
  227. compilerOptions.append(' ').append(option);
  228. }
  229. void CppCompiler::setPrecompileHeader(bool _pch)
  230. {
  231. if (targetCompiler!=GccCppCompiler)
  232. throw MakeStringException(0, "precompiled header generation only supported for g++ and compatible compilers");
  233. precompileHeader = _pch;
  234. }
  235. void CppCompiler::addDefine(const char * symbolName, const char * value)
  236. {
  237. compilerOptions.append(" ").append(USE_DEFINE_FLAG[targetCompiler]).append(symbolName);
  238. if (value)
  239. compilerOptions.append('=').append(value);
  240. }
  241. void CppCompiler::addLibrary(const char * libName)
  242. {
  243. if (verbose)
  244. PrintLog("addLibrary %s", libName);
  245. const char* lname = libName;
  246. const char * quote;
  247. StringBuffer path, tail; // NOTE - because of the (hacky) code below that sets lname to point within tail.str(), this must NOT be moved inside the if block
  248. if (targetCompiler == GccCppCompiler)
  249. {
  250. // It seems gcc compiler doesn't like things like -lmydir/libx.so
  251. splitFilename(libName, &path, &path, &tail, &tail);
  252. if(path.length())
  253. {
  254. addLibraryPath(path);
  255. lname = tail.str();
  256. // HACK - make it work with plugins. This should be handled at caller end!
  257. if (strncmp(lname, "lib", 3) == 0)
  258. lname += 3;
  259. }
  260. quote = NULL; //quoting lib names with gcc causes link error (lib not found)
  261. }
  262. else
  263. {
  264. quote = "\"";
  265. }
  266. linkerLibraries.append(" ").append(USE_LIB_FLAG[targetCompiler]).append(quote).append(lname).append(USE_LIB_TAIL[targetCompiler]).append(quote);
  267. }
  268. void CppCompiler::addLibraryPath(const char * libPath)
  269. {
  270. linkerOptions.append(" ").append(USE_LIBPATH_FLAG[targetCompiler]).append(libPath).append(USE_LIBPATH_TAIL[targetCompiler]);
  271. if (USE_LIBRPATH_FLAG[targetCompiler])
  272. linkerOptions.append(" ").append(USE_LIBRPATH_FLAG[targetCompiler]).append(libPath);
  273. }
  274. void CppCompiler::_addInclude(StringBuffer &s, const char * paths)
  275. {
  276. if (!paths)
  277. return;
  278. StringBuffer includePath;
  279. for (;;)
  280. {
  281. while (*paths && *paths != ENVSEPCHAR)
  282. includePath.append(*paths++);
  283. if (includePath.length())
  284. s.append(" ").append(USE_INCLUDE_FLAG[targetCompiler]).append(includePath).append(USE_INCLUDE_TAIL[targetCompiler]);
  285. if (!*paths)
  286. break;
  287. paths++;
  288. includePath.clear();
  289. }
  290. }
  291. void CppCompiler::addInclude(const char * paths)
  292. {
  293. _addInclude(compilerOptions, paths);
  294. }
  295. void CppCompiler::addLinkOption(const char * option)
  296. {
  297. if (option && *option)
  298. linkerOptions.append(' ').append(LIB_OPTION_PREFIX[targetCompiler]).append(option);
  299. }
  300. void CppCompiler::addSourceFile(const char * filename)
  301. {
  302. allSources.append(filename);
  303. }
  304. void CppCompiler::writeLogFile(const char* filepath, StringBuffer& log)
  305. {
  306. if(!filepath || !*filepath || !log.length())
  307. return;
  308. Owned <IFile> f = createIFile(filepath);
  309. if(f->exists())
  310. f->remove();
  311. Owned <IFileIO> fio = f->open(IFOcreaterw);
  312. if(fio.get())
  313. fio->write(0, log.length(), log.str());
  314. }
  315. bool CppCompiler::compile()
  316. {
  317. if (abortChecker && abortChecker->abortRequested())
  318. return false;
  319. TIME_SECTION(!verbose ? NULL : onlyCompile ? "compile" : "compile/link");
  320. Owned<IThreadPool> pool = createThreadPool("CCompilerWorker", this, NULL, maxCompileThreads?maxCompileThreads:1, INFINITE);
  321. addCompileOption(COMPILE_ONLY[targetCompiler]);
  322. bool ret = false;
  323. Semaphore finishedCompiling;
  324. int numSubmitted = 0;
  325. atomic_set(&numFailed, 0);
  326. ForEachItemIn(i0, allSources)
  327. {
  328. ret = compileFile(pool, allSources.item(i0), finishedCompiling);
  329. if (!ret)
  330. break;
  331. ++numSubmitted;
  332. }
  333. for (int idx = 0; idx < numSubmitted; idx++)
  334. {
  335. if (abortChecker)
  336. {
  337. while (!finishedCompiling.wait(5*1000))
  338. {
  339. if (abortChecker && abortChecker->abortRequested())
  340. {
  341. PrintLog("Aborting compilation");
  342. pool->stopAll(true);
  343. if (!pool->joinAll(true, 10*1000))
  344. WARNLOG("CCompilerWorker; timed out waiting for threads in pool");
  345. return false;
  346. }
  347. }
  348. }
  349. else
  350. finishedCompiling.wait();
  351. }
  352. if (atomic_read(&numFailed) > 0)
  353. ret = false;
  354. else if (!onlyCompile && !precompileHeader)
  355. ret = doLink();
  356. if (!saveTemps && !onlyCompile)
  357. {
  358. removeTemporaries();
  359. StringBuffer temp;
  360. ForEachItemIn(i2, allSources)
  361. remove(getObjectName(temp.clear(), allSources.item(i2)).str());
  362. }
  363. //Combine logfiles
  364. const char* cclog = ccLogPath.get();
  365. if(!cclog||!*cclog)
  366. cclog = queryCcLogName();
  367. Owned <IFile> dstfile = createIFile(cclog);
  368. dstfile->remove();
  369. Owned<IFileIO> dstIO = dstfile->open(IFOwrite);
  370. ForEachItemIn(i2, logFiles)
  371. {
  372. Owned <IFile> srcfile = createIFile(logFiles.item(i2));
  373. if (srcfile->exists())
  374. {
  375. dstIO->appendFile(srcfile);
  376. srcfile->remove();
  377. }
  378. }
  379. //Don't leave lots of blank log files around if the compile was successful
  380. bool logIsEmpty = (dstIO->size() == 0);
  381. dstIO.clear();
  382. if (ret && logIsEmpty)
  383. dstfile->remove();
  384. pool->joinAll(true, 1000);
  385. return ret;
  386. }
  387. bool CppCompiler::compileFile(IThreadPool * pool, const char * filename, Semaphore & finishedCompiling)
  388. {
  389. if (!filename || *filename == 0)
  390. return false;
  391. StringBuffer cmdline;
  392. cmdline.append(CC_NAME[targetCompiler]);
  393. if (precompileHeader)
  394. cmdline.append(CC_OPTION_PRECOMPILEHEADER[targetCompiler]);
  395. cmdline.append(" \"");
  396. if (sourceDir.length())
  397. {
  398. cmdline.append(sourceDir);
  399. addPathSepChar(cmdline);
  400. }
  401. cmdline.append(filename);
  402. if (!precompileHeader)
  403. cmdline.append(".cpp");
  404. cmdline.append("\" ");
  405. expandCompileOptions(cmdline);
  406. if (useDebugLibrary)
  407. cmdline.append(" ").append(LIBFLAG_DEBUG[targetCompiler]);
  408. else
  409. cmdline.append(" ").append(LIBFLAG_RELEASE[targetCompiler]);
  410. _addInclude(cmdline, stdIncludes);
  411. if (targetCompiler == Vs6CppCompiler)
  412. {
  413. if (targetDir.get())
  414. cmdline.append(" /Fo").append("\"").append(targetDir).append("\"");
  415. cmdline.append(" /Fd").append("\"").append(targetDir).append(createDLL ? SharedObjectPrefix : NULL).append(filename).append(".pdb").append("\"");//MORE: prefer create a single pdb file using coreName
  416. }
  417. else
  418. {
  419. cmdline.append(" -o ").append("\"").append(targetDir).append(filename).append('.');
  420. if (precompileHeader)
  421. cmdline.append(PCH_FILE_EXT[targetCompiler]);
  422. else
  423. cmdline.append(OBJECT_FILE_EXT[targetCompiler]);
  424. cmdline.append("\"");
  425. }
  426. StringBuffer expanded;
  427. expandRootDirectory(expanded, cmdline);
  428. StringBuffer logFile;
  429. logFile.append(filename).append(".log.tmp");
  430. logFiles.append(logFile);
  431. Owned<CCompilerThreadParam> parm;
  432. if (verbose)
  433. PrintLog("%s", expanded.toCharArray());
  434. parm.setown(new CCompilerThreadParam(expanded, finishedCompiling, logFile));
  435. pool->start(parm.get());
  436. return true;
  437. }
  438. void CppCompiler::expandCompileOptions(StringBuffer & target)
  439. {
  440. target.append(" ").append(CC_OPTION_CORE[targetCompiler]).append(" ");
  441. if (targetDebug)
  442. target.append(CC_OPTION_DEBUG[targetCompiler]);
  443. else
  444. target.append(CC_OPTION_RELEASE[targetCompiler]);
  445. target.append(compilerOptions).append(CC_EXTRA_OPTIONS);
  446. }
  447. bool CppCompiler::doLink()
  448. {
  449. StringBuffer cmdline;
  450. cmdline.append(LINK_NAME[targetCompiler]).append(LINK_SEPARATOR[targetCompiler]);
  451. cmdline.append(" ");
  452. if (targetDebug)
  453. cmdline.append(createDLL ? DLL_LINK_OPTION_DEBUG[targetCompiler] : EXE_LINK_OPTION_DEBUG[targetCompiler]);
  454. else
  455. cmdline.append(createDLL ? DLL_LINK_OPTION_RELEASE[targetCompiler] : EXE_LINK_OPTION_RELEASE[targetCompiler]);
  456. cmdline.append(" ");
  457. if (createDLL)
  458. cmdline.append(" ").append(LINK_OPTION_CORE[targetCompiler]);
  459. cmdline.append(stdLibs);
  460. ForEachItemIn(i0, allSources)
  461. cmdline.append(" ").append("\"").append(targetDir).append(allSources.item(i0)).append(".").append(OBJECT_FILE_EXT[targetCompiler]).append("\"");
  462. cmdline.append(linkerOptions);
  463. cmdline.append(linkerLibraries);
  464. StringBuffer outName;
  465. outName.append(createDLL ? SharedObjectPrefix : NULL).append(CORE_NAME).append(createDLL ? SharedObjectExtension : ProcessExtension);
  466. cmdline.append(LINK_TARGET[targetCompiler]).append("\"").append(targetDir).append(outName).append("\"");
  467. StringBuffer temp;
  468. remove(temp.clear().append(targetDir).append(outName).str());
  469. StringBuffer expanded;
  470. expandRootDirectory(expanded, cmdline);
  471. DWORD runcode = 0;
  472. if (verbose)
  473. PrintLog("%s", expanded.toCharArray());
  474. StringBuffer logFile = StringBuffer(CORE_NAME).append("_link.log.tmp");
  475. logFiles.append(logFile);
  476. bool ret = invoke_program(expanded.toCharArray(), runcode, true, logFile) && (runcode == 0);
  477. return ret;
  478. }
  479. void CppCompiler::expandRootDirectory(StringBuffer & expanded, StringBuffer & in)
  480. {
  481. unsigned len = in.length();
  482. unsigned i;
  483. for (i = 0; i < len; i++)
  484. {
  485. char c = in.charAt(i);
  486. if (c == '#')
  487. {
  488. if (compilerRoot)
  489. expanded.append(compilerRoot);
  490. else
  491. expanded.append(DEFAULT_CC_LOCATION[targetCompiler]);
  492. }
  493. else
  494. expanded.append(c);
  495. }
  496. }
  497. StringBuffer & CppCompiler::getObjectName(StringBuffer & out, const char * filename)
  498. {
  499. out.append(targetDir);
  500. splitFilename(filename, NULL, NULL, &out, &out);
  501. return out.append(".").append(OBJECT_FILE_EXT[targetCompiler]);
  502. }
  503. void CppCompiler::removeTemporaries()
  504. {
  505. switch (targetCompiler)
  506. {
  507. case Vs6CppCompiler:
  508. case GccCppCompiler:
  509. {
  510. StringBuffer temp;
  511. remove(temp.clear().append(targetDir).append(CORE_NAME).append(".exp").str());
  512. remove(getObjectName(temp.clear(), CORE_NAME).str());
  513. remove(temp.clear().append(targetDir).append(CORE_NAME).append(".lib").str());
  514. #ifdef _WIN32
  515. remove(temp.clear().append(targetDir).append(CORE_NAME).append(".res.lib").str());
  516. #else
  517. remove(temp.clear().append(targetDir).append(CORE_NAME).append(".res.o.lib").str());
  518. remove(temp.clear().append(targetDir).append("lib").append(CORE_NAME).append(".res.o.so").str());
  519. #endif
  520. break;
  521. }
  522. }
  523. }
  524. void CppCompiler::setDebug(bool _debug)
  525. {
  526. targetDebug = _debug;
  527. }
  528. void CppCompiler::setDebugLibrary(bool debug)
  529. {
  530. useDebugLibrary = debug;
  531. }
  532. void CppCompiler::setCreateExe(bool _createExe)
  533. {
  534. createDLL = !_createExe;
  535. }
  536. void CppCompiler::setOptimizeLevel(unsigned level)
  537. {
  538. const char * option = NULL;
  539. switch (targetCompiler)
  540. {
  541. case Vs6CppCompiler:
  542. switch (level)
  543. {
  544. case 0: option = "/Od"; break;
  545. case 1: option = "/O1"; break;
  546. case 2: option = "/O2"; break;
  547. default: // i.e. 3 or higher
  548. option = "/Ob1gty /G6"; break;
  549. }
  550. break;
  551. case GccCppCompiler:
  552. switch (level)
  553. {
  554. case 0: option = "-O0"; break; // do not optimize
  555. case 1: option = "-O1"; break;
  556. case 2: option = "-O2"; break;
  557. default: // i.e. 3 or higher
  558. option = "-O3"; break;
  559. }
  560. break;
  561. }
  562. if (option)
  563. addCompileOption(option);
  564. }
  565. void CppCompiler::setTargetBitLength(unsigned bitlength)
  566. {
  567. const char * option = NULL;
  568. switch (targetCompiler)
  569. {
  570. case Vs6CppCompiler:
  571. switch (bitlength)
  572. {
  573. case 32: break; // 64-bit windows TBD at present....
  574. default:
  575. throwUnexpected();
  576. }
  577. break;
  578. case GccCppCompiler:
  579. switch (bitlength)
  580. {
  581. case 32: option = "-m32"; break;
  582. case 64: option = "-m64"; break;
  583. default:
  584. throwUnexpected();
  585. }
  586. break;
  587. }
  588. if (option)
  589. addCompileOption(option);
  590. }
  591. void CppCompiler::setCCLogPath(const char* path)
  592. {
  593. if(path && *path)
  594. ccLogPath.set(path);
  595. }
  596. //===========================================================================
  597. bool fileIsOlder(const char *dest, const char *src)
  598. {
  599. int h1 = _open(dest, _O_RDONLY);
  600. if (h1 == -1)
  601. return true;
  602. int h2 = _open(src, _O_RDONLY);
  603. assertex(h2 != -1);
  604. struct _stat stat1;
  605. struct _stat stat2;
  606. _fstat(h1, &stat1);
  607. _fstat(h2, &stat2);
  608. _close(h1);
  609. _close(h2);
  610. return stat1.st_mtime < stat2.st_mtime;
  611. }
  612. //===========================================================================
  613. void setCompilerPath(const char * path, const char * includes, const char * libs, const char * tmpdir, bool verbose)
  614. {
  615. doSetCompilerPath(path, includes, libs, tmpdir, DEFAULT_COMPILER, verbose);
  616. }
  617. void setCompilerPath(const char * path, const char * includes, const char * libs, const char * tmpdir, CompilerType targetCompiler, bool verbose)
  618. {
  619. doSetCompilerPath(path, includes, libs, tmpdir, targetCompiler, verbose);
  620. }
  621. ICppCompiler * createCompiler(const char * coreName, const char * sourceDir, const char * targetDir, bool verbose)
  622. {
  623. return new CppCompiler(coreName, sourceDir, targetDir, DEFAULT_COMPILER, verbose);
  624. }
  625. ICppCompiler * createCompiler(const char * coreName, const char * sourceDir, const char * targetDir, CompilerType targetCompiler, bool verbose)
  626. {
  627. return new CppCompiler(coreName, sourceDir, targetDir, targetCompiler, verbose);
  628. }
  629. //===========================================================================
  630. class CCompilerWorker : public CInterface, implements IPooledThread
  631. {
  632. public:
  633. IMPLEMENT_IINTERFACE;
  634. CCompilerWorker(CppCompiler * _compiler, bool _okToAbort) : compiler(_compiler), okToAbort(_okToAbort)
  635. {
  636. handle = 0;
  637. aborted = false;
  638. }
  639. bool canReuse() { return true; }
  640. bool stop()
  641. {
  642. if (okToAbort)
  643. interrupt_program(handle, true);
  644. aborted = true;
  645. return true;
  646. }
  647. void init(void *_params) { params.set((CCompilerThreadParam *)_params); }
  648. void main()
  649. {
  650. DWORD runcode = 0;
  651. bool success;
  652. aborted = false;
  653. handle = 0;
  654. try
  655. {
  656. success = invoke_program(params->cmdline, runcode, false, params->logfile, &handle, false, okToAbort);
  657. if (success)
  658. wait_program(handle, runcode, true);
  659. }
  660. catch(IException* e)
  661. {
  662. StringBuffer sb;
  663. e->errorMessage(sb);
  664. e->Release();
  665. if (sb.length())
  666. PrintLog("%s", sb.str());
  667. success = false;
  668. }
  669. handle = 0;
  670. if (!success || aborted)
  671. atomic_inc(&compiler->numFailed);
  672. params->finishedCompiling.signal();
  673. return;
  674. }
  675. private:
  676. CppCompiler * compiler;
  677. Owned<CCompilerThreadParam> params;
  678. HANDLE handle;
  679. bool aborted;
  680. bool okToAbort;
  681. };
  682. IPooledThread *CppCompiler::createNew()
  683. {
  684. return new CCompilerWorker(this, (abortChecker != NULL));
  685. }