jcomp.cpp 28 KB

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