jcomp.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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. #include "jregexp.hpp"
  20. #include "jerror.hpp"
  21. #ifdef _WIN32
  22. #include <windows.h>
  23. #include <winbase.h>
  24. #include <io.h>
  25. #else
  26. #include <sys/wait.h>
  27. #endif
  28. #include <fcntl.h>
  29. #include <sys/types.h>
  30. #include <sys/stat.h>
  31. #include <stdio.h>
  32. #include "jfile.hpp"
  33. #include "jdebug.hpp"
  34. #include "jcomp.ipp"
  35. #define CC_EXTRA_OPTIONS ""
  36. #ifdef GENERATE_LISTING
  37. #undef CC_EXTRA_OPTIONS
  38. #define CC_EXTRA_OPTIONS " /FAs"
  39. #endif
  40. #ifdef _WIN32
  41. #define DEFAULT_COMPILER Vs6CppCompiler
  42. #else
  43. #define DEFAULT_COMPILER GccCppCompiler
  44. #endif
  45. //---------------------------------------------------------------------------
  46. #define BASE_ADDRESS "0x00480000"
  47. //#define BASE_ADDRESS "0x10000000"
  48. static const char * CC_NAME[] = { "\"#" PATHSEPSTR "bin" PATHSEPSTR "cl.bat\"", "\"#" PATHSEPSTR "bin" PATHSEPSTR "g++\"" };
  49. static const char * LINK_NAME[] = { "\"#" PATHSEPSTR "bin" PATHSEPSTR "link.bat\"", "\"#" PATHSEPSTR "bin" PATHSEPSTR "g++\"" };
  50. static const char * LIB_DIR[] = { "\"#\\lib\"", "\"#/lib\"" };
  51. static const char * LIB_OPTION_PREFIX[] = { "", "-Wl," };
  52. static const char * USE_LIBPATH_FLAG[] = { "/libpath:\"", "-L" };
  53. static const char * USE_LIBPATH_TAIL[] = { "\"", "" };
  54. static const char * USE_LIBRPATH_FLAG[] = { NULL, "-Wl,-rpath," };
  55. static const char * USE_LIB_FLAG[] = { "", "-l" };
  56. static const char * USE_LIB_TAIL[] = { ".lib", "" };
  57. static const char * USE_INCLUDE_FLAG[] = { "/I\"", "\"-I" };
  58. static const char * USE_DEFINE_FLAG[] = { "/D", "-D" };
  59. static const char * USE_INCLUDE_TAIL[] = { "\"", "\"" };
  60. static const char * INCLUDEPATH[] = { "\"#\\include\"", "\"#/include\"" };
  61. static const char * LINK_SEPARATOR[] = { " /link ", " " };
  62. static const char * OBJECT_FILE_EXT[] = { "obj", "o" };
  63. static const char * PCH_FILE_EXT[] = { "", "gch" };
  64. static const char * LIBFLAG_DEBUG[] = { "/MDd", "" };
  65. static const char * LIBFLAG_RELEASE[] = { "/MD", "" };
  66. static const char * COMPILE_ONLY[] = { "/c", "-c" };
  67. static const char * CC_OPTION_CORE[] = { "", "-std=c++11 -fvisibility=hidden -DUSE_VISIBILITY=1 -Werror -Wno-tautological-compare" };
  68. static const char * LINK_OPTION_CORE[] = { "/DLL /libpath:." , "" };
  69. static const char * CC_OPTION_DEBUG[] = { "/Zm500 /EHsc /GR /Zi /nologo /bigobj", "-g -fPIC -O0" };
  70. static const char * CC_OPTION_RELEASE[] = { "/Zm500 /EHsc /GR /Oi /Ob1 /GF /nologo /bigobj", "-fPIC -O0" };
  71. static const char * CC_OPTION_PRECOMPILEHEADER[] = { "", " -x c++-header" };
  72. #ifdef __APPLE__
  73. static const char * DLL_LINK_OPTION_DEBUG[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO /DEBUG /DEBUGTYPE:CV", "-g -shared -L. -fPIC -pipe -O0" };
  74. static const char * EXE_LINK_OPTION_DEBUG[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO /DEBUG /DEBUGTYPE:CV", "-g -L. -fPIC -pipe -O0 -Wl,-export_dynamic -v" };
  75. static const char * DLL_LINK_OPTION_RELEASE[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO", "-shared -L. -fPIC -pipe -O0" };
  76. static const char * EXE_LINK_OPTION_RELEASE[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO", "-L. -fPIC -pipe -O0 -Wl,-export_dynamic -v" };
  77. #else
  78. static const char * DLL_LINK_OPTION_DEBUG[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO /DEBUG /DEBUGTYPE:CV", "-g -shared -L. -fPIC -pipe -O0" };
  79. static const char * EXE_LINK_OPTION_DEBUG[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO /DEBUG /DEBUGTYPE:CV", "-g -L. -Wl,-E -fPIC -pipe -O0" };
  80. static const char * DLL_LINK_OPTION_RELEASE[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO", "-shared -L. -fPIC -pipe -O0" };
  81. static const char * EXE_LINK_OPTION_RELEASE[] = { "/BASE:" BASE_ADDRESS " /NOLOGO /LARGEADDRESSAWARE /INCREMENTAL:NO", "-L. -Wl,-E -fPIC -pipe -O0" };
  82. #endif
  83. static const char * LINK_TARGET[] = { " /out:", " -o " };
  84. static const char * DEFAULT_CC_LOCATION[] = { ".", "." };
  85. //===========================================================================
  86. static StringAttr compilerRoot;
  87. static StringAttr stdIncludes;
  88. static StringBuffer stdLibs;
  89. static StringBuffer &dequote(StringBuffer &in)
  90. {
  91. if (in.length() >= 2 && in.charAt(0)=='"' && in.charAt(in.length()-1)=='"')
  92. {
  93. in.remove(in.length()-1, 1);
  94. in.remove(0, 1);
  95. }
  96. return in;
  97. }
  98. static void doSetCompilerPath(const char * path, const char * includes, const char * libs, const char * tmpdir, unsigned targetCompiler, bool verbose)
  99. {
  100. if (!includes)
  101. includes = INCLUDEPATH[targetCompiler];
  102. if (!libs)
  103. libs = LIB_DIR[targetCompiler];
  104. if (verbose)
  105. {
  106. PrintLog("Include directory set to %s", includes);
  107. PrintLog("Library directory set to %s", libs);
  108. }
  109. compilerRoot.set(path ? path : targetCompiler==GccCppCompiler ? "/usr" : ".\\CL");
  110. stdIncludes.set(includes);
  111. stdLibs.clear();
  112. for (;;)
  113. {
  114. StringBuffer thislib;
  115. while (*libs && *libs != ENVSEPCHAR)
  116. thislib.append(*libs++);
  117. if (thislib.length())
  118. {
  119. stdLibs.append(" ").append(USE_LIBPATH_FLAG[targetCompiler]).append(thislib).append(USE_LIBPATH_TAIL[targetCompiler]);
  120. if (USE_LIBRPATH_FLAG[targetCompiler])
  121. stdLibs.append(" ").append(USE_LIBRPATH_FLAG[targetCompiler]).append(thislib);
  122. }
  123. if (!*libs)
  124. break;
  125. libs++;
  126. }
  127. StringBuffer fname;
  128. if (path)
  129. {
  130. const char *finger = CC_NAME[targetCompiler];
  131. while (*finger)
  132. {
  133. if (*finger == '#')
  134. fname.append(path);
  135. else
  136. fname.append(*finger);
  137. finger++;
  138. }
  139. #if defined(__linux__)
  140. StringBuffer clbin_dir;
  141. const char* dir_end = strrchr(fname, '/');
  142. if(dir_end == NULL)
  143. clbin_dir.append(".");
  144. else
  145. clbin_dir.append((dir_end - fname.str()) + 1, fname.str());
  146. StringBuffer pathenv(clbin_dir.str());
  147. const char* oldpath = getenv("PATH");
  148. if(oldpath != NULL && *oldpath != '\0')
  149. pathenv.append(":").append(oldpath);
  150. setenv("PATH", pathenv.str(), 1);
  151. #endif
  152. }
  153. else
  154. {
  155. fname.append(compilerRoot).append(CC_NAME[targetCompiler]);
  156. fname.replaceString("#",NULL);
  157. }
  158. if (verbose)
  159. PrintLog("Compiler path set to %s", fname.str());
  160. dequote(fname);
  161. #ifdef _WIN32
  162. if (_access(fname.str(), 4))
  163. {
  164. #else
  165. #if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
  166. struct stat filestatus;
  167. int r = stat(fname.str(), &filestatus);
  168. if ( (r != 0)
  169. || (!S_ISREG(filestatus.st_mode))
  170. || ((filestatus.st_mode&(S_IXOTH|S_IXGRP|S_IXUSR))==0))
  171. {
  172. if (r == -1) errno = ENOENT;
  173. #endif
  174. #endif
  175. if (verbose)
  176. PrintLog("SetCompilerPath - no compiler found");
  177. throw makeOsExceptionV(GetLastError(), "setCompilerPath could not locate compiler %s", fname.str());
  178. }
  179. if(tmpdir && *tmpdir)
  180. {
  181. //MORE: this should be done for the child process instead of the parent but invoke does not let me do it
  182. #if defined(__linux__)
  183. setenv("TMPDIR", tmpdir, 1);
  184. #endif
  185. #ifdef _WIN32
  186. StringBuffer tmpbuf;
  187. tmpbuf.append("TMP=").append(tmpdir);
  188. _putenv(tmpbuf.str());
  189. #endif
  190. }
  191. }
  192. //===========================================================================
  193. class CCompilerThreadParam : public CInterface
  194. {
  195. public:
  196. CCompilerThreadParam(const StringBuffer & _cmdline, Semaphore & _finishedCompiling, const StringBuffer & _logfile) : cmdline(_cmdline), logfile(_logfile), finishedCompiling(_finishedCompiling) {};
  197. StringBuffer cmdline;
  198. StringBuffer logfile;
  199. Semaphore & finishedCompiling;
  200. };
  201. //===========================================================================
  202. static void setDirectoryPrefix(StringAttr & target, const char * source)
  203. {
  204. if (source && *source)
  205. {
  206. StringBuffer temp;
  207. target.set(addDirectoryPrefix(temp, source));
  208. }
  209. }
  210. CppCompiler::CppCompiler(const char * _coreName, const char * _sourceDir, const char * _targetDir, unsigned _targetCompiler, bool _verbose)
  211. {
  212. coreName.set(_coreName);
  213. targetCompiler = _targetCompiler;
  214. createDLL = true;
  215. #ifdef _DEBUG
  216. setDebug(true);
  217. setDebugLibrary(true);
  218. #else
  219. setDebug(false);
  220. setDebugLibrary(false);
  221. #endif
  222. setDirectoryPrefix(sourceDir, _sourceDir);
  223. setDirectoryPrefix(targetDir, _targetDir);
  224. maxCompileThreads = 1;
  225. onlyCompile = false;
  226. verbose = _verbose;
  227. saveTemps = false;
  228. abortChecker = NULL;
  229. precompileHeader = false;
  230. linkFailed = false;
  231. }
  232. void CppCompiler::addCompileOption(const char * option)
  233. {
  234. compilerOptions.append(' ').append(option);
  235. }
  236. void CppCompiler::setPrecompileHeader(bool _pch)
  237. {
  238. if (targetCompiler!=GccCppCompiler)
  239. throw MakeStringException(0, "precompiled header generation only supported for g++ and compatible compilers");
  240. precompileHeader = _pch;
  241. }
  242. bool CppCompiler::fireException(IException *e)
  243. {
  244. CriticalBlock block(cs);
  245. exceptions.append(*LINK(e));
  246. return true;
  247. }
  248. void CppCompiler::addDefine(const char * symbolName, const char * value)
  249. {
  250. compilerOptions.append(" ").append(USE_DEFINE_FLAG[targetCompiler]).append(symbolName);
  251. if (value)
  252. compilerOptions.append('=').append(value);
  253. }
  254. void CppCompiler::addLibrary(const char * libName)
  255. {
  256. if (verbose)
  257. PrintLog("addLibrary %s", libName);
  258. const char* lname = libName;
  259. const char * quote;
  260. 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
  261. if (targetCompiler == GccCppCompiler)
  262. {
  263. // It seems gcc compiler doesn't like things like -lmydir/libx.so
  264. splitFilename(libName, &path, &path, &tail, &tail);
  265. if(path.length())
  266. {
  267. addLibraryPath(path);
  268. lname = tail.str();
  269. // HACK - make it work with plugins. This should be handled at caller end!
  270. if (strncmp(lname, "lib", 3) == 0)
  271. lname += 3;
  272. }
  273. quote = NULL; //quoting lib names with gcc causes link error (lib not found)
  274. }
  275. else
  276. {
  277. quote = "\"";
  278. }
  279. linkerLibraries.append(" ").append(USE_LIB_FLAG[targetCompiler]).append(quote).append(lname).append(USE_LIB_TAIL[targetCompiler]).append(quote);
  280. }
  281. void CppCompiler::addLibraryPath(const char * libPath)
  282. {
  283. linkerOptions.append(" ").append(USE_LIBPATH_FLAG[targetCompiler]).append(libPath).append(USE_LIBPATH_TAIL[targetCompiler]);
  284. if (USE_LIBRPATH_FLAG[targetCompiler])
  285. linkerOptions.append(" ").append(USE_LIBRPATH_FLAG[targetCompiler]).append(libPath);
  286. }
  287. void CppCompiler::_addInclude(StringBuffer &s, const char * paths)
  288. {
  289. if (!paths)
  290. return;
  291. StringBuffer includePath;
  292. for (;;)
  293. {
  294. while (*paths && *paths != ENVSEPCHAR)
  295. includePath.append(*paths++);
  296. if (includePath.length())
  297. s.append(" ").append(USE_INCLUDE_FLAG[targetCompiler]).append(includePath).append(USE_INCLUDE_TAIL[targetCompiler]);
  298. if (!*paths)
  299. break;
  300. paths++;
  301. includePath.clear();
  302. }
  303. }
  304. void CppCompiler::addInclude(const char * paths)
  305. {
  306. _addInclude(compilerOptions, paths);
  307. }
  308. void CppCompiler::addLinkOption(const char * option)
  309. {
  310. if (option && *option)
  311. linkerOptions.append(' ').append(LIB_OPTION_PREFIX[targetCompiler]).append(option);
  312. }
  313. void CppCompiler::addSourceFile(const char * filename)
  314. {
  315. DBGLOG("addSourceFile %s", filename);
  316. allSources.append(filename);
  317. }
  318. void CppCompiler::addObjectFile(const char * filename)
  319. {
  320. linkerLibraries.append(" ").append(filename);
  321. }
  322. void CppCompiler::writeLogFile(const char* filepath, StringBuffer& log)
  323. {
  324. if(!filepath || !*filepath || !log.length())
  325. return;
  326. Owned <IFile> f = createIFile(filepath);
  327. if(f->exists())
  328. f->remove();
  329. Owned <IFileIO> fio = f->open(IFOcreaterw);
  330. if(fio.get())
  331. fio->write(0, log.length(), log.str());
  332. }
  333. bool CppCompiler::compile()
  334. {
  335. if (abortChecker && abortChecker->abortRequested())
  336. return false;
  337. TIME_SECTION(!verbose ? NULL : onlyCompile ? "compile" : "compile/link");
  338. Owned<IThreadPool> pool = createThreadPool("CCompilerWorker", this, this, maxCompileThreads?maxCompileThreads:1, INFINITE);
  339. addCompileOption(COMPILE_ONLY[targetCompiler]);
  340. bool ret = false;
  341. Semaphore finishedCompiling;
  342. int numSubmitted = 0;
  343. numFailed.store(0);
  344. ForEachItemIn(i0, allSources)
  345. {
  346. ret = compileFile(pool, allSources.item(i0), finishedCompiling);
  347. if (!ret)
  348. break;
  349. ++numSubmitted;
  350. }
  351. for (int idx = 0; idx < numSubmitted; idx++)
  352. {
  353. if (abortChecker)
  354. {
  355. while (!finishedCompiling.wait(5*1000))
  356. {
  357. if (abortChecker && abortChecker->abortRequested())
  358. {
  359. PrintLog("Aborting compilation");
  360. pool->stopAll(true);
  361. if (!pool->joinAll(true, 10*1000))
  362. WARNLOG("CCompilerWorker; timed out waiting for threads in pool");
  363. return false;
  364. }
  365. }
  366. }
  367. else
  368. finishedCompiling.wait();
  369. }
  370. if (numFailed > 0)
  371. ret = false;
  372. else if (!onlyCompile && !precompileHeader)
  373. ret = doLink();
  374. if (!saveTemps && !onlyCompile)
  375. {
  376. removeTemporaries();
  377. StringBuffer temp;
  378. ForEachItemIn(i2, allSources)
  379. remove(getObjectName(temp.clear(), allSources.item(i2)).str());
  380. }
  381. //Combine logfiles
  382. const char* cclog = ccLogPath.get();
  383. if(!cclog||!*cclog)
  384. cclog = queryCcLogName();
  385. Owned <IFile> dstfile = createIFile(cclog);
  386. dstfile->remove();
  387. Owned<IFileIO> dstIO = dstfile->open(IFOwrite);
  388. ForEachItemIn(i2, logFiles)
  389. {
  390. Owned <IFile> srcfile = createIFile(logFiles.item(i2));
  391. if (srcfile->exists())
  392. {
  393. dstIO->appendFile(srcfile);
  394. srcfile->remove();
  395. }
  396. }
  397. //Don't leave lots of blank log files around if the compile was successful
  398. bool logIsEmpty = (dstIO->size() == 0);
  399. dstIO.clear();
  400. if (ret && logIsEmpty)
  401. dstfile->remove();
  402. pool->joinAll(true, 1000);
  403. return ret;
  404. }
  405. bool CppCompiler::compileFile(IThreadPool * pool, const char * filename, Semaphore & finishedCompiling)
  406. {
  407. if (!filename || *filename == 0)
  408. return false;
  409. StringBuffer cmdline;
  410. cmdline.append(CC_NAME[targetCompiler]);
  411. if (precompileHeader)
  412. cmdline.append(CC_OPTION_PRECOMPILEHEADER[targetCompiler]);
  413. cmdline.append(" \"");
  414. if (sourceDir.length())
  415. {
  416. cmdline.append(sourceDir);
  417. addPathSepChar(cmdline);
  418. }
  419. cmdline.append(filename);
  420. cmdline.append("\" ");
  421. expandCompileOptions(cmdline);
  422. if (useDebugLibrary)
  423. cmdline.append(" ").append(LIBFLAG_DEBUG[targetCompiler]);
  424. else
  425. cmdline.append(" ").append(LIBFLAG_RELEASE[targetCompiler]);
  426. _addInclude(cmdline, stdIncludes);
  427. if (targetCompiler == Vs6CppCompiler)
  428. {
  429. if (targetDir.get())
  430. cmdline.append(" /Fo").append("\"").append(targetDir).append("\"");
  431. StringBuffer basename;
  432. splitFilename(filename, &basename, &basename, &basename, NULL);
  433. cmdline.append(" /Fd").append("\"").append(targetDir).append(createDLL ? SharedObjectPrefix : NULL).append(filename).append(".pdb").append("\"");//MORE: prefer create a single pdb file using coreName
  434. }
  435. else
  436. {
  437. cmdline.append(" -o ").append("\"");
  438. if (precompileHeader)
  439. cmdline.append(targetDir).append(filename).append('.').append(PCH_FILE_EXT[targetCompiler]);
  440. else
  441. getObjectName(cmdline, filename);
  442. cmdline.append("\"");
  443. }
  444. StringBuffer expanded;
  445. expandRootDirectory(expanded, cmdline);
  446. StringBuffer logFile;
  447. logFile.append(filename).append(".log.tmp");
  448. logFiles.append(logFile);
  449. Owned<CCompilerThreadParam> parm;
  450. if (verbose)
  451. PrintLog("%s", expanded.str());
  452. parm.setown(new CCompilerThreadParam(expanded, finishedCompiling, logFile));
  453. pool->start(parm.get());
  454. return true;
  455. }
  456. void CppCompiler::extractErrors(IArrayOf<IError> & errors)
  457. {
  458. ForEachItemIn(i, exceptions)
  459. {
  460. IException & cur = exceptions.item(i);
  461. StringBuffer msg;
  462. cur.errorMessage(msg);
  463. errors.append(*createError(JLIBERR_CppCompileError, msg, nullptr));
  464. }
  465. const char* cclog = ccLogPath.get();
  466. if(!cclog||!*cclog)
  467. cclog = queryCcLogName();
  468. Owned <IFile> logfile = createIFile(cclog);
  469. if (!logfile->exists())
  470. return;
  471. try
  472. {
  473. StringBuffer file;
  474. file.loadFile(logfile);
  475. RegExpr vsErrorPattern("^{.+}({[0-9]+}) : error {.*$}");
  476. RegExpr vsLinkErrorPattern("^{.+} : error {.*$}");
  477. //cpperr.ecl:7:10: error: ‘syntaxError’ was not declared in this scope
  478. RegExpr gccErrorPattern("^{.+}:{[0-9]+}:{[0-9]+}: {[a-z]+}: {.*$}");
  479. RegExpr gccErrorPattern2("^{.+}:{[0-9]+}: {[a-z]+}: {.*$}");
  480. RegExpr gccLinkErrorPattern("^{.+}:{[0-9]+}: {.*$}"); // undefined reference
  481. RegExpr gccLinkErrorPattern2("^.+ld: {.*$}"); // fail to find library etc.
  482. RegExpr gccExitStatusPattern("^.*exit status$"); // collect2: error: ld returned 1 exit status
  483. const char * cur = file.str();
  484. do
  485. {
  486. const char * newline = strchr(cur, '\n');
  487. StringAttr next;
  488. if (newline)
  489. {
  490. next.set(cur, newline-cur);
  491. cur = newline+1;
  492. if (*cur == '\r')
  493. cur++;
  494. }
  495. else
  496. {
  497. next.set(cur);
  498. cur = NULL;
  499. }
  500. if (gccExitStatusPattern.find(next))
  501. {
  502. //ignore
  503. }
  504. else if (gccErrorPattern.find(next))
  505. {
  506. StringBuffer filename, line, column, kind, msg;
  507. gccErrorPattern.findstr(filename, 1);
  508. gccErrorPattern.findstr(line, 2);
  509. gccErrorPattern.findstr(column, 3);
  510. gccErrorPattern.findstr(kind, 4);
  511. gccErrorPattern.findstr(msg, 5);
  512. if (strieq(kind, "error"))
  513. errors.append(*createError(CategoryError, SeverityError, JLIBERR_CppCompileError, msg.str(), filename.str(), atoi(line), atoi(column), 0));
  514. else
  515. errors.append(*createError(CategoryCpp, SeverityWarning, JLIBERR_CppCompileError, msg.str(), filename.str(), atoi(line), atoi(column), 0));
  516. }
  517. else if (gccErrorPattern2.find(next))
  518. {
  519. StringBuffer filename, line, kind, msg;
  520. gccErrorPattern2.findstr(filename, 1);
  521. gccErrorPattern2.findstr(line, 2);
  522. gccErrorPattern2.findstr(kind, 3);
  523. gccErrorPattern2.findstr(msg, 4);
  524. if (strieq(kind, "error"))
  525. errors.append(*createError(CategoryError, SeverityError, JLIBERR_CppCompileError, msg.str(), filename.str(), atoi(line), 0, 0));
  526. else
  527. errors.append(*createError(CategoryCpp, SeverityWarning, JLIBERR_CppCompileError, msg.str(), filename.str(), atoi(line), 0, 0));
  528. }
  529. else if (gccLinkErrorPattern.find(next))
  530. {
  531. StringBuffer filename, line, msg;
  532. gccLinkErrorPattern.findstr(filename, 1);
  533. gccLinkErrorPattern.findstr(line, 2);
  534. gccLinkErrorPattern.findstr(msg, 3);
  535. ErrorSeverity severity = linkFailed ? SeverityError : SeverityWarning;
  536. errors.append(*createError(CategoryError, severity, JLIBERR_CppCompileError, msg.str(), filename.str(), atoi(line), 0, 0));
  537. }
  538. else if (gccLinkErrorPattern2.find(next))
  539. {
  540. StringBuffer msg("C++ link error: ");
  541. gccLinkErrorPattern2.findstr(msg, 1);
  542. ErrorSeverity severity = linkFailed ? SeverityError : SeverityWarning;
  543. errors.append(*createError(CategoryError, severity, JLIBERR_CppCompileError, msg.str(), NULL, 0, 0, 0));
  544. }
  545. else if (vsErrorPattern.find(next))
  546. {
  547. StringBuffer filename, line, msg("C++ compiler error: ");
  548. vsErrorPattern.findstr(filename, 1);
  549. vsErrorPattern.findstr(line, 2);
  550. vsErrorPattern.findstr(msg, 3);
  551. errors.append(*createError(CategoryError, SeverityError, JLIBERR_CppCompileError, msg.str(), filename.str(), atoi(line), 0, 0));
  552. }
  553. else if (vsLinkErrorPattern.find(next))
  554. {
  555. StringBuffer filename, msg("C++ link error: ");
  556. vsLinkErrorPattern.findstr(filename, 1);
  557. vsLinkErrorPattern.findstr(msg, 2);
  558. errors.append(*createError(CategoryError, SeverityError, JLIBERR_CppCompileError, msg.str(), filename.str(), 0, 0, 0));
  559. }
  560. } while (cur);
  561. }
  562. catch (IException * e)
  563. {
  564. e->Release();
  565. }
  566. }
  567. void CppCompiler::expandCompileOptions(StringBuffer & target)
  568. {
  569. target.append(" ").append(CC_OPTION_CORE[targetCompiler]).append(" ");
  570. if (targetDebug)
  571. target.append(CC_OPTION_DEBUG[targetCompiler]);
  572. else
  573. target.append(CC_OPTION_RELEASE[targetCompiler]);
  574. target.append(compilerOptions).append(CC_EXTRA_OPTIONS);
  575. }
  576. bool CppCompiler::doLink()
  577. {
  578. StringBuffer cmdline;
  579. cmdline.append(LINK_NAME[targetCompiler]).append(LINK_SEPARATOR[targetCompiler]);
  580. cmdline.append(" ");
  581. if (targetDebug)
  582. cmdline.append(createDLL ? DLL_LINK_OPTION_DEBUG[targetCompiler] : EXE_LINK_OPTION_DEBUG[targetCompiler]);
  583. else
  584. cmdline.append(createDLL ? DLL_LINK_OPTION_RELEASE[targetCompiler] : EXE_LINK_OPTION_RELEASE[targetCompiler]);
  585. cmdline.append(" ");
  586. if (createDLL)
  587. cmdline.append(" ").append(LINK_OPTION_CORE[targetCompiler]);
  588. cmdline.append(stdLibs);
  589. ForEachItemIn(i0, allSources)
  590. {
  591. StringBuffer objFilename;
  592. getObjectName(objFilename, allSources.item(i0));
  593. cmdline.append(" ").append("\"").append(objFilename).append("\"");
  594. }
  595. cmdline.append(linkerOptions);
  596. cmdline.append(linkerLibraries);
  597. StringBuffer outName;
  598. outName.append(createDLL ? SharedObjectPrefix : NULL).append(coreName).append(createDLL ? SharedObjectExtension : ProcessExtension);
  599. cmdline.append(LINK_TARGET[targetCompiler]).append("\"").append(targetDir).append(outName).append("\"");
  600. StringBuffer temp;
  601. remove(temp.clear().append(targetDir).append(outName).str());
  602. StringBuffer expanded;
  603. expandRootDirectory(expanded, cmdline);
  604. DWORD runcode = 0;
  605. if (verbose)
  606. PrintLog("%s", expanded.str());
  607. StringBuffer logFile = StringBuffer(coreName).append("_link.log.tmp");
  608. logFiles.append(logFile);
  609. bool ret;
  610. try
  611. {
  612. ret = invoke_program(expanded.str(), runcode, true, logFile, nullptr, true) && (runcode == 0);
  613. }
  614. catch (IException * e)
  615. {
  616. exceptions.append(*e);
  617. ret = false;
  618. }
  619. linkFailed = !ret;
  620. return ret;
  621. }
  622. void CppCompiler::expandRootDirectory(StringBuffer & expanded, StringBuffer & in)
  623. {
  624. unsigned len = in.length();
  625. unsigned i;
  626. for (i = 0; i < len; i++)
  627. {
  628. char c = in.charAt(i);
  629. if (c == '#')
  630. {
  631. if (compilerRoot)
  632. expanded.append(compilerRoot);
  633. else
  634. expanded.append(DEFAULT_CC_LOCATION[targetCompiler]);
  635. }
  636. else
  637. expanded.append(c);
  638. }
  639. }
  640. StringBuffer & CppCompiler::getObjectName(StringBuffer & out, const char * filename)
  641. {
  642. out.append(targetDir);
  643. if (targetCompiler == Vs6CppCompiler)
  644. splitFilename(filename, NULL, NULL, &out, NULL);
  645. else
  646. splitFilename(filename, NULL, NULL, &out, &out);
  647. return out.append(".").append(OBJECT_FILE_EXT[targetCompiler]);
  648. }
  649. void CppCompiler::removeTemporaries()
  650. {
  651. DBGLOG("Remove temporaries");
  652. StringBuffer temp;
  653. switch (targetCompiler)
  654. {
  655. case Vs6CppCompiler:
  656. {
  657. removeFileTraceIfFail(temp.clear().append(targetDir).append(coreName).append(".exp").str());
  658. removeFileTraceIfFail(temp.clear().append(targetDir).append(coreName).append(".lib").str());
  659. removeFileTraceIfFail(temp.clear().append(targetDir).append(coreName).append(".res").str());
  660. break;
  661. }
  662. case GccCppCompiler:
  663. {
  664. temp.clear().append(coreName).append(".res.s*");
  665. DBGLOG("Remove %s%s",targetDir.str(), temp.str());
  666. Owned<IDirectoryIterator> resTemps = createDirectoryIterator(targetDir, temp.str());
  667. ForEach(*resTemps)
  668. {
  669. removeFileTraceIfFail(resTemps->getName(temp.clear().append(targetDir)).str());
  670. }
  671. break;
  672. }
  673. }
  674. }
  675. void CppCompiler::setDebug(bool _debug)
  676. {
  677. targetDebug = _debug;
  678. }
  679. void CppCompiler::setDebugLibrary(bool debug)
  680. {
  681. useDebugLibrary = debug;
  682. }
  683. void CppCompiler::setCreateExe(bool _createExe)
  684. {
  685. createDLL = !_createExe;
  686. }
  687. void CppCompiler::setOptimizeLevel(unsigned level)
  688. {
  689. const char * option = NULL;
  690. switch (targetCompiler)
  691. {
  692. case Vs6CppCompiler:
  693. switch (level)
  694. {
  695. case 0: option = "/Od"; break;
  696. case 1: option = "/O1"; break;
  697. case 2: option = "/O2"; break;
  698. default: // i.e. 3 or higher
  699. option = "/Ob1gty /G6"; break;
  700. }
  701. break;
  702. case GccCppCompiler:
  703. switch (level)
  704. {
  705. case 0: option = "-O0"; break; // do not optimize
  706. case 1: option = "-O1"; break;
  707. case 2: option = "-O2"; break;
  708. default: // i.e. 3 or higher
  709. option = "-O3"; break;
  710. }
  711. break;
  712. }
  713. if (option)
  714. addCompileOption(option);
  715. }
  716. void CppCompiler::setTargetBitLength(unsigned bitlength)
  717. {
  718. const char * option = NULL;
  719. switch (targetCompiler)
  720. {
  721. case Vs6CppCompiler:
  722. switch (bitlength)
  723. {
  724. case 32: break; // 64-bit windows TBD at present....
  725. default:
  726. throwUnexpected();
  727. }
  728. break;
  729. case GccCppCompiler:
  730. #if defined (_ARCH_X86_64_) || defined(_ARCH_X86_)
  731. // Note that gcc only seems to support these options on the x86 architecture
  732. switch (bitlength)
  733. {
  734. case 32: option = "-m32"; break;
  735. case 64: option = "-m64"; break;
  736. default:
  737. throwUnexpected();
  738. }
  739. #endif
  740. break;
  741. }
  742. if (option)
  743. addCompileOption(option);
  744. }
  745. void CppCompiler::setCCLogPath(const char* path)
  746. {
  747. if(path && *path)
  748. ccLogPath.set(path);
  749. }
  750. //===========================================================================
  751. bool fileIsOlder(const char *dest, const char *src)
  752. {
  753. int h1 = _open(dest, _O_RDONLY);
  754. if (h1 == -1)
  755. return true;
  756. int h2 = _open(src, _O_RDONLY);
  757. assertex(h2 != -1);
  758. struct _stat stat1;
  759. struct _stat stat2;
  760. _fstat(h1, &stat1);
  761. _fstat(h2, &stat2);
  762. _close(h1);
  763. _close(h2);
  764. return stat1.st_mtime < stat2.st_mtime;
  765. }
  766. //===========================================================================
  767. void setCompilerPath(const char * path, const char * includes, const char * libs, const char * tmpdir, bool verbose)
  768. {
  769. doSetCompilerPath(path, includes, libs, tmpdir, DEFAULT_COMPILER, verbose);
  770. }
  771. void setCompilerPath(const char * path, const char * includes, const char * libs, const char * tmpdir, CompilerType targetCompiler, bool verbose)
  772. {
  773. doSetCompilerPath(path, includes, libs, tmpdir, targetCompiler, verbose);
  774. }
  775. ICppCompiler * createCompiler(const char * coreName, const char * sourceDir, const char * targetDir, bool verbose)
  776. {
  777. return new CppCompiler(coreName, sourceDir, targetDir, DEFAULT_COMPILER, verbose);
  778. }
  779. ICppCompiler * createCompiler(const char * coreName, const char * sourceDir, const char * targetDir, CompilerType targetCompiler, bool verbose)
  780. {
  781. return new CppCompiler(coreName, sourceDir, targetDir, targetCompiler, verbose);
  782. }
  783. //===========================================================================
  784. class CCompilerWorker : implements IPooledThread, public CInterface
  785. {
  786. public:
  787. IMPLEMENT_IINTERFACE;
  788. CCompilerWorker(CppCompiler * _compiler, bool _okToAbort) : compiler(_compiler), okToAbort(_okToAbort)
  789. {
  790. handle = 0;
  791. aborted = false;
  792. }
  793. virtual bool canReuse() const override { return true; }
  794. virtual bool stop() override
  795. {
  796. if (okToAbort)
  797. interrupt_program(handle, true);
  798. aborted = true;
  799. return true;
  800. }
  801. virtual void init(void *_params) override { params.set((CCompilerThreadParam *)_params); }
  802. virtual void threadmain() override
  803. {
  804. DWORD runcode = 0;
  805. bool success;
  806. aborted = false;
  807. handle = 0;
  808. Owned<IException> error;
  809. try
  810. {
  811. success = invoke_program(params->cmdline, runcode, false, params->logfile, &handle, true, okToAbort);
  812. if (success)
  813. wait_program(handle, runcode, true);
  814. }
  815. catch(IException* e)
  816. {
  817. StringBuffer sb;
  818. e->errorMessage(sb);
  819. error.setown(e);
  820. if (sb.length())
  821. PrintLog("%s", sb.str());
  822. success = false;
  823. }
  824. handle = 0;
  825. if (!success || aborted || runcode != 0)
  826. compiler->numFailed++;
  827. params->finishedCompiling.signal();
  828. if (error)
  829. throw error.getClear();
  830. }
  831. private:
  832. CppCompiler * compiler;
  833. Owned<CCompilerThreadParam> params;
  834. HANDLE handle;
  835. bool aborted;
  836. bool okToAbort;
  837. };
  838. IPooledThread *CppCompiler::createNew()
  839. {
  840. return new CCompilerWorker(this, (abortChecker != NULL));
  841. }