BlContext.cpp 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929
  1. #pragma warning(disable:4996)
  2. #define MAX_SEG_COUNT 1024
  3. #include "BlContext.h"
  4. #include "BlCvParser.h"
  5. #include "BlCodeView.h"
  6. #include "BeefySysLib/util/PerfTimer.h"
  7. #include "../Compiler/BfAstAllocator.h"
  8. #include "../COFFData.h"
  9. #include "BeefySysLib/FileStream.h"
  10. #include "BeefySysLib/CachedDataStream.h"
  11. #include "../Backend/BeCOFFObject.h"
  12. #include "../Compiler/BfDemangler.h"
  13. #include <time.h>
  14. #include <iostream>
  15. #include <stdlib.h>
  16. #include <direct.h>
  17. #include "codeview/cvinfo.h"
  18. #define GET(T) *((T*)(data += sizeof(T)) - 1)
  19. #define PTR_ALIGN(ptr, origPtr, alignSize) ptr = ( (origPtr)+( ((ptr - origPtr) + (alignSize - 1)) & ~(alignSize - 1) ) )
  20. USING_NS_BF;
  21. //#include "BeefySysLib/third_party/sparsehash/google/sparsehash/densehashtable.h"
  22. //////////////////////////////////////////////////////////////////////////
  23. BlChunk* BlSegment::AddChunk(void* data, int size, int characteristics, int& offset)
  24. {
  25. if (size == 0)
  26. return NULL;
  27. if ((characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0)
  28. {
  29. BF_ASSERT(data == NULL);
  30. }
  31. else
  32. {
  33. BF_ASSERT(data != NULL);
  34. }
  35. int align = 1;
  36. int chAlign = characteristics & IMAGE_SCN_ALIGN_MASK;
  37. if (chAlign == IMAGE_SCN_ALIGN_8192BYTES)
  38. align = 8192;
  39. else if (chAlign == IMAGE_SCN_ALIGN_4096BYTES)
  40. align = 4096;
  41. else if (chAlign == IMAGE_SCN_ALIGN_2048BYTES)
  42. align = 2048;
  43. else if (chAlign == IMAGE_SCN_ALIGN_1024BYTES)
  44. align = 1024;
  45. else if (chAlign == IMAGE_SCN_ALIGN_512BYTES)
  46. align = 512;
  47. else if (chAlign == IMAGE_SCN_ALIGN_256BYTES)
  48. align = 256;
  49. else if (chAlign == IMAGE_SCN_ALIGN_128BYTES)
  50. align = 128;
  51. else if (chAlign == IMAGE_SCN_ALIGN_64BYTES)
  52. align = 64;
  53. else if (chAlign == IMAGE_SCN_ALIGN_32BYTES)
  54. align = 32;
  55. else if (chAlign == IMAGE_SCN_ALIGN_16BYTES)
  56. align = 16;
  57. else if (chAlign == IMAGE_SCN_ALIGN_8BYTES)
  58. align = 8;
  59. else if (chAlign == IMAGE_SCN_ALIGN_4BYTES)
  60. align = 4;
  61. else if (chAlign == IMAGE_SCN_ALIGN_2BYTES)
  62. align = 2;
  63. int prevSize = mCurSize;
  64. mCurSize = (mCurSize + (align - 1)) & ~(align - 1);
  65. offset = mCurSize;
  66. mCurSize += size;
  67. mAlign = std::max(mAlign, align);
  68. if (data == NULL)
  69. return NULL;
  70. BlChunk blChunk;
  71. blChunk.mOffset = offset;
  72. blChunk.mAlignPad = offset - prevSize;
  73. blChunk.mSize = size;
  74. blChunk.mData = data;
  75. blChunk.mObjectDataIdx = -1;
  76. mChunks.push_back(blChunk);
  77. auto blChunkPtr = &mChunks.back();
  78. return blChunkPtr;
  79. }
  80. //////////////////////////////////////////////////////////////////////////
  81. void BlPeRelocs::Add(uint32 addr, int fixupType)
  82. {
  83. int ofs = addr - mBlockAddr;
  84. if ((mLenPtr == NULL) || (ofs >= 0x1000))
  85. {
  86. if ((mLenPtr != NULL) && (*mLenPtr % 4 == 2))
  87. {
  88. (*mLenPtr) += 2;
  89. int16 alignVal = 0;
  90. mData.Write(&alignVal, 2);
  91. }
  92. mBlockAddr = addr;
  93. mData.Write(&mBlockAddr, 4);
  94. mLenPtr = (int32*)mData.mWriteCurPtr;
  95. int32 len = 8 + 2;
  96. mData.Write(&len, 4);
  97. int16 val = fixupType << 12;
  98. mData.Write(&val, 2);
  99. }
  100. else
  101. {
  102. int16 val = (ofs) | (fixupType << 12);
  103. mData.Write(&val, 2);
  104. (*mLenPtr) += 2;
  105. }
  106. }
  107. //////////////////////////////////////////////////////////////////////////
  108. static void FixLibName(String& libName)
  109. {
  110. if ((libName.length() > 4) && (stricmp(libName.c_str() + libName.length() - 4, ".lib") != 0))
  111. libName += ".lib";
  112. }
  113. //////////////////////////////////////////////////////////////////////////
  114. BlContext::BlContext()
  115. {
  116. mNumObjFiles = 0;
  117. mNumLibs = 0;
  118. mNumImportedObjs = 0;
  119. mNumWeakSymbols = 0;
  120. #ifdef BL_PERFTIME
  121. gPerfManager = new PerfManager();
  122. gPerfManager->StartRecording();
  123. #endif
  124. //mOutName = "c:\\temp\\out.exe";
  125. //mOutName = "c:\\temp\\TestDLL2.dll";
  126. //mOutName = "c:\\temp\\TestDLL2ABCDEFGHIJKMNOPQRSTUVWXYZ.dll";
  127. mCodeView = NULL;
  128. mSymTable.mContext = this;
  129. mDebugKind = 0;
  130. mImageBase = 0x140000000LL;
  131. mVerbose = false;
  132. mNoDefaultLib = false;
  133. mHasFixedBase = false;
  134. mHasDynamicBase = true;
  135. mHighEntropyVA = true;
  136. mIsNXCompat = true;
  137. mIsTerminalServerAware = true;
  138. mPeVersionMajor = 0;
  139. mPeVersionMinor = 0;
  140. mFailed = false;
  141. mErrorCount = 0;
  142. mIsDLL = false;
  143. mPeSubsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
  144. mStackReserve = 0x100000;
  145. mStackCommit = 0x1000;
  146. mHeapReserve = 0x100000;
  147. mHeapCommit = 0x1000;
  148. mTimestamp = (int)time(0);
  149. mProcessingSegIdx = 0;
  150. mIDataSeg = NULL;
  151. mBSSSeg = NULL;
  152. mNumFixedSegs = 0;
  153. mDbgSymSectsFound = 0;
  154. mDbgSymSectsUsed = 0;
  155. mTextSeg = NULL;
  156. mRDataSeg = NULL;
  157. mDataSeg = NULL;
  158. mSegments.reserve(MAX_SEG_COUNT);
  159. }
  160. BlContext::~BlContext()
  161. {
  162. if (mCodeView != NULL)
  163. {
  164. mCodeView->StopWorkThreads();
  165. delete mCodeView;
  166. }
  167. #ifdef BL_PERFTIME
  168. if (gPerfManager->IsRecording())
  169. {
  170. gPerfManager->StopRecording(true);
  171. }
  172. #endif
  173. }
  174. BlSymHash BlContext::Hash(const char* symName)
  175. {
  176. BlSymHash symHash;
  177. Hash128(symName, (int)strlen(symName));
  178. symHash.mName = symName;
  179. return symHash;
  180. }
  181. String BlContext::ObjectDataIdxToString(int objectDataIdx)
  182. {
  183. if (objectDataIdx == -1)
  184. return "<unknown>";
  185. auto objectData = mObjectDatas[objectDataIdx];
  186. String name;
  187. if (objectData->mLib != NULL)
  188. {
  189. name = "\"";
  190. name += GetFileName(objectData->mLib->mFileName);
  191. name += "\" (";
  192. name += GetFileName(objectData->mName);
  193. name += ")";
  194. }
  195. else
  196. {
  197. name = "\"";
  198. name += GetFileName(objectData->mName);
  199. name += "\"";
  200. }
  201. return name;
  202. }
  203. String BlContext::GetSymDisp(const StringImpl&name)
  204. {
  205. String str;
  206. if ((name.empty()) || (name[0] != '?'))
  207. {
  208. str += "\"";
  209. str += name;
  210. str += "\"";
  211. return str;
  212. }
  213. str += "\"";
  214. str += BfDemangler::Demangle(name, DbgLanguage_Unknown);
  215. str += "\" (";
  216. str += name;
  217. str += ")";
  218. return str;
  219. }
  220. String BlContext::FixFilePath(const StringImpl& path, const StringImpl& actualFileName)
  221. {
  222. String actualPath;
  223. int lastSlash = BF_MAX((int)path.LastIndexOf('\\'), (int)path.LastIndexOf('/'));
  224. if (lastSlash != -1)
  225. actualPath.Append(path.c_str(), lastSlash);
  226. for (int i = 0; i < (int)actualPath.length(); i++)
  227. if (actualPath[i] == '/')
  228. actualPath[i] = '\\';
  229. actualPath += actualFileName;
  230. return actualPath;
  231. }
  232. void BlContext::Fail(const StringImpl& error)
  233. {
  234. AutoCrit autoCrit(mCritSect);
  235. mErrorCount++;
  236. if (mErrorCount > 100)
  237. return;
  238. std::cerr << "ERROR: " << error.c_str() << std::endl;
  239. mFailed = true;
  240. }
  241. void BlContext::Warn(const StringImpl& error)
  242. {
  243. AutoCrit autoCrit(mCritSect);
  244. mErrorCount++;
  245. std::cerr << "WARNING: " << error.c_str() << std::endl;
  246. }
  247. void BlContext::Fail(BlObjectData* objectData, const StringImpl& error)
  248. {
  249. AutoCrit autoCrit(mCritSect);
  250. Fail(StrFormat("%s in %s", error.c_str(), ObjectDataIdxToString(objectData->mIdx).c_str()));
  251. }
  252. void BlContext::AssertFailed()
  253. {
  254. BF_ASSERT(mFailed);
  255. }
  256. void BlContext::NotImpl()
  257. {
  258. BF_FATAL("Not implemented");
  259. }
  260. void BlContext::AddSegment(BlSegment* seg)
  261. {
  262. seg->mContext = this;
  263. seg->mSegmentIdx = (int)mSegments.size();
  264. if (mSegments.size() >= MAX_SEG_COUNT)
  265. {
  266. Fail("Maximum segment count exceeded");
  267. return;
  268. }
  269. mSegments.push_back(seg);
  270. mOrderedSegments.push_back(seg);
  271. }
  272. void BlContext::LoadFiles()
  273. {
  274. BL_AUTOPERF("BlContext::LoadFiles");
  275. BfSizedVector<BlObjectDataSectInfo, 16> sectInfos;
  276. BfSizedVector<BlObjectDataSymInfo, 256> symInfos;
  277. String tempStr;
  278. BfSizedVector<int, 16> orderedRelocSects;
  279. while (true)
  280. {
  281. orderedRelocSects.clear();
  282. if (mObjectDataWorkQueue.empty())
  283. break;
  284. auto objectData = mObjectDataWorkQueue.back();
  285. mObjectDataWorkQueue.pop_back();
  286. uint8* data = (uint8*)objectData->mData;
  287. PEFileHeader* fileHeader = (PEFileHeader*)data;
  288. int nameLen = (int)strlen(objectData->mName);
  289. if (nameLen > 4)
  290. {
  291. const char* ext = objectData->mName + nameLen - 4;
  292. if (stricmp(ext, ".res") == 0)
  293. {
  294. LoadResourceData(objectData);
  295. continue;
  296. }
  297. else if (stricmp(ext, ".def") == 0)
  298. {
  299. LoadDefData(objectData);
  300. continue;
  301. }
  302. }
  303. bool dbgTestFile = false;//strcmp(objectData->mName, "Internal.obj") == 0;
  304. if (fileHeader->mMachine != PE_MACHINE_X64)
  305. {
  306. if ((fileHeader->mMachine == 0) && (fileHeader->mNumberOfSections <= 1))
  307. {
  308. // This is an object that contains no code - probably just weak externals
  309. }
  310. else
  311. {
  312. Fail(objectData, "Invalid object file format");
  313. continue;
  314. }
  315. }
  316. data += sizeof(PEFileHeader);
  317. PESectionHeader* sectionHeaderArr = (PESectionHeader*)data;
  318. data += fileHeader->mNumberOfSections * sizeof(PESectionHeader);
  319. BlCvParser cvParser(this);
  320. auto _CommitSection = [&](int objSectionNum, BlObjectDataSectInfo& sectInfo)
  321. {
  322. auto sectionHeader = &sectionHeaderArr[objSectionNum];
  323. if (sectInfo.mSegmentIdx == -1)
  324. {
  325. if (sectInfo.mState == BlSectInfoState_QueuedDebugT)
  326. {
  327. cvParser.AddTypeData(sectionHeader);
  328. sectInfo.mState = (BlSectInfoState)0;
  329. }
  330. else if (sectInfo.mState == BlSectInfoState_QueuedDebugS)
  331. {
  332. mDbgSymSectsUsed++;
  333. cvParser.AddSymbolData(sectionHeader);
  334. sectInfo.mState = (BlSectInfoState)0;
  335. }
  336. else
  337. BF_FATAL("Error");
  338. return;
  339. }
  340. auto section = mSegments[sectInfo.mSegmentIdx];
  341. uint8* sectData = NULL;
  342. if (sectionHeader->mPointerToRawData != NULL)
  343. sectData = (uint8*)objectData->mData + sectionHeader->mPointerToRawData;
  344. BlChunk* blChunk = section->AddChunk(sectData, sectionHeader->mSizeOfRawData, sectionHeader->mCharacteristics, sectInfo.mSegmentOffset);
  345. if (blChunk != NULL)
  346. {
  347. sectInfo.mChunkData = blChunk->mData;
  348. blChunk->mObjectDataIdx = objectData->mIdx;
  349. }
  350. orderedRelocSects.push_back(objSectionNum);
  351. if ((sectionHeader->mCharacteristics & IMAGE_SCN_MEM_EXECUTE) != 0)
  352. {
  353. if (mCodeView != NULL)
  354. cvParser.AddContribution(sectInfo.mSegmentIdx, sectInfo.mSegmentOffset, sectionHeader->mSizeOfRawData, sectionHeader->mCharacteristics);
  355. }
  356. };
  357. BlSegmentInfo sectionInfo;
  358. char* strTab = (char*)objectData->mData + fileHeader->mPointerToSymbolTable + fileHeader->mNumberOfSymbols * sizeof(PE_SymInfo);
  359. if (mCodeView != NULL)
  360. cvParser.AddModule(objectData, strTab);
  361. sectInfos.clear();
  362. for (int sectIdx = 0; sectIdx < fileHeader->mNumberOfSections; sectIdx++)
  363. {
  364. BlSegment* section = NULL;
  365. BlObjectDataSectInfo sectInfo = { -1 };
  366. auto sectionHeader = &sectionHeaderArr[sectIdx];
  367. bool isComdat = (sectionHeader->mCharacteristics & IMAGE_SCN_LNK_COMDAT) != 0;
  368. if (sectionHeader->mPointerToRawData != 0)
  369. data = (uint8*)objectData->mData + sectionHeader->mPointerToRawData;
  370. char* sectionName = sectionHeader->mName;
  371. if (sectionName[0] == '/')
  372. {
  373. int idx = atoi(sectionName + 1);
  374. sectionName = &strTab[idx];
  375. }
  376. if (strncmp(sectionName, ".xdata", 6) == 0)
  377. {
  378. }
  379. if (strncmp(sectionName, ".drectve", 5) == 0)
  380. {
  381. char* cmdStart = NULL;
  382. auto _HandleParam = [&] (const StringImpl& cmd, const StringImpl& arg)
  383. {
  384. if (cmd == "/DEFAULTLIB")
  385. {
  386. String libName = arg;
  387. int lastDot = (int)libName.LastIndexOf('.');
  388. if (lastDot == -1)
  389. libName += ".lib";
  390. AddFile(libName, BlObjectDataKind_DirectiveLib);
  391. }
  392. else if (cmd == "/DISALLOWLIB")
  393. {
  394. String libName = arg;
  395. FixLibName(libName);
  396. String libCanonName = FixPathAndCase(libName);
  397. // Make sure we haven't already used this library, if so then throw an error, otherwise
  398. // just add it to the seen-list so we don't add it later
  399. auto itr = mSeenLibs.find(libCanonName);
  400. if (itr != mSeenLibs.end())
  401. {
  402. Fail(StrFormat("Disallowed lib '%s', disallowed in %s, has been used", arg.c_str(), ObjectDataIdxToString(objectData->mIdx).c_str()));
  403. }
  404. auto insertPair = mNoDefaultLibs.insert(libCanonName);
  405. }
  406. else if (cmd == "/MERGE")
  407. {
  408. int equalIdx = (int)arg.IndexOf('=');
  409. if (equalIdx == -1)
  410. return;
  411. String fromName = arg.Substring(0, equalIdx);
  412. String toName = arg.Substring(equalIdx + 1);
  413. mSectionMerges[fromName] = toName;
  414. }
  415. else if (cmd == "/ALTERNATENAME")
  416. {
  417. int equalIdx = (int)arg.IndexOf('=');
  418. if (equalIdx == -1)
  419. return;
  420. String fromName = arg.Substring(0, equalIdx);
  421. String toName = arg.Substring(equalIdx + 1);
  422. mSectionMerges[fromName] = toName;
  423. auto blSymbol = mSymTable.Add(fromName.c_str());
  424. if (blSymbol->mKind == BlSymKind_Undefined)
  425. {
  426. int remapIdx = (int)mRemapStrs.size();
  427. mRemapStrs.push_back(toName);
  428. blSymbol->mKind = BlSymKind_WeakSymbol;
  429. blSymbol->mParam = remapIdx;
  430. blSymbol->mObjectDataIdx = objectData->mIdx;
  431. }
  432. }
  433. else if (cmd == "/EXPORT")
  434. {
  435. const StringImpl& exportName = arg;
  436. auto pair = mExports.insert(std::make_pair(exportName, BlExport()));
  437. if (!pair.second)
  438. {
  439. Warn(StrFormat("Export '%s' specified multiple times; using first specification", exportName.c_str()));
  440. }
  441. }
  442. else if (cmd == "/FAILIFMISMATCH")
  443. {
  444. }
  445. else if (cmd == "/EDITANDCONTINUE")
  446. {
  447. }
  448. else if (cmd == "/THROWINGNEW")
  449. {
  450. }
  451. else if (cmd == "/GUARDSYM")
  452. {
  453. }
  454. else if (cmd == "/INCLUDE")
  455. {
  456. mForcedSyms.push_back(arg);
  457. }
  458. else
  459. {
  460. Fail(StrFormat("Invalid link option \"%s\" in %s", cmd.c_str(), ObjectDataIdxToString(objectData->mIdx).c_str()));
  461. }
  462. };
  463. /*#ifdef _DEBUG
  464. String dbgOut = "Directives for ";
  465. dbgOut += ObjectDataIdxToString(objectData->mIdx);
  466. dbgOut += ": ";
  467. dbgOut.insert(dbgOut.end(), (char*)data, (char*)data + sectionHeader->mSizeOfRawData);
  468. dbgOut += "\n";
  469. OutputDebugStrF(dbgOut.c_str());
  470. #endif*/
  471. StringT<256> curCmd;
  472. StringT<256> curArg;
  473. bool inArg = false;
  474. bool inQuote = false;
  475. bool prevSlash = false;
  476. for (char* cPtr = (char*)data; cPtr < (char*)data + sectionHeader->mSizeOfRawData; cPtr++)
  477. {
  478. char c = *cPtr;
  479. if (c == 0)
  480. break;
  481. if (c == '"')
  482. {
  483. inQuote = !inQuote;
  484. }
  485. else if ((c == ' ') && (!inQuote))
  486. {
  487. if (!curCmd.empty())
  488. {
  489. _HandleParam(curCmd, curArg);
  490. curCmd.clear();
  491. curArg.clear();
  492. inArg = false;
  493. }
  494. }
  495. else if ((c == ':') && (!inQuote))
  496. {
  497. inArg = true;
  498. }
  499. else if (inArg)
  500. curArg += c;
  501. else
  502. curCmd += toupper(c);
  503. }
  504. if (!curCmd.empty())
  505. _HandleParam(curCmd, curArg);
  506. }
  507. else if (strcmp(sectionName, ".debug$T") == 0)
  508. {
  509. if (mCodeView != NULL)
  510. {
  511. sectInfo.mState = BlSectInfoState_QueuedDebugT;
  512. if (!isComdat)
  513. _CommitSection(sectIdx, sectInfo);
  514. }
  515. }
  516. else if (strcmp(sectionName, ".debug$S") == 0)
  517. {
  518. mDbgSymSectsFound++;
  519. if (mCodeView != NULL)
  520. {
  521. sectInfo.mState = BlSectInfoState_QueuedDebugS;
  522. if (!isComdat)
  523. _CommitSection(sectIdx, sectInfo);
  524. }
  525. }
  526. else
  527. {
  528. if (strcmp(sectionName, ".bss") == 0)
  529. {
  530. sectionName = (char*)mBSSSeg->mName.c_str();
  531. }
  532. auto _CompareSectionInfo = [] (BlSegmentInfo* lhs, BlSegmentInfo* rhs)
  533. {
  534. return lhs->mName < rhs->mName;
  535. };
  536. sectionInfo.mName = sectionName;
  537. auto itr = std::lower_bound(mOrderedSegments.begin(), mOrderedSegments.end(), &sectionInfo, _CompareSectionInfo);
  538. if (itr != mOrderedSegments.end())
  539. {
  540. section = *itr;
  541. if (section->mName != sectionName)
  542. section = NULL;
  543. }
  544. if (section == NULL)
  545. {
  546. section = mDynSegments.Alloc();
  547. section->mName = sectionName;
  548. section->mContext = this;
  549. section->mSegmentIdx = (int)mSegments.size();
  550. mSegments.push_back(section);
  551. mOrderedSegments.push_back(section);
  552. std::sort(mOrderedSegments.begin(), mOrderedSegments.end(), _CompareSectionInfo);
  553. }
  554. }
  555. /*else if (strncmp(sectionHeader->mName, ".text", 5) == 0)
  556. {
  557. section = &mTextSect;
  558. }
  559. else if (strncmp(sectionHeader->mName, ".rdata", 6) == 0)
  560. {
  561. section = &mRDataSect;
  562. }
  563. else if (strncmp(sectionHeader->mName, ".bss", 4) == 0)
  564. {
  565. section = &mBSSSect;
  566. }*/
  567. if (section != NULL)
  568. {
  569. // Add the alignment flags later
  570. section->mCharacteristics |= (sectionHeader->mCharacteristics & ~IMAGE_SCN_ALIGN_MASK);
  571. sectInfo.mSegmentIdx = section->mSegmentIdx;
  572. if (isComdat)
  573. {
  574. sectInfo.mState = BlSectInfoState_QueuedData;
  575. }
  576. else
  577. {
  578. /*uint8* sectData = NULL;
  579. if (sectionHeader->mPointerToRawData != NULL)
  580. sectData = (uint8*)objectData->mData + sectionHeader->mPointerToRawData;
  581. BlChunk* blChunk = section->AddChunk(sectData, sectionHeader->mSizeOfRawData, sectionHeader->mCharacteristics, sectInfo.mSectionOffset);
  582. if (blChunk != NULL)
  583. sectInfo.mChunkData = blChunk->mData;
  584. orderedRelocSects.push_back(sectIdx);*/
  585. _CommitSection(sectIdx, sectInfo);
  586. }
  587. }
  588. data += sectionHeader->mSizeOfRawData;
  589. if (sectionHeader->mPointerToRawData != 0)
  590. sectInfo.mRelocData = (uint8*)objectData->mData + sectionHeader->mPointerToRelocations;
  591. sectInfos.push_back(sectInfo);
  592. }
  593. data = (uint8*)objectData->mData + fileHeader->mPointerToSymbolTable;
  594. PE_SymInfo* symInfoArr = (PE_SymInfo*)data;
  595. //////// Read symbols
  596. // This is the primary symbol creation loop
  597. {
  598. BL_AUTOPERF("BlContext::LoadFiles ReadSymbols");
  599. symInfos.clear();
  600. symInfos.resize(fileHeader->mNumberOfSymbols);
  601. for (int symIdx = 0; symIdx < (int)fileHeader->mNumberOfSymbols; symIdx++)
  602. {
  603. auto& symInfo = symInfos[symIdx];
  604. PE_SymInfo* objSym = (PE_SymInfo*)data;
  605. data += sizeof(PE_SymInfo);
  606. if ((objSym->mNumOfAuxSymbols != 0) && (objSym->mStorageClass == IMAGE_SYM_CLASS_STATIC))
  607. {
  608. BF_ASSERT(objSym->mSectionNum >= 1);
  609. auto& sectInfo = sectInfos[objSym->mSectionNum - 1];
  610. PE_SymInfoAux* symAuxInfo = (PE_SymInfoAux*)data;
  611. sectInfo.mSelectNum = symAuxInfo->mNumber;
  612. sectInfo.mSelection = symAuxInfo->mSelection;
  613. symInfo.mKind = BlObjectDataSymInfo::Kind_Section;
  614. symInfo.mSectionNum = objSym->mSectionNum;
  615. symIdx += objSym->mNumOfAuxSymbols;
  616. data += sizeof(PE_SymInfo) * objSym->mNumOfAuxSymbols;
  617. continue;
  618. }
  619. if (objSym->mSectionNum == 0xFFFF)
  620. {
  621. symInfo.mSegmentIdx = -1;
  622. symInfo.mSegmentOffset = objSym->mValue;
  623. // Do anything with this? @comp.id, @feat.00
  624. // Rich Signature stuff.
  625. }
  626. else if (objSym->mSectionNum != 0)
  627. {
  628. auto& sectInfo = sectInfos[objSym->mSectionNum - 1];
  629. symInfo.mSegmentIdx = sectInfo.mSegmentIdx;
  630. int sectOffset = sectInfo.mSegmentOffset;
  631. symInfo.mSegmentOffset = sectInfo.mSegmentOffset + objSym->mValue;
  632. }
  633. if (objSym->mStorageClass == IMAGE_SYM_CLASS_LABEL)
  634. {
  635. auto& sectInfo = sectInfos[objSym->mSectionNum - 1];
  636. if (sectInfo.mChunkData == (void*)-1)
  637. {
  638. // Don't let labels cause COMDAT commits
  639. continue;
  640. }
  641. }
  642. if ((objSym->mStorageClass != IMAGE_SYM_CLASS_EXTERNAL) &&
  643. (objSym->mStorageClass != IMAGE_SYM_CLASS_EXTERNAL_DEF) &&
  644. (objSym->mStorageClass != IMAGE_SYM_CLASS_WEAK_EXTERNAL))
  645. {
  646. if (objSym->mSectionNum != 0xFFFF)
  647. {
  648. auto& sectInfo = sectInfos[objSym->mSectionNum - 1];
  649. if (sectInfo.mChunkData == (void*)-1)
  650. {
  651. _CommitSection(objSym->mSectionNum - 1, sectInfo);
  652. symInfo.mSegmentOffset += sectInfo.mSegmentOffset;
  653. }
  654. }
  655. BF_ASSERT(objSym->mSectionNum != 0);
  656. continue;
  657. }
  658. char* symName;
  659. if (objSym->mName[0] == 0)
  660. {
  661. symName = strTab + objSym->mNameOfs[1];
  662. }
  663. else
  664. {
  665. symName = objSym->mName;
  666. if (symName[7] != 0) // Do we have to zero-terminate ourselves?
  667. {
  668. symName = (char*)mAlloc.AllocBytes(9);
  669. memcpy(symName, objSym->mName, 8);
  670. }
  671. }
  672. if ((objSym->mSectionNum == 0) && (objSym->mStorageClass != IMAGE_SYM_CLASS_WEAK_EXTERNAL))
  673. {
  674. if (objSym->mValue > 0)
  675. {
  676. // Zero-initialized value, where mValue is the size. I've only seen this occur in C
  677. // files with zero-initialized local static variables
  678. auto blSymbol = mSymTable.Add(symName);
  679. if (blSymbol->mObjectDataIdx != -1)
  680. continue;
  681. int align = std::min(objSym->mValue, 16);
  682. mBSSSeg->mAlign = std::max(mBSSSeg->mAlign, align);
  683. mBSSSeg->mCurSize = BF_ALIGN(mBSSSeg->mCurSize, align);
  684. symInfo.mSegmentIdx = mBSSSeg->mSegmentIdx;
  685. symInfo.mSegmentOffset = mBSSSeg->mCurSize;
  686. mBSSSeg->mCurSize += objSym->mValue;
  687. blSymbol->mObjectDataIdx = objectData->mIdx;
  688. blSymbol->mSegmentIdx = symInfo.mSegmentIdx;
  689. blSymbol->mSegmentOffset = symInfo.mSegmentOffset;
  690. continue;
  691. }
  692. else
  693. {
  694. // External reference
  695. symInfo.mSym = mSymTable.Add(symName);
  696. if (symInfo.mSym->mKind >= 0)
  697. {
  698. symInfo.mSegmentIdx = symInfo.mSym->mSegmentIdx;
  699. symInfo.mSegmentOffset = symInfo.mSym->mSegmentOffset;
  700. }
  701. else
  702. {
  703. symInfo.mSegmentIdx = -1;
  704. }
  705. continue;
  706. }
  707. }
  708. // Export
  709. auto blSymbol = mSymTable.Add(symName);
  710. if (blSymbol->mObjectDataIdx != -1)
  711. {
  712. bool usePrevSymbol = false;
  713. if (objSym->mStorageClass == IMAGE_SYM_CLASS_WEAK_EXTERNAL)
  714. {
  715. symIdx += objSym->mNumOfAuxSymbols;
  716. data += sizeof(PE_SymInfo) * objSym->mNumOfAuxSymbols;
  717. usePrevSymbol = true; // Everything is higher priority than a weak external
  718. }
  719. else
  720. {
  721. BlObjectData* prevObjectData = mObjectDatas[blSymbol->mObjectDataIdx];
  722. if (blSymbol->mKind == BlSymKind_WeakSymbol)
  723. usePrevSymbol = false; // Always prefer a non-weak symbol
  724. else if (prevObjectData->mKind > objectData->mKind)
  725. usePrevSymbol = true; // Previous has higher priority, leave it
  726. else if ((mBSSSeg != NULL) && (blSymbol->mSegmentIdx == mBSSSeg->mSegmentIdx))
  727. {
  728. // This came from an implicit "sized UNDEF" symbol, so allow it to be overriden with
  729. // actual data
  730. usePrevSymbol = false;
  731. }
  732. else if (prevObjectData->mKind == objectData->mKind)
  733. {
  734. auto& sectInfo = sectInfos[objSym->mSectionNum - 1];
  735. if (sectInfo.mSelection == IMAGE_COMDAT_SELECT_ANY)
  736. {
  737. usePrevSymbol = true;
  738. }
  739. else if (sectInfo.mSelection == IMAGE_COMDAT_SELECT_LARGEST)
  740. {
  741. //TODO: Find actual chunk
  742. usePrevSymbol = true;
  743. }
  744. else if (sectInfo.mSelection > 2)
  745. {
  746. Fail(StrFormat("Unsupported COMDAT selection '%d' found on symbol '%s' in %s", sectInfo.mSelection, GetSymDisp(symName).c_str(), ObjectDataIdxToString(objectData->mIdx).c_str()));
  747. }
  748. else
  749. {
  750. // Ambiguous priority, throw error
  751. Fail(StrFormat("Duplicate symbol %s found in %s, first defined in %s", GetSymDisp(symName).c_str(), ObjectDataIdxToString(objectData->mIdx).c_str(),
  752. ObjectDataIdxToString(blSymbol->mObjectDataIdx).c_str()));
  753. }
  754. }
  755. }
  756. if (usePrevSymbol)
  757. {
  758. if (blSymbol->mSegmentIdx >= 0)
  759. {
  760. symInfo.mSegmentIdx = blSymbol->mSegmentIdx;
  761. symInfo.mSegmentOffset = blSymbol->mSegmentOffset;
  762. }
  763. else
  764. {
  765. symInfo.mSym = blSymbol;
  766. }
  767. continue;
  768. }
  769. }
  770. if (objSym->mStorageClass == IMAGE_SYM_CLASS_WEAK_EXTERNAL)
  771. {
  772. struct _WeakExtern
  773. {
  774. int32 mTagIndex;
  775. int32 mCharacteristics;
  776. };
  777. _WeakExtern* weakExtern = (_WeakExtern*)data;
  778. PE_SymInfo* refSymInfo = &symInfoArr[weakExtern->mTagIndex];
  779. char* refSymName;
  780. if (refSymInfo->mName[0] == 0)
  781. {
  782. refSymName = strTab + refSymInfo->mNameOfs[1];
  783. }
  784. else
  785. {
  786. refSymName = refSymInfo->mName;
  787. if (refSymName[7] != 0) // Do we have to zero-terminate ourselves?
  788. {
  789. refSymName = (char*)mAlloc.AllocBytes(9);
  790. memcpy(refSymName, refSymInfo->mName, 8);
  791. }
  792. }
  793. symInfo.mSym = blSymbol;
  794. int remapIdx = (int)mRemapStrs.size();
  795. mRemapStrs.push_back(refSymName);
  796. mNumWeakSymbols++;
  797. mForcedSyms.push_back(refSymName);
  798. blSymbol->mKind = BlSymKind_WeakSymbol;
  799. blSymbol->mParam = remapIdx;
  800. blSymbol->mObjectDataIdx = objectData->mIdx;
  801. symIdx += objSym->mNumOfAuxSymbols;
  802. data += sizeof(PE_SymInfo) * objSym->mNumOfAuxSymbols;
  803. continue;
  804. }
  805. auto& sectInfo = sectInfos[objSym->mSectionNum - 1];
  806. if (sectInfo.mChunkData == (void*)-1)
  807. {
  808. _CommitSection(objSym->mSectionNum - 1, sectInfo);
  809. symInfo.mSegmentOffset += sectInfo.mSegmentOffset;
  810. }
  811. blSymbol->mObjectDataIdx = objectData->mIdx;
  812. blSymbol->mSegmentIdx = symInfo.mSegmentIdx;
  813. blSymbol->mSegmentOffset = symInfo.mSegmentOffset;
  814. }
  815. }
  816. // Any loaded COMDAT section with section associativities need to load those associated sections now
  817. // This most often occurs with a debug$S entry for a COMDAT function, such as a template method.
  818. // We only want to include the static debug info if the function is chosen.
  819. while (true)
  820. {
  821. // We may need to iterate multiple times, if there are chained dependencies and a new commited
  822. // depdency occurs after a pending dependent entry
  823. bool commitedNew = false;
  824. for (int sectIdx = 0; sectIdx < fileHeader->mNumberOfSections; sectIdx++)
  825. {
  826. auto sectionHeader = &sectionHeaderArr[sectIdx];
  827. bool isComdat = (sectionHeader->mCharacteristics & IMAGE_SCN_LNK_COMDAT) != 0;
  828. if (!isComdat)
  829. continue;
  830. auto& sectInfo = sectInfos[sectIdx];
  831. if (sectInfo.IsUsed())
  832. continue;
  833. if (sectInfo.mSelection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
  834. {
  835. auto checkSelectInfo = sectInfos[sectInfo.mSelectNum - 1];
  836. if (checkSelectInfo.IsUsed())
  837. {
  838. _CommitSection(sectIdx, sectInfo);
  839. commitedNew = true;
  840. }
  841. }
  842. }
  843. if (!commitedNew)
  844. break;
  845. }
  846. // Queue relocs
  847. {
  848. BL_AUTOPERF("BlContext::LoadFiles Relocs");
  849. for (int ordIdx = 0; ordIdx < (int)orderedRelocSects.size(); ordIdx++)
  850. {
  851. int sectIdx = orderedRelocSects[ordIdx];
  852. auto sectionHeader = &sectionHeaderArr[sectIdx];
  853. auto& sectInfo = sectInfos[sectIdx];
  854. if (sectInfo.mSegmentIdx == -1)
  855. continue;
  856. if (sectInfo.mChunkData == (void*)-1)
  857. {
  858. // Unused COMDAT, or is data
  859. continue;
  860. }
  861. auto seg = mSegments[sectInfo.mSegmentIdx];
  862. data = (uint8*)sectInfo.mRelocData;
  863. bool isDebugSymSect = seg->mName == ".debug$S";
  864. bool hadDeferredSyms = false;
  865. int lastRelocOffset = 0;
  866. if (!seg->mRelocs.empty())
  867. lastRelocOffset = seg->mRelocs.back().mOutOffset;
  868. for (int relocIdx = 0; relocIdx < sectionHeader->mNumberOfRelocations; relocIdx++)
  869. {
  870. COFFRelocation* reloc = (COFFRelocation*)data;
  871. data += sizeof(COFFRelocation);
  872. auto& sym = symInfos[reloc->mSymbolTableIndex];
  873. int outOffset = sectInfo.mSegmentOffset + (int)reloc->mVirtualAddress;
  874. if (sym.mSegmentIdx == -1)
  875. {
  876. //NotImpl();
  877. /*auto symInfo = &symInfoArr[reloc->mSymbolTableIndex];
  878. auto targetSectInfo = sectInfos[symInfo->mSectionNum - 1];
  879. sym.mSectionIdx = targetSectInfo.mSectionIdx;
  880. if (targetSectInfo.mChunkData == (void*)-1)
  881. {
  882. _CommitComdat(symInfo->mSectionNum - 1, targetSectInfo);
  883. sym.mSectionOffset += targetSectInfo.mSectionOffset;
  884. }*/
  885. }
  886. if (outOffset < lastRelocOffset)
  887. {
  888. NotImpl();
  889. }
  890. BlReloc blReloc;
  891. blReloc.mOutOffset = outOffset;
  892. if (sym.mSym != NULL)
  893. {
  894. /*if ((isDebugSymSect) && (sym.mSym->mSegmentIdx >= 0) && (sym.mSym->mSegmentIdx < mNumFixedSegs))
  895. {
  896. blReloc.mSegmentIdx = sym.mSym->mSegmentIdx;
  897. blReloc.mSegmentOffset = sym.mSym->mSegmentOffset;
  898. blReloc.mFlags = BeRelocFlags_Loc;
  899. }
  900. else*/
  901. {
  902. hadDeferredSyms = true;
  903. blReloc.mSym = sym.mSym;
  904. blReloc.mFlags = (BeRelocFlags)(BeRelocFlags_Sym | BeRelocFlags_SymIsNew);
  905. }
  906. }
  907. else
  908. {
  909. BF_ASSERT(sym.mSegmentIdx != -1);
  910. if (sym.mKind == BlObjectDataSymInfo::Kind_Section)
  911. {
  912. auto& sectInfo = sectInfos[sym.mSectionNum - 1];
  913. blReloc.mSegmentIdx = sectInfo.mSegmentIdx;
  914. blReloc.mSegmentOffset = sectInfo.mSegmentOffset;
  915. }
  916. else
  917. {
  918. blReloc.mSegmentIdx = sym.mSegmentIdx;
  919. blReloc.mSegmentOffset = sym.mSegmentOffset;
  920. }
  921. blReloc.mFlags = BeRelocFlags_Loc;
  922. }
  923. /*if (sym.mIsFunc)
  924. blReloc.mFlags = (BeRelocFlags)(blReloc.mFlags | BeRelocFlags_Func);*/
  925. switch (reloc->mType)
  926. {
  927. case IMAGE_REL_AMD64_ADDR32NB:
  928. blReloc.mKind = BlRelocKind_ADDR32NB;
  929. //blReloc.mParam = *(int32*)((uint8*)sectInfo.mChunkData + reloc->mVirtualAddress);
  930. break;
  931. case IMAGE_REL_AMD64_ADDR64:
  932. //TODO:
  933. blReloc.mKind = BlRelocKind_ADDR64;
  934. //blReloc.mParam = *(int64*)((uint8*)sectInfo.mChunkData + reloc->mVirtualAddress);
  935. break;
  936. case IMAGE_REL_AMD64_REL32:
  937. blReloc.mKind = BlRelocKind_REL32;
  938. //blReloc.mParam = *(int32*)((uint8*)sectInfo.mChunkData + reloc->mVirtualAddress);
  939. break;
  940. case IMAGE_REL_AMD64_REL32_1:
  941. blReloc.mKind = BlRelocKind_REL32_1;
  942. //blReloc.mParam = *(int32*)((uint8*)sectInfo.mChunkData + reloc->mVirtualAddress);
  943. break;
  944. case IMAGE_REL_AMD64_REL32_4:
  945. blReloc.mKind = BlRelocKind_REL32_4;
  946. //blReloc.mParam = *(int32*)((uint8*)sectInfo.mChunkData + reloc->mVirtualAddress);
  947. break;
  948. case IMAGE_REL_AMD64_SECREL:
  949. blReloc.mKind = BlRelocKind_SECREL;
  950. //blReloc.mParam = *(int32*)((uint8*)sectInfo.mChunkData + reloc->mVirtualAddress);
  951. break;
  952. case IMAGE_REL_AMD64_SECTION:
  953. NotImpl();
  954. break;
  955. default:
  956. NotImpl();
  957. break;
  958. }
  959. lastRelocOffset = outOffset;
  960. seg->mRelocs.push_back(blReloc);
  961. }
  962. }
  963. }
  964. if (mCodeView != NULL)
  965. {
  966. BL_AUTOPERF("BlContext::LoadFiles Cv FinishModule");
  967. cvParser.FinishModule(sectionHeaderArr, sectInfos, symInfoArr, symInfos);
  968. }
  969. //TODO: Make so we can unmap memory-mapped data. Currently we can't do that because of string pointers in symbols
  970. }
  971. }
  972. bool BlContext::HandleLibSymbolRef(BlSymbol* sym, int objectDataIds)
  973. {
  974. const char* name = sym->mName;
  975. BlObjectData* objectData = mObjectDatas[objectDataIds];
  976. if ((objectData->mLoadState == BlObjectDataLoadState_UnloadedLib) || (objectData->mLoadState == BlObjectDataLoadState_UnloadedThinLib))
  977. {
  978. mNumImportedObjs++;
  979. bool isThinLib = objectData->mLoadState == BlObjectDataLoadState_UnloadedThinLib;
  980. BlLibMemberHeader* header = (BlLibMemberHeader*)objectData->mData;
  981. if ((header->mName[0] == '/') || (header->mName[0] == '\\'))
  982. {
  983. objectData->mName = objectData->mLib->mStrTable + atoi(header->mName + 1);
  984. for (char* cPtr = objectData->mName; true; cPtr++)
  985. {
  986. // Thin string table entries end with "/\n" for some reason.
  987. char c = *cPtr;
  988. if (c == 0)
  989. break;
  990. if (c == '\n')
  991. {
  992. char* endC = cPtr;
  993. if (cPtr[-1] == '/')
  994. endC = cPtr - 1;
  995. char* newStr = (char*)mAlloc.AllocBytes((int)(endC - objectData->mName + 1));
  996. memcpy(newStr, objectData->mName, (int)(endC - objectData->mName));
  997. newStr[endC - objectData->mName] = 0;
  998. objectData->mName = newStr;
  999. break;
  1000. }
  1001. }
  1002. }
  1003. else
  1004. {
  1005. char* slashPos = strchr(header->mName, '/');
  1006. BF_ASSERT(slashPos != NULL);
  1007. int len = (int)(slashPos - header->mName);
  1008. objectData->mName = (char*)mAlloc.AllocBytes(len + 1);
  1009. memcpy(objectData->mName, header->mName, len);
  1010. }
  1011. if (isThinLib)
  1012. {
  1013. auto mappedFile = mMappedFiles.Alloc();
  1014. String objPath = GetAbsPath(objectData->mName, GetFileDir(objectData->mLib->mFileName));
  1015. if (!mappedFile->Open(objPath))
  1016. {
  1017. Fail(StrFormat("Failed to open thin archive member \"%s\" from \"%s\"", objectData->mName, objectData->mLib->mFileName.c_str()));
  1018. }
  1019. else
  1020. {
  1021. objectData->mData = mappedFile->mData;
  1022. objectData->mSize = mappedFile->mFileSize;
  1023. BF_ASSERT(objectData->mData != NULL);
  1024. mObjectDataWorkQueue.push_back(objectData);
  1025. }
  1026. }
  1027. else
  1028. {
  1029. objectData->mSize = atoi(header->mSize);
  1030. objectData->mData = (uint8*)objectData->mData + sizeof(BlLibMemberHeader);
  1031. PEImportObjectHeader* importObjectHeader = (PEImportObjectHeader*)objectData->mData;
  1032. if ((importObjectHeader->mSig1 == 0) && (importObjectHeader->mSig2 == IMPORT_OBJECT_HDR_SIG2))
  1033. {
  1034. uint8* data = (uint8*)objectData->mData;
  1035. data += sizeof(PEImportObjectHeader);
  1036. char* symName = (char*)data;
  1037. char* dllName = symName + strlen(symName) + 1;
  1038. String dllFixedName = FixPathAndCase(dllName);
  1039. BlImportFile* blImportFile;
  1040. auto itr = mImportFiles.find(dllFixedName);
  1041. if (itr != mImportFiles.end())
  1042. {
  1043. blImportFile = &itr->second;
  1044. }
  1045. else
  1046. {
  1047. blImportFile = &(mImportFiles.insert(std::make_pair(dllFixedName, BlImportFile())).first->second);
  1048. }
  1049. //OutputDebugStrF("Imported: %s:%s\n", dllName, symName);
  1050. int objType = (importObjectHeader->mType) & 3;
  1051. int nameType = importObjectHeader->mType >> 2;
  1052. auto blLookup = blImportFile->mLookups.Alloc();
  1053. if (nameType != IMPORT_OBJECT_ORDINAL)
  1054. blLookup->mName = symName;
  1055. blLookup->mHint = importObjectHeader->mHint;
  1056. if (strncmp(name, "__imp_", 6) == 0)
  1057. sym->mKind = BlSymKind_ImportImp;
  1058. else
  1059. sym->mKind = BlSymKind_Import;
  1060. sym->mParam = (int)mImportLookups.size();
  1061. mImportLookups.push_back(blLookup);
  1062. objectData->mLoadState = BlObjectDataLoadState_ImportObject;
  1063. objectData->mImportSym = sym;
  1064. }
  1065. else
  1066. {
  1067. BF_ASSERT(objectData->mData != NULL);
  1068. mObjectDataWorkQueue.push_back(objectData);
  1069. }
  1070. }
  1071. return true;
  1072. }
  1073. else if (objectData->mLoadState == BlObjectDataLoadState_ImportObject)
  1074. {
  1075. // We have both a "_imp_<X>" and "<X>" import name, so link those together
  1076. BF_ASSERT((objectData->mImportSym->mKind == BlSymKind_Import) || (objectData->mImportSym->mKind == BlSymKind_ImportImp));
  1077. if (strncmp(name, "__imp_", 6) == 0)
  1078. sym->mKind = BlSymKind_ImportImp;
  1079. else
  1080. sym->mKind = BlSymKind_Import;
  1081. sym->mParam = objectData->mImportSym->mParam;
  1082. return true;
  1083. }
  1084. else
  1085. {
  1086. return false;
  1087. }
  1088. }
  1089. BlSymbol* BlContext::ProcessSymbol(BlSymbol* sym)
  1090. {
  1091. // Try to load symbol from a lib if we need to
  1092. bool madeProgress = false;
  1093. while (sym->mKind == BlSymKind_WeakSymbol)
  1094. {
  1095. sym = mSymTable.Add(mRemapStrs[sym->mParam].c_str());
  1096. madeProgress = true;
  1097. }
  1098. if (sym->mKind == BlSymKind_LibSymbolRef)
  1099. {
  1100. madeProgress |= HandleLibSymbolRef(sym, sym->mParam);
  1101. }
  1102. else if (sym->mKind == BlSymKind_LibSymbolGroupRef)
  1103. {
  1104. // This symbol is reported in multiple libraries
  1105. for (auto objectDataIdx : mImportGroups[sym->mParam]->mObjectDatas)
  1106. {
  1107. madeProgress |= HandleLibSymbolRef(sym, objectDataIdx);
  1108. if (madeProgress)
  1109. {
  1110. // We only want to load ONE new object file, otherwise we could end up with multiple definitions
  1111. break;
  1112. }
  1113. }
  1114. }
  1115. else
  1116. madeProgress = true;
  1117. if ((!madeProgress) && (mObjectDataWorkQueue.empty()))
  1118. {
  1119. // If the mObjectDataWorkQueue is empty, that means we already tried to load a lib's object file
  1120. // that was supposed to define this symbol, but it didn't. This shouldn't happen in a well-formed lib
  1121. // unless we have a bug.
  1122. BF_ASSERT("Library error?" == 0);
  1123. sym->mKind = BlSymKind_Undefined;
  1124. }
  1125. return sym;
  1126. }
  1127. BlSymbol* BlContext::ResolveSym(const char* name, bool throwError)
  1128. {
  1129. auto sym = mSymTable.Add(name);
  1130. if ((throwError) && (sym->mKind == BlSymKind_Undefined))
  1131. {
  1132. BlSymNotFound symNotFound;
  1133. symNotFound.mSym = sym;
  1134. symNotFound.mOutOffset = -1;
  1135. symNotFound.mSegmentIdx = -1;
  1136. mSymNotFounds.push_back(symNotFound);
  1137. return sym;
  1138. }
  1139. sym = ProcessSymbol(sym);
  1140. return sym;
  1141. }
  1142. uint64 BlContext::GetSymAddr(BlSymbol* sym)
  1143. {
  1144. if (sym->mSegmentIdx < 0)
  1145. {
  1146. if (sym->mKind == BlSymKind_Absolute)
  1147. return sym->mSegmentOffset;
  1148. return 0;
  1149. }
  1150. auto segment = mSegments[sym->mSegmentIdx];
  1151. return segment->mRVA + sym->mSegmentOffset;
  1152. }
  1153. void BlContext::AddAbsoluteSym(const char * name, int val)
  1154. {
  1155. auto sym = mSymTable.Add(name);
  1156. sym->mObjectDataIdx = -1;
  1157. sym->mKind = BlSymKind_Absolute;
  1158. sym->mParam = val;
  1159. }
  1160. void BlContext::PlaceSections()
  1161. {
  1162. std::multimap<String, BlSegment*> groupedSections;
  1163. mSectionMerges[".text"] = "!0.text";
  1164. mSectionMerges[".rdata"] = "!1.rdata";
  1165. mSectionMerges[".data"] = "!2.data";
  1166. mSectionMerges[".bss"] = "!3.bss";
  1167. mSectionMerges[".pdata"] = "!4.pdata";
  1168. mSectionMerges[".idata"] = "!5.idata";
  1169. mSectionMerges[".gfids"] = "!6.gfids";
  1170. mSectionMerges[".00cfg"] = "!7.00cfg";
  1171. mSectionMerges[".rsrc"] = "!9.rsrc";
  1172. mSectionMerges[".reloc"] = "!9.reloc";
  1173. mSectionMerges[".tls"] = "!A.tls";
  1174. mSectionMerges[".xdata"] = "!B.xdata";
  1175. for (auto sect : mOrderedSegments)
  1176. {
  1177. auto sectName = sect->mName;
  1178. int dollarPos = (int)sectName.IndexOf('$');
  1179. if (dollarPos != -1)
  1180. sectName.RemoveToEnd(dollarPos);
  1181. while (true)
  1182. {
  1183. auto mergeItr = mSectionMerges.find(sectName);
  1184. if (mergeItr == mSectionMerges.end())
  1185. break;
  1186. sectName = mergeItr->second;
  1187. }
  1188. groupedSections.insert(std::make_pair(sectName, sect));
  1189. }
  1190. BlOutSection* outSection = NULL;
  1191. int outSectionIdx = -1;
  1192. for (auto pair : groupedSections)
  1193. {
  1194. auto baseName = pair.first;
  1195. auto sect = pair.second;
  1196. if (baseName[0] == '!')
  1197. baseName.Remove(0, 2);
  1198. if ((outSection == NULL) || (outSection->mName != baseName))
  1199. {
  1200. outSection = mOutSections.Alloc();
  1201. outSection->mName = baseName;
  1202. outSectionIdx++;
  1203. outSection->mIdx = outSectionIdx;
  1204. }
  1205. BF_ASSERT((sect->mOutSectionIdx == -1) || (sect->mOutSectionIdx == outSectionIdx));
  1206. sect->mOutSectionIdx = outSectionIdx;
  1207. outSection->mSegments.push_back(sect);
  1208. outSection->mCharacteristics |= sect->mCharacteristics;
  1209. //outSection->mRawSize = (outSection->mRawSize + (sect->mAlign - 1)) & ~(sect->mAlign - 1);
  1210. outSection->mAlign = std::max(outSection->mAlign, sect->mAlign);
  1211. //outSection->mRawSize += sect->mCurSize;
  1212. }
  1213. int32 curRVA = 0x1000;
  1214. int rawDataPos = (int)sizeof(PEHeader);
  1215. rawDataPos += 0xB0; // DOS program
  1216. rawDataPos += (int)sizeof(PE_NTHeaders64);
  1217. rawDataPos += (int)mOutSections.size() * sizeof(PESectionHeader);
  1218. rawDataPos = (rawDataPos + (512 - 1)) & ~(512 - 1);
  1219. for (auto outSection : mOutSections)
  1220. {
  1221. bool isUninitialized = false;
  1222. outSection->mRawDataPos = rawDataPos;
  1223. outSection->mRVA = curRVA;
  1224. for (auto sect : outSection->mSegments)
  1225. {
  1226. if ((!isUninitialized) && ((sect->mCharacteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0))
  1227. {
  1228. // This is for when transition from .data to .bss
  1229. int endRVA = (curRVA + (512 - 1)) & ~(512 - 1);
  1230. outSection->mRawSize = endRVA - outSection->mRVA;
  1231. isUninitialized = true;
  1232. }
  1233. curRVA = (curRVA + (sect->mAlign - 1)) & ~(sect->mAlign - 1);
  1234. sect->mRVA = curRVA;
  1235. curRVA += sect->mCurSize;
  1236. }
  1237. // Virtual size is NOT size-aligned
  1238. outSection->mVirtualSize = curRVA - outSection->mRVA;
  1239. if (!isUninitialized)
  1240. {
  1241. curRVA = (curRVA + (512 - 1)) & ~(512 - 1);
  1242. outSection->mRawSize = curRVA - outSection->mRVA;
  1243. }
  1244. curRVA = (curRVA + (4096 - 1)) & ~(4096 - 1);
  1245. rawDataPos += outSection->mRawSize;
  1246. int characteristics = outSection->mCharacteristics;
  1247. if (outSection->mAlign == 8192) characteristics |= IMAGE_SCN_ALIGN_8192BYTES;
  1248. else if (outSection->mAlign == 4096) characteristics |= IMAGE_SCN_ALIGN_4096BYTES;
  1249. else if (outSection->mAlign == 2048) characteristics |= IMAGE_SCN_ALIGN_2048BYTES;
  1250. else if (outSection->mAlign == 1024) characteristics |= IMAGE_SCN_ALIGN_1024BYTES;
  1251. else if (outSection->mAlign == 512) characteristics |= IMAGE_SCN_ALIGN_512BYTES;
  1252. else if (outSection->mAlign == 256) characteristics |= IMAGE_SCN_ALIGN_256BYTES;
  1253. else if (outSection->mAlign == 128) characteristics |= IMAGE_SCN_ALIGN_128BYTES;
  1254. else if (outSection->mAlign == 64) characteristics |= IMAGE_SCN_ALIGN_64BYTES;
  1255. else if (outSection->mAlign == 32) characteristics |= IMAGE_SCN_ALIGN_32BYTES;
  1256. else if (outSection->mAlign == 16) characteristics |= IMAGE_SCN_ALIGN_16BYTES;
  1257. else if (outSection->mAlign == 8) characteristics |= IMAGE_SCN_ALIGN_8BYTES;
  1258. else if (outSection->mAlign == 4) characteristics |= IMAGE_SCN_ALIGN_4BYTES;
  1259. else if (outSection->mAlign == 2) characteristics |= IMAGE_SCN_ALIGN_2BYTES;
  1260. outSection->mCharacteristics = characteristics;
  1261. }
  1262. }
  1263. void BlContext::ResolveRelocs()
  1264. {
  1265. BL_AUTOPERF("BlContext::ResolveRelocs");
  1266. int startProcessingSegIdx = mProcessingSegIdx;
  1267. while (true)
  1268. {
  1269. auto seg = mSegments[mProcessingSegIdx];
  1270. //for (auto& reloc : seg->mRelocs)
  1271. while (seg->mResolvedRelocIdx < (int)seg->mRelocs.size())
  1272. {
  1273. auto& reloc = seg->mRelocs[seg->mResolvedRelocIdx];
  1274. if ((reloc.mFlags & BeRelocFlags_Sym) != 0)
  1275. {
  1276. }
  1277. if ((reloc.mFlags & (BeRelocFlags_SymIsNew | BeRelocFlags_Sym)) == (BeRelocFlags_SymIsNew | BeRelocFlags_Sym))
  1278. {
  1279. auto sym = reloc.mSym;
  1280. sym = ProcessSymbol(sym);
  1281. reloc.mSym = sym;
  1282. if (sym->mKind == BlSymKind_Undefined)
  1283. {
  1284. BlSymNotFound symNotFound;
  1285. symNotFound.mOutOffset = reloc.mOutOffset;
  1286. symNotFound.mSegmentIdx = seg->mSegmentIdx;
  1287. symNotFound.mSym = sym;
  1288. mSymNotFounds.push_back(symNotFound);
  1289. //reloc.mFlags = (BeRelocFlags)(reloc.mFlags & ~BeRelocFlags_SymIsN | BeRelocFlags_Sym);
  1290. //reloc.mSym = sym;
  1291. }
  1292. else
  1293. {
  1294. bool didLocSet = false;
  1295. if ((sym->mObjectDataIdx != -1) && (sym->mSegmentIdx >= 0))
  1296. {
  1297. BlObjectData* symObjectData = mObjectDatas[sym->mObjectDataIdx];
  1298. if (symObjectData->mKind == BlObjectDataKind_SpecifiedObj)
  1299. {
  1300. // If this sym comes from a specified object file then it can't be overwritten, we can resolve now
  1301. reloc.mFlags = (BeRelocFlags)(reloc.mFlags & ~BeRelocFlags_Sym | BeRelocFlags_Loc);
  1302. reloc.mSegmentIdx = sym->mSegmentIdx;
  1303. reloc.mSegmentOffset = sym->mSegmentOffset;
  1304. didLocSet = true;
  1305. }
  1306. }
  1307. /*if (!didLocSet)
  1308. {
  1309. reloc.mFlags = (BeRelocFlags)(reloc.mFlags & ~BeRelocFlags_SymName | BeRelocFlags_Sym);
  1310. reloc.mSym = sym;
  1311. }*/
  1312. }
  1313. }
  1314. if ((reloc.mFlags & BeRelocFlags_SymIsNew) != 0)
  1315. reloc.mFlags = (BeRelocFlags)(reloc.mFlags & ~BeRelocFlags_SymIsNew);
  1316. // Handle any work queue items and then retry this reloc on next pass through ResolveRelocs
  1317. if (!mObjectDataWorkQueue.empty())
  1318. return;
  1319. seg->mResolvedRelocIdx++;
  1320. }
  1321. mProcessingSegIdx = (mProcessingSegIdx + 1) % (int)mSegments.size();
  1322. if (mProcessingSegIdx == startProcessingSegIdx)
  1323. break;
  1324. }
  1325. }
  1326. static bool IsResIdNamed(const char16_t* id)
  1327. {
  1328. return ((uintptr)id >= 0x10000);
  1329. }
  1330. static const char16_t* ParseResStr(uint8*& data)
  1331. {
  1332. char16_t& firstC = GET(char16_t);
  1333. if (firstC == 0xFFFF)
  1334. {
  1335. int16 id = GET(int16);
  1336. return (const char16_t*)(intptr)id;
  1337. }
  1338. while (true)
  1339. {
  1340. char16_t& nextC = GET(char16_t);
  1341. if (nextC == 0)
  1342. break;
  1343. }
  1344. return &firstC;
  1345. }
  1346. void BlContext::LoadResourceData(BlObjectData* objectData)
  1347. {
  1348. uint8* data = (uint8*)objectData->mData;
  1349. uint8* dataEnd = data + objectData->mSize;
  1350. while (data < dataEnd)
  1351. {
  1352. uint32 dataSize = GET(uint32);
  1353. uint32 headerSize = GET(uint32);
  1354. const char16_t* resType = ParseResStr(data);
  1355. const char16_t* resName = ParseResStr(data);
  1356. PTR_ALIGN(data, (uint8*)objectData->mData, 4);
  1357. uint32 dataVersion = GET(uint32);
  1358. uint16 memoryFlags = GET(uint16);
  1359. uint16 languageId = GET(uint16);
  1360. uint32 version = GET(uint32);
  1361. uint32 characteristics = GET(uint32);
  1362. if (dataSize == 0)
  1363. {
  1364. PTR_ALIGN(data, (uint8*)objectData->mData, 4);
  1365. continue;
  1366. }
  1367. // Index by type
  1368. BlResDirectory* typeResDir;
  1369. auto pair = mRootResDirectory.mEntries.insert(std::make_pair(resType, (BlResEntry*)NULL));
  1370. if (pair.second)
  1371. {
  1372. typeResDir = mResEntries.Alloc<BlResDirectory>();
  1373. typeResDir->mIsDir = true;
  1374. pair.first->second = typeResDir;
  1375. }
  1376. else
  1377. typeResDir = (BlResDirectory*)pair.first->second;
  1378. // Index by name
  1379. BlResDirectory* nameResDir;
  1380. pair = typeResDir->mEntries.insert(std::make_pair(resName, (BlResEntry*)NULL));
  1381. if (pair.second)
  1382. {
  1383. nameResDir = mResEntries.Alloc<BlResDirectory>();
  1384. nameResDir->mIsDir = true;
  1385. pair.first->second = nameResDir;
  1386. }
  1387. else
  1388. nameResDir = (BlResDirectory*)pair.first->second;
  1389. // Index by language
  1390. pair = nameResDir->mEntries.insert(std::make_pair((const char16_t*)(intptr)languageId, (BlResEntry*)NULL));
  1391. if (pair.second)
  1392. {
  1393. auto resData = mResEntries.Alloc<BlResData>();
  1394. resData->mIsDir = false;
  1395. pair.first->second = resData;
  1396. resData->mData = (uint8*)data;
  1397. resData->mSize = dataSize;
  1398. }
  1399. data += dataSize;
  1400. PTR_ALIGN(data, (uint8*)objectData->mData, 4);
  1401. }
  1402. }
  1403. void BlContext::LoadDefData(BlObjectData* objectData)
  1404. {
  1405. uint8* data = (uint8*)objectData->mData;
  1406. uint8* dataEnd = data + objectData->mSize;
  1407. char* cmdStart = (char*)data;
  1408. bool isSep = false;
  1409. std::vector<String> args;
  1410. int lineNum = 1;
  1411. auto _Fail = [&] (const StringImpl& err)
  1412. {
  1413. Fail(StrFormat("%s in %s on line %d", err.c_str(), ObjectDataIdxToString(objectData->mIdx).c_str(), lineNum));
  1414. };
  1415. bool inExports = false;
  1416. while (true)
  1417. {
  1418. char c;
  1419. auto cPtr = (char*)data;
  1420. if (data == dataEnd)
  1421. c = 0;
  1422. else
  1423. c = GET(char);
  1424. bool newIsSep = (c == ',') || (c == '=') || (c == '.');
  1425. if ((isspace(c)) || (c == 0) || (newIsSep) || (isSep))
  1426. {
  1427. if (cmdStart != NULL)
  1428. {
  1429. String str((char*)cmdStart, cPtr);
  1430. args.emplace_back(str);
  1431. cmdStart = NULL;
  1432. }
  1433. }
  1434. isSep = newIsSep;
  1435. if ((cmdStart == NULL) && (!isspace(c)))
  1436. {
  1437. cmdStart = cPtr;
  1438. }
  1439. if (((c == '\r') || (c == '\n') || (c == 0)) &&
  1440. (!args.empty()))
  1441. {
  1442. if (args[0] == "LIBRARY")
  1443. {
  1444. // Ignore
  1445. }
  1446. else if (args[0] == "EXPORTS")
  1447. {
  1448. inExports = true;
  1449. if (args.size() != 1)
  1450. _Fail("Invalid argument");
  1451. }
  1452. else if (args[0] == "HEAPSIZE")
  1453. {
  1454. if (args.size() == 2)
  1455. {
  1456. int reserve = strtol(args[1].c_str(), NULL, 0);
  1457. if (reserve != 0)
  1458. mHeapReserve = BF_ALIGN(reserve, 4);
  1459. }
  1460. else if (args.size() == 4)
  1461. {
  1462. int reserve = strtol(args[1].c_str(), NULL, 0);
  1463. if (args[2] != ",")
  1464. _Fail("Invalid arguments");
  1465. int commit = strtol(args[3].c_str(), NULL, 0);
  1466. if (reserve != 0)
  1467. mHeapReserve = BF_ALIGN(reserve, 4);
  1468. if (commit != 0)
  1469. mHeapCommit = BF_ALIGN(commit, 4);
  1470. }
  1471. else
  1472. {
  1473. _Fail("Invalid number of arguments for HEAPSIZE");
  1474. }
  1475. }
  1476. else if (args[0] == "STACKSIZE")
  1477. {
  1478. if (args.size() == 2)
  1479. {
  1480. int reserve = strtol(args[1].c_str(), NULL, 0);
  1481. if (reserve != 0)
  1482. mHeapReserve = BF_ALIGN(reserve, 4);
  1483. }
  1484. else if (args.size() == 4)
  1485. {
  1486. int reserve = strtol(args[1].c_str(), NULL, 0);
  1487. if (args[2] != ",")
  1488. _Fail("Invalid arguments");
  1489. int commit = strtol(args[3].c_str(), NULL, 0);
  1490. if (reserve != 0)
  1491. mStackReserve = BF_ALIGN(reserve, 4);
  1492. if (commit != 0)
  1493. mStackCommit = BF_ALIGN(commit, 4);
  1494. }
  1495. else
  1496. {
  1497. _Fail("Invalid number of arguments for STACKSIZE");
  1498. }
  1499. }
  1500. else if (args[0] == "VERSION")
  1501. {
  1502. if (args.size() == 2)
  1503. {
  1504. mPeVersionMajor = strtol(args[1].c_str(), NULL, 0);
  1505. }
  1506. else if (args.size() == 4)
  1507. {
  1508. mPeVersionMajor = strtol(args[1].c_str(), NULL, 0);
  1509. if (args[2] != ".")
  1510. _Fail("Invalid arguments");
  1511. mPeVersionMinor = strtol(args[3].c_str(), NULL, 0);
  1512. }
  1513. else
  1514. {
  1515. _Fail("Invalid number of arguments for VERSION");
  1516. }
  1517. }
  1518. else if (inExports)
  1519. {
  1520. BlExport blExport;
  1521. String name = args[0];
  1522. for (int argIdx = 1; argIdx < (int)args.size(); argIdx++)
  1523. {
  1524. auto& arg = args[argIdx];
  1525. if ((argIdx == 1) && (arg == "="))
  1526. {
  1527. argIdx++;
  1528. blExport.mSrcName = args[argIdx];
  1529. continue;
  1530. }
  1531. if (arg[0] == '@')
  1532. {
  1533. blExport.mOrdinal = strtol(arg.c_str() + 1, NULL, 0);
  1534. blExport.mOrdinalSpecified = true;
  1535. }
  1536. else if (arg == "NONAME")
  1537. {
  1538. blExport.mNoName = true;
  1539. }
  1540. else if (arg == "PRIVATE")
  1541. {
  1542. blExport.mIsPrivate = true;
  1543. }
  1544. else if (arg == "DATA")
  1545. {
  1546. blExport.mIsData = true;
  1547. }
  1548. else
  1549. _Fail("Invalid export argument");
  1550. }
  1551. auto pair = mExports.insert(std::make_pair(name, blExport));
  1552. if (!pair.second)
  1553. {
  1554. Warn(StrFormat("Export '%s' specified multiple times; using first specification", name.c_str()));
  1555. }
  1556. //mExports[name] = export;
  1557. }
  1558. else
  1559. {
  1560. _Fail("Unrecognized command");
  1561. }
  1562. // Process
  1563. args.clear();
  1564. }
  1565. if (c == '\n')
  1566. lineNum++;
  1567. if (c == 0)
  1568. break;
  1569. }
  1570. }
  1571. void BlContext::Init(bool is64Bit, bool isDebug)
  1572. {
  1573. char cwd[MAX_PATH];
  1574. _getcwd(cwd, MAX_PATH);
  1575. AddSearchPath(cwd);
  1576. AddSearchPath("C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\lib\\amd64\\");
  1577. AddSearchPath("C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\atlmfc\\lib\\amd64\\");
  1578. AddSearchPath("C:\\Program Files (x86)\\Windows Kits\\10\\lib\\10.0.10240.0\\ucrt\\x64\\");
  1579. AddSearchPath("C:\\Program Files (x86)\\Windows Kits\\8.1\\lib\\winv6.3\\um\\x64\\");
  1580. if (!mNoDefaultLib)
  1581. {
  1582. for (auto& libNameSrc : mDefaultLibs)
  1583. {
  1584. String libName = libNameSrc;
  1585. FixLibName(libName);
  1586. String libCanonName = FixPathAndCase(libName);
  1587. auto itr = mNoDefaultLibs.find(libCanonName);
  1588. if (itr == mNoDefaultLibs.end())
  1589. AddFile(libName, BlObjectDataKind_DefaultLib);
  1590. }
  1591. /*AddFile("libcmtd.lib", BlObjectDataKind_DefaultLib);
  1592. AddFile("oldnames.lib", BlObjectDataKind_DefaultLib);
  1593. AddFile("vcruntimed.lib", BlObjectDataKind_DefaultLib);
  1594. AddFile("ucrtd.lib", BlObjectDataKind_DefaultLib);*/
  1595. }
  1596. }
  1597. void BlContext::AddSearchPath(const StringImpl& directory)
  1598. {
  1599. String dir = directory;
  1600. if (!dir.empty())
  1601. {
  1602. char endC = dir[dir.length() - 1];
  1603. if ((endC != '\\') && (endC != '/'))
  1604. dir += "\\";
  1605. }
  1606. mSearchPaths.push_back(dir);
  1607. }
  1608. bool BlContext::DoAddFile(const StringImpl& path, BlObjectDataKind objectDataKind)
  1609. {
  1610. auto mappedFile = mMappedFiles.Alloc();
  1611. if (!mappedFile->Open(path))
  1612. {
  1613. Fail(StrFormat("Failed to open file: %s", path.c_str()));
  1614. return false;
  1615. }
  1616. BF_ASSERT(mappedFile->mData != NULL);
  1617. bool isLib = (objectDataKind != BlObjectDataKind_SpecifiedObj);
  1618. if (isLib)
  1619. {
  1620. BL_AUTOPERF("BlContext::AddFile ReadLib");
  1621. mNumLibs++;
  1622. bool isThinLib = (isLib) && (strncmp((char*)mappedFile->mData, "!<thin>\n", 8) == 0);
  1623. if ((!isThinLib) && (strncmp((char*)mappedFile->mData, "!<arch>\n", 8) != 0))
  1624. {
  1625. Fail(StrFormat("Invalid lib file format: %s", path.c_str()));
  1626. return false;
  1627. }
  1628. uint8* data = (uint8*)mappedFile->mData;
  1629. uint8* dataEnd = data + mappedFile->mFileSize;
  1630. data += 8;
  1631. std::vector<int> objectDataIndices;
  1632. const int minMemberSize = sizeof(BlLibMemberHeader);
  1633. objectDataIndices.resize(mappedFile->mFileSize / minMemberSize + 1, -1);
  1634. auto blLib = mLibs.Alloc();
  1635. blLib->mFileName = path;
  1636. int memberIdx = 0;
  1637. while (data < dataEnd)
  1638. {
  1639. BlLibMemberHeader* header = (BlLibMemberHeader*)data;
  1640. //BfBitSet archUsed;
  1641. //archUsed.Init(mappedFile->mFileSize);
  1642. data += sizeof(BlLibMemberHeader);
  1643. if ((strncmp(header->mName, "/ ", 2) == 0) && (memberIdx == 0))
  1644. {
  1645. int numSymbols = FromBigEndian(*(int32*)data);
  1646. data += 4;
  1647. uint8* strTab = data + numSymbols * 4;
  1648. for (int symIdx = 0; symIdx < numSymbols; symIdx++)
  1649. {
  1650. //OutputDebugStrF("LibSym: %s:%s\n", fileName.c_str(), (const char*)strTab);
  1651. auto blSymbol = mSymTable.Add((const char*)strTab);
  1652. strTab += strlen((char*)strTab) + 1;
  1653. if (blSymbol->mKind == BlSymKind_LibSymbolRef)
  1654. {
  1655. int groupId = (int)mImportGroups.size();
  1656. auto importGroup = mImportGroups.Alloc();
  1657. importGroup->mObjectDatas.push_back(blSymbol->mParam);
  1658. blSymbol->mKind = BlSymKind_LibSymbolGroupRef;
  1659. blSymbol->mParam = groupId;
  1660. }
  1661. if ((blSymbol->mKind != BlSymKind_Undefined) && (blSymbol->mKind != BlSymKind_WeakSymbol) &&
  1662. (blSymbol->mKind != BlSymKind_LibSymbolGroupRef))
  1663. continue;
  1664. int offset = FromBigEndian(((int32*)data)[symIdx]);
  1665. int memberNum = offset / minMemberSize;
  1666. int objectDataIdx = objectDataIndices[memberNum];
  1667. if (objectDataIdx == -1)
  1668. {
  1669. objectDataIdx = (int)mObjectDatas.size();
  1670. auto objectData = mObjectDatas.Alloc();
  1671. if (objectDataKind == BlObjectDataKind_SpecifiedObj)
  1672. objectData->mKind = BlObjectDataKind_SpecifiedLib;
  1673. else
  1674. objectData->mKind = objectDataKind;
  1675. objectData->mIdx = objectDataIdx;
  1676. objectData->mLib = blLib;
  1677. objectData->mData = (uint8*)mappedFile->mData + offset;
  1678. objectData->mLoadState = isThinLib ? BlObjectDataLoadState_UnloadedThinLib : BlObjectDataLoadState_UnloadedLib;
  1679. objectDataIndices[memberNum] = objectDataIdx;
  1680. }
  1681. if (blSymbol->mKind == BlSymKind_LibSymbolGroupRef)
  1682. {
  1683. auto importGroup = mImportGroups[blSymbol->mParam];
  1684. importGroup->mObjectDatas.push_back(objectDataIdx);
  1685. }
  1686. else
  1687. {
  1688. blSymbol->mKind = BlSymKind_LibSymbolRef;
  1689. blSymbol->mParam = objectDataIdx;
  1690. blSymbol->mObjectDataIdx = -1;
  1691. }
  1692. }
  1693. }
  1694. if (strncmp(header->mName, "// ", 3) == 0)
  1695. {
  1696. blLib->mStrTable = (char*)data;
  1697. break;
  1698. }
  1699. int len = atoi(header->mSize);
  1700. len = (len + 1) & ~1; // Even addr
  1701. data = (uint8*)header + sizeof(BlLibMemberHeader) + len;
  1702. memberIdx++;
  1703. }
  1704. }
  1705. else
  1706. {
  1707. mNumObjFiles++;
  1708. int objectDataIdx = (int)mObjectDatas.size();
  1709. auto objectData = mObjectDatas.Alloc();
  1710. objectData->mKind = objectDataKind;
  1711. objectData->mIdx = objectDataIdx;
  1712. objectData->mName = (char*)mAlloc.AllocBytes((int)path.length() + 1);
  1713. memcpy(objectData->mName, path.c_str(), path.length() + 1);
  1714. objectData->mData = mappedFile->mData;
  1715. objectData->mSize = mappedFile->mFileSize;
  1716. BF_ASSERT(objectData->mData != NULL);
  1717. mObjectDataWorkQueue.push_back(objectData);
  1718. }
  1719. return true;
  1720. }
  1721. bool BlContext::AddFile(const StringImpl& fileName, BlObjectDataKind objectDataKind)
  1722. {
  1723. BL_AUTOPERF("BlContext::AddFile");
  1724. bool isLib = false;
  1725. int dotPos = (int)fileName.LastIndexOf('.');
  1726. if ((dotPos != -1) && (strncmp(fileName.c_str() + dotPos, ".lib", 4) == 0))
  1727. {
  1728. String lookupStr = FixPathAndCase(fileName);
  1729. if (!mSeenLibs.insert(lookupStr).second)
  1730. return true; // Already seen
  1731. isLib = true;
  1732. if (objectDataKind == BlObjectDataKind_SpecifiedObj)
  1733. objectDataKind = BlObjectDataKind_SpecifiedLib;
  1734. }
  1735. bool isAbsPath = (fileName.length() >= 2) &&
  1736. ((fileName[0] == '/') || (fileName[0] == '\\') || (fileName[1] == ':'));
  1737. if (isAbsPath)
  1738. {
  1739. if (FileExists(fileName))
  1740. return DoAddFile(fileName, objectDataKind);
  1741. }
  1742. else
  1743. {
  1744. String path;
  1745. String actualFileName;
  1746. for (auto& searchPath : mSearchPaths)
  1747. {
  1748. path = searchPath;
  1749. path += fileName;
  1750. if (FileExists(path, &actualFileName))
  1751. {
  1752. path = FixFilePath(path, actualFileName);
  1753. return DoAddFile(path, objectDataKind);
  1754. }
  1755. }
  1756. }
  1757. Fail(StrFormat("Unable to locate file: %s", fileName.c_str()));
  1758. return false;
  1759. }
  1760. void BlContext::PopulateIData_LookupTable(BlSegment* iDataSect, int& hintNameTableSize)
  1761. {
  1762. int importLookupTableSize = ((int)mImportLookups.size() + (int)mImportFiles.size()) * 8;
  1763. int importDirectoryTableSize = ((int)mImportFiles.size() + 1) * 20;
  1764. int hintNameTableOfs = importLookupTableSize + importDirectoryTableSize + importLookupTableSize;
  1765. // Import lookup table
  1766. for (auto& importFilePair : mImportFiles)
  1767. {
  1768. auto& importFile = importFilePair.second;
  1769. for (auto lookup : importFile.mLookups)
  1770. {
  1771. if (lookup->mName.empty())
  1772. {
  1773. mImportStream.Write((int64)0x8000000000000000LL | lookup->mHint);
  1774. }
  1775. else
  1776. {
  1777. mImportStream.Write((int64)iDataSect->mRVA + hintNameTableOfs + hintNameTableSize);
  1778. hintNameTableSize += 2;
  1779. hintNameTableSize += (int)lookup->mName.length() + 1;
  1780. if ((hintNameTableSize % 2) == 1)
  1781. hintNameTableSize++;
  1782. }
  1783. }
  1784. mImportStream.Write((int64)0);
  1785. }
  1786. }
  1787. void BlContext::PopulateIData(BlSegment* iDataSect)
  1788. {
  1789. int importLookupTableSize = ((int)mImportLookups.size() + (int)mImportFiles.size()) * 8;
  1790. int hintNameTableSize = 0;
  1791. PopulateIData_LookupTable(iDataSect, hintNameTableSize);
  1792. int idataIdx = 0;
  1793. int thunkIdx = 0;
  1794. for (auto& importFilePair : mImportFiles)
  1795. {
  1796. auto& importFile = importFilePair.second;
  1797. for (auto lookup : importFile.mLookups)
  1798. {
  1799. lookup->mThunkIdx = thunkIdx++;
  1800. lookup->mIDataIdx = idataIdx++;
  1801. }
  1802. idataIdx++; // For NULL entry
  1803. }
  1804. int importDirectoryTableSize = ((int)mImportFiles.size() + 1) * 20;
  1805. int importDirOfs = importLookupTableSize;
  1806. int importLookupOfs = importDirOfs + importDirectoryTableSize;
  1807. int hintNameTableOfs = importLookupTableSize + importDirectoryTableSize + importLookupTableSize;
  1808. int strTableOfs = hintNameTableOfs + hintNameTableSize;
  1809. // Import directory
  1810. int curLookupIdx = 0;
  1811. for (auto& importFilePair : mImportFiles)
  1812. {
  1813. auto& importFileName = importFilePair.first;
  1814. auto& importFile = importFilePair.second;
  1815. mImportStream.Write((int32)(iDataSect->mRVA + importLookupOfs + curLookupIdx*8)); // Import lookup table RVA
  1816. mImportStream.Write((int32)0); // Timestamp
  1817. mImportStream.Write((int32)0); // Forwarder chain
  1818. mImportStream.Write((int32)(iDataSect->mRVA + strTableOfs)); // Name RVA
  1819. mImportStream.Write((int32)(iDataSect->mRVA + curLookupIdx * 8)); // Import address table RVA
  1820. curLookupIdx += (int)importFile.mLookups.size() + 1;
  1821. strTableOfs += (int)importFileName.length() + 1;
  1822. }
  1823. // Empty import directory entry terminates
  1824. mImportStream.WriteZeros(20);
  1825. hintNameTableSize = 0;
  1826. PopulateIData_LookupTable(iDataSect, hintNameTableSize);
  1827. // Hint/Name Table
  1828. for (auto& importFilePair : mImportFiles)
  1829. {
  1830. auto& importFile = importFilePair.second;
  1831. for (auto lookup : importFile.mLookups)
  1832. {
  1833. if (!lookup->mName.empty())
  1834. {
  1835. mImportStream.Write((int16)lookup->mHint);
  1836. mImportStream.Write((void*)lookup->mName.c_str(), (int)lookup->mName.length() + 1);
  1837. if ((mImportStream.GetPos() % 2) == 1)
  1838. mImportStream.Write((uint8)0);
  1839. }
  1840. }
  1841. }
  1842. // Str table
  1843. for (auto& importFilePair : mImportFiles)
  1844. {
  1845. auto& importFileName = importFilePair.first;
  1846. mImportStream.Write((void*)importFileName.c_str(), (int)importFileName.length() + 1);
  1847. }
  1848. BF_ASSERT(mImportStream.GetPos() == strTableOfs);
  1849. BlChunk chunk;
  1850. chunk.mOffset = 0;
  1851. chunk.mAlignPad = 0;
  1852. chunk.mData = (void*)&mImportStream.mData[0];
  1853. chunk.mSize = mImportStream.GetSize();
  1854. iDataSect->mChunks.push_back(chunk);
  1855. BF_ASSERT(iDataSect->mCurSize == chunk.mSize);
  1856. }
  1857. BlSegment* BlContext::CreateIData()
  1858. {
  1859. auto iDataSect = mDynSegments.Alloc();
  1860. iDataSect->mName = ".idata";
  1861. iDataSect->mContext = this;
  1862. iDataSect->mSegmentIdx = (int)mSegments.size();
  1863. iDataSect->mAlign = 8;
  1864. iDataSect->mCharacteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
  1865. mSegments.push_back(iDataSect);
  1866. mOrderedSegments.push_back(iDataSect);
  1867. int hintNameTableSize = 0;
  1868. for (auto& importFilePair : mImportFiles)
  1869. {
  1870. auto& importFile = importFilePair.second;
  1871. for (auto lookup : importFile.mLookups)
  1872. {
  1873. if (!lookup->mName.empty())
  1874. {
  1875. hintNameTableSize += 2;
  1876. hintNameTableSize += (int)lookup->mName.length() + 1;
  1877. if ((hintNameTableSize % 2) == 1)
  1878. hintNameTableSize++;
  1879. }
  1880. }
  1881. }
  1882. int importLookupTableSize = ((int)mImportLookups.size() + (int)mImportFiles.size()) * 8;
  1883. int importDirectoryTableSize = ((int)mImportFiles.size() + 1) * 20;
  1884. int hintNameTableOfs = importLookupTableSize + importDirectoryTableSize + importLookupTableSize;
  1885. int strTableOfs = hintNameTableOfs + hintNameTableSize;
  1886. // Import directory
  1887. int curLookupIdx = 0;
  1888. for (auto& importFilePair : mImportFiles)
  1889. {
  1890. auto& importFileName = importFilePair.first;
  1891. strTableOfs += (int)importFileName.length() + 1;
  1892. }
  1893. iDataSect->mCurSize = strTableOfs;
  1894. return iDataSect;
  1895. }
  1896. BlSegment* BlContext::CreateThunkData()
  1897. {
  1898. if (mImportLookups.empty())
  1899. return NULL;
  1900. auto thunkSect = mDynSegments.Alloc();
  1901. thunkSect->mName = ".text$thunk";
  1902. thunkSect->mContext = this;
  1903. thunkSect->mSegmentIdx = (int)mSegments.size();
  1904. thunkSect->mAlign = 8;
  1905. thunkSect->mCharacteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE;
  1906. mSegments.push_back(thunkSect);
  1907. mOrderedSegments.push_back(thunkSect);
  1908. thunkSect->mCurSize = (int)mImportLookups.size() * 6;
  1909. return thunkSect;
  1910. }
  1911. void BlContext::PopulateExportData(BlSegment* exportSeg)
  1912. {
  1913. std::vector<uint32> rvaMap;
  1914. String libName = GetFileName(mOutName);
  1915. DynMemStream strTab;
  1916. int numNames = 0;
  1917. int maxOrdinal = 0;
  1918. for (auto& exportPair : mExports)
  1919. {
  1920. const StringImpl& name = exportPair.first;
  1921. auto& blExport = exportPair.second;
  1922. String symName;
  1923. if (!blExport.mSrcName.empty())
  1924. symName = blExport.mSrcName;
  1925. else
  1926. symName = name;
  1927. if (!blExport.mNoName)
  1928. numNames++;
  1929. int ordIdx = blExport.mOrdinal - 1;
  1930. while (ordIdx >= rvaMap.size())
  1931. rvaMap.push_back(0);
  1932. auto sym = ResolveSym(symName.c_str(), false);
  1933. if (sym == NULL)
  1934. {
  1935. Fail(StrFormat("Unable to find exported symbol '%s'", symName.c_str()));
  1936. }
  1937. else
  1938. {
  1939. rvaMap[ordIdx] = (uint32)GetSymAddr(sym);
  1940. }
  1941. }
  1942. int numEntries = maxOrdinal - 1;
  1943. int32 funcRVA = exportSeg->mRVA + (int)sizeof(IMAGE_EXPORT_DIRECTORY);
  1944. int32 namePtrTabRVA = funcRVA + (int)rvaMap.size() * 4;
  1945. int32 ordTabRVA = namePtrTabRVA + numNames * 4;
  1946. int32 strTabRVA = ordTabRVA + numNames * 2;
  1947. // Export Directory Table
  1948. IMAGE_EXPORT_DIRECTORY exportDir = { 0 };
  1949. exportDir.Name = strTabRVA + strTab.GetSize();
  1950. strTab.Write((void*)libName.c_str(), (int)libName.length() + 1);
  1951. exportDir.Base = 1;
  1952. exportDir.NumberOfFunctions = (uint32)rvaMap.size();
  1953. exportDir.NumberOfNames = numNames;
  1954. exportDir.AddressOfFunctions = funcRVA;
  1955. exportDir.AddressOfNames = namePtrTabRVA;
  1956. exportDir.AddressOfNameOrdinals = ordTabRVA;
  1957. mExportStream.WriteT(exportDir);
  1958. // Export Address Table
  1959. mExportStream.Write((void*)&rvaMap[0], (int)rvaMap.size() * 4);
  1960. // Name Pointer Table
  1961. for (auto& exportPair : mExports)
  1962. {
  1963. const StringImpl& name = exportPair.first;
  1964. auto& blExport = exportPair.second;
  1965. if (!blExport.mNoName)
  1966. {
  1967. mExportStream.Write((int32)(strTabRVA + strTab.GetSize()));
  1968. strTab.Write((void*)name.c_str(), (int)name.length() + 1);
  1969. }
  1970. }
  1971. // Export Ordinal Table
  1972. for (auto& exportPair : mExports)
  1973. {
  1974. auto& blExport = exportPair.second;
  1975. if (!blExport.mNoName)
  1976. mExportStream.Write((int16)(blExport.mOrdinal - 1));
  1977. }
  1978. // String table data
  1979. mExportStream.Write(strTab.GetPtr(), strTab.GetSize());
  1980. BlChunk chunk;
  1981. chunk.mOffset = 0;
  1982. chunk.mAlignPad = 0;
  1983. chunk.mData = mExportStream.GetPtr();
  1984. chunk.mSize = mExportStream.GetSize();
  1985. exportSeg->mChunks.push_back(chunk);
  1986. BF_ASSERT(exportSeg->mCurSize == chunk.mSize);
  1987. }
  1988. BlSegment* BlContext::CreateExportData()
  1989. {
  1990. if (mExports.size() == 0)
  1991. return NULL;
  1992. String libName = GetFileName(mOutName);
  1993. int curOrdinal = 1;
  1994. int maxOrdinal = 0;
  1995. std::unordered_map<int, const String*> usedIds;
  1996. std::vector<int> ordinalMap;
  1997. int strTableSize = (int)libName.length() + 1;
  1998. int numNames = 0;
  1999. for (auto& exportPair : mExports)
  2000. {
  2001. auto& name = exportPair.first;
  2002. auto& blExport = exportPair.second;
  2003. if (blExport.mOrdinal > 0)
  2004. {
  2005. maxOrdinal = std::max(maxOrdinal, blExport.mOrdinal);
  2006. auto pair = usedIds.insert(std::make_pair(blExport.mOrdinal, &name));
  2007. if (!pair.second)
  2008. {
  2009. Fail(StrFormat("Export '%s' and export '%s' both specified ordinal %d", pair.first->second->c_str(), exportPair.first.c_str(), blExport.mOrdinal));
  2010. blExport.mOrdinal = -1;
  2011. }
  2012. }
  2013. if (!blExport.mNoName)
  2014. {
  2015. strTableSize += (int)name.length() + 1;
  2016. numNames++;
  2017. }
  2018. }
  2019. for (auto& exportPair : mExports)
  2020. {
  2021. const StringImpl& name = exportPair.first;
  2022. auto& blExport = exportPair.second;
  2023. if (blExport.mOrdinal <= 0)
  2024. {
  2025. while (usedIds.find(curOrdinal) != usedIds.end())
  2026. curOrdinal++;
  2027. blExport.mOrdinal = curOrdinal++;
  2028. maxOrdinal = std::max(maxOrdinal, blExport.mOrdinal);
  2029. }
  2030. }
  2031. int numEntries = maxOrdinal;
  2032. auto thunkSect = mDynSegments.Alloc();
  2033. thunkSect->mName = ".rdata$export";
  2034. thunkSect->mContext = this;
  2035. thunkSect->mSegmentIdx = (int)mSegments.size();
  2036. thunkSect->mAlign = 8;
  2037. thunkSect->mCharacteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
  2038. mSegments.push_back(thunkSect);
  2039. mOrderedSegments.push_back(thunkSect);
  2040. thunkSect->mCurSize = sizeof(IMAGE_EXPORT_DIRECTORY) + (numEntries * 4) + (numNames * 4) + (numNames * 2) + strTableSize;
  2041. return thunkSect;
  2042. }
  2043. void BlContext::PopulateCvInfoData(BlSegment* cvInfoSect)
  2044. {
  2045. mCvInfoStream.Write((int32)'SDSR');
  2046. mCvInfoStream.WriteT(mCodeView->mSignature);
  2047. mCvInfoStream.Write(mCodeView->mAge);
  2048. String pdbName = mCodeView->mMsf.mFileName;
  2049. //String pdbName = "C:\\proj\\TestCPP\\x64\\Debug\\TestCPP.pdb";
  2050. mCvInfoStream.Write((void*)pdbName.c_str(), (int)pdbName.length() + 1);
  2051. BlChunk chunk;
  2052. chunk.mOffset = 0;
  2053. chunk.mAlignPad = 0;
  2054. chunk.mData = (void*)&mCvInfoStream.mData[0];
  2055. chunk.mSize = mCvInfoStream.GetSize();
  2056. cvInfoSect->mChunks.push_back(chunk);
  2057. }
  2058. BlSegment* BlContext::CreateCvInfoData()
  2059. {
  2060. auto cvInfoSect = mDynSegments.Alloc();
  2061. cvInfoSect->mName = ".rdata$cvInfo";
  2062. cvInfoSect->mContext = this;
  2063. cvInfoSect->mSegmentIdx = (int)mSegments.size();
  2064. cvInfoSect->mAlign = 8;
  2065. cvInfoSect->mCharacteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
  2066. mSegments.push_back(cvInfoSect);
  2067. mOrderedSegments.push_back(cvInfoSect);
  2068. cvInfoSect->mCurSize = 4 + 4 + 16 + (int)mCodeView->mMsf.mFileName.length() + 1;
  2069. return cvInfoSect;
  2070. }
  2071. void BlContext::PopulateDebugDirData(BlSegment* debugDirSect, BlSegment* cvInfoSect)
  2072. {
  2073. IMAGE_DEBUG_DIRECTORY debugDir = { 0 };
  2074. debugDir.TimeDateStamp = mTimestamp;
  2075. debugDir.Type = 2;
  2076. debugDir.SizeOfData = cvInfoSect->mCurSize;
  2077. debugDir.AddressOfRawData = cvInfoSect->mRVA;
  2078. auto outSection = mOutSections[cvInfoSect->mOutSectionIdx];
  2079. debugDir.PointerToRawData = (cvInfoSect->mRVA - outSection->mRVA) + outSection->mRawDataPos;
  2080. mDebugDirStream.WriteT(debugDir);
  2081. BlChunk chunk;
  2082. chunk.mOffset = 0;
  2083. chunk.mAlignPad = 0;
  2084. chunk.mData = (void*)&mDebugDirStream.mData[0];
  2085. chunk.mSize = mDebugDirStream.GetSize();
  2086. debugDirSect->mChunks.push_back(chunk);
  2087. BF_ASSERT(debugDirSect->mCurSize == chunk.mSize);
  2088. }
  2089. BlSegment* BlContext::CreateDebugDirData()
  2090. {
  2091. auto debugDirSect = mDynSegments.Alloc();
  2092. debugDirSect->mName = ".rdata$debugDir";
  2093. debugDirSect->mContext = this;
  2094. debugDirSect->mSegmentIdx = (int)mSegments.size();
  2095. debugDirSect->mAlign = 8;
  2096. debugDirSect->mCharacteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
  2097. mSegments.push_back(debugDirSect);
  2098. mOrderedSegments.push_back(debugDirSect);
  2099. debugDirSect->mCurSize = sizeof(IMAGE_DEBUG_DIRECTORY);
  2100. return debugDirSect;
  2101. }
  2102. void BlContext::GetResDataStats(BlResDirectory* resDir, int& dirCount, int& dataCount, int& symsStrsSize, int& dataSize)
  2103. {
  2104. for (auto& pair : resDir->mEntries)
  2105. {
  2106. auto resId = pair.first;
  2107. if (IsResIdNamed(resId))
  2108. symsStrsSize += 2 + (int)wcslen((wchar_t*)resId) * 2;
  2109. auto entry = pair.second;
  2110. if (entry->mIsDir)
  2111. {
  2112. dirCount++;
  2113. GetResDataStats((BlResDirectory*)entry, dirCount, dataCount, symsStrsSize, dataSize);
  2114. }
  2115. else
  2116. {
  2117. BlResData* resData = (BlResData*)entry;
  2118. dataCount++;
  2119. dataSize += resData->mSize;
  2120. }
  2121. }
  2122. }
  2123. void BlContext::CreateResData(BlSegment* resSeg, BlResDirectory* resDir, int resDirSize, int symsStrSize, DynMemStream& symStrsStream, DynMemStream& dataEntryStream)
  2124. {
  2125. int numNamedEntries = 0;
  2126. int numIdEntries = 0;
  2127. for (auto& pair : resDir->mEntries)
  2128. {
  2129. auto resId = pair.first;
  2130. if (IsResIdNamed(resId))
  2131. numNamedEntries++;
  2132. else
  2133. numIdEntries++;
  2134. }
  2135. mResDataStream.Write(0); // Characteristics (always 0)
  2136. mResDataStream.Write(0); // Timestamp
  2137. mResDataStream.Write(0); // Version
  2138. mResDataStream.Write((int16)numNamedEntries); // Number of named entries
  2139. mResDataStream.Write((int16)numIdEntries); // Number of id entries
  2140. int curEntriesPos = mResDataStream.GetPos();
  2141. mResDataStream.WriteZeros((int)resDir->mEntries.size() * 8);
  2142. for (int pass = 0; pass < 2; pass++)
  2143. {
  2144. for (auto& pair : resDir->mEntries)
  2145. {
  2146. auto resId = pair.first;
  2147. if ((IsResIdNamed(resId)) == (pass == 0))
  2148. {
  2149. if (pass == 0)
  2150. {
  2151. // Name
  2152. *(int32*)(&mResDataStream.mData[curEntriesPos]) = 0x80000000 | (resDirSize + symStrsStream.GetSize());
  2153. int strLen = (int)wcslen((wchar_t*)resId);
  2154. symStrsStream.Write((int16)strLen);
  2155. symStrsStream.Write((uint8*)resId, strLen * 2);
  2156. }
  2157. else
  2158. *(int32*)(&mResDataStream.mData[curEntriesPos]) = (int16)(intptr)resId;
  2159. auto resEntry = pair.second;
  2160. if (resEntry->mIsDir)
  2161. {
  2162. *(int32*)(&mResDataStream.mData[curEntriesPos + 4]) = 0x80000000 | mResDataStream.GetPos();
  2163. CreateResData(resSeg, (BlResDirectory*)resEntry, resDirSize, symsStrSize, symStrsStream, dataEntryStream);
  2164. }
  2165. else
  2166. {
  2167. BlResData* resData = (BlResData*)resEntry;
  2168. *(int32*)(&mResDataStream.mData[curEntriesPos + 4]) = (resDirSize + symsStrSize) + dataEntryStream.GetSize();
  2169. dataEntryStream.Write((int32)(resSeg->mRVA + resSeg->mCurSize));
  2170. dataEntryStream.Write((int32)resData->mSize);
  2171. dataEntryStream.Write((int32)0); // Codepage
  2172. dataEntryStream.Write((int32)0); // Reserved
  2173. BlChunk chunk;
  2174. chunk.mOffset = -1;
  2175. chunk.mAlignPad = 0;
  2176. chunk.mData = resData->mData;
  2177. chunk.mSize = resData->mSize;
  2178. resSeg->mChunks.push_back(chunk);
  2179. resSeg->mCurSize += resData->mSize;
  2180. }
  2181. curEntriesPos += 8;
  2182. }
  2183. }
  2184. }
  2185. }
  2186. void BlContext::PopulateResData(BlSegment* resSeg)
  2187. {
  2188. int prevSize = resSeg->mCurSize;
  2189. // Insert fake chunk
  2190. {
  2191. BlChunk chunk;
  2192. chunk.mOffset = 0;
  2193. chunk.mAlignPad = 0;
  2194. chunk.mData = 0;
  2195. chunk.mSize = 0;
  2196. resSeg->mChunks.push_back(chunk);
  2197. }
  2198. int dirCount = 0;
  2199. int dataCount = 0;
  2200. int symsStrSize = 0;
  2201. int dataSize = 0;
  2202. GetResDataStats(&mRootResDirectory, dirCount, dataCount, symsStrSize, dataSize);
  2203. int resDirSize = 16 + ((16 + 8) * dirCount) + ((8) * dataCount);
  2204. resSeg->mCurSize = resDirSize + symsStrSize + (dataCount * 16);
  2205. DynMemStream symStrsStream;
  2206. DynMemStream dataEntryStream;
  2207. CreateResData(resSeg, &mRootResDirectory, resDirSize, symsStrSize, symStrsStream, dataEntryStream);
  2208. BF_ASSERT(mResDataStream.GetSize() == resDirSize);
  2209. if (symStrsStream.GetSize() != 0)
  2210. mResDataStream.Write(symStrsStream.GetPtr(), symStrsStream.GetSize());
  2211. if (dataEntryStream.GetSize() != 0)
  2212. mResDataStream.Write(dataEntryStream.GetPtr(), dataEntryStream.GetSize());
  2213. BlChunk& chunk = resSeg->mChunks.front();
  2214. chunk.mData = (void*)&mResDataStream.mData[0];
  2215. chunk.mSize = mResDataStream.GetSize();
  2216. BF_ASSERT(resSeg->mCurSize == prevSize);
  2217. }
  2218. BlSegment* BlContext::CreateSegment(const StringImpl& name, int characteristics, int align)
  2219. {
  2220. auto seg = mDynSegments.Alloc();
  2221. seg->mName = name;
  2222. seg->mContext = this;
  2223. seg->mSegmentIdx = (int)mSegments.size();
  2224. seg->mAlign = align;
  2225. seg->mCharacteristics = characteristics;
  2226. AddSegment(seg);
  2227. return seg;
  2228. }
  2229. BlSegment* BlContext::CreateResData()
  2230. {
  2231. String manifest;
  2232. manifest += "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>\n";
  2233. manifest += "<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>\n";
  2234. manifest += " <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n";
  2235. manifest += " <security>\n";
  2236. manifest += " <requestedPrivileges>\n";
  2237. manifest += " <requestedExecutionLevel ";
  2238. manifest += mManifestUAC;
  2239. manifest += " />\n";
  2240. manifest += " </requestedPrivileges>\n";
  2241. manifest += " </security>\n";
  2242. manifest += " </trustInfo>\n";
  2243. manifest += "</assembly>\n";
  2244. mManifestData = manifest;
  2245. auto idResDir = mResEntries.Alloc<BlResDirectory>();
  2246. auto langDir = mResEntries.Alloc<BlResDirectory>();
  2247. auto manifestData = mResEntries.Alloc<BlResData>();
  2248. manifestData->mIsDir = false;
  2249. manifestData->mData = (void*)mManifestData.c_str();
  2250. manifestData->mSize = (int)mManifestData.length();
  2251. mRootResDirectory.mEntries[(const char16_t*)(intptr)24] = idResDir;
  2252. idResDir->mEntries[(const char16_t*)(intptr)0] = langDir;
  2253. langDir->mEntries[(const char16_t*)(intptr)1033] = manifestData;
  2254. auto resSeg = CreateSegment(".rsrc", IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ, 8);
  2255. int dirCount = 0;
  2256. int dataCount = 0;
  2257. int symsStrSize = 0;
  2258. int dataSize = 0;
  2259. GetResDataStats(&mRootResDirectory, dirCount, dataCount, symsStrSize, dataSize);
  2260. int resDirSize = 16 + ((16 + 8) * dirCount) + ((8) * dataCount);
  2261. resSeg->mCurSize = resDirSize + symsStrSize + (dataCount * 16) + dataSize;
  2262. return resSeg;
  2263. }
  2264. void BlContext::PopulateThunkData(BlSegment* thunkSect, BlSegment* iDataSect)
  2265. {
  2266. for (auto& importFilePair : mImportFiles)
  2267. {
  2268. auto& importFile = importFilePair.second;
  2269. for (auto lookup : importFile.mLookups)
  2270. {
  2271. // jmp qword ptr [Rel32]
  2272. mThunkStream.Write((uint8)0xFF);
  2273. mThunkStream.Write((uint8)0x25);
  2274. int32 targetAddr = iDataSect->mRVA + (lookup->mIDataIdx * 8);
  2275. targetAddr -= thunkSect->mRVA + (lookup->mThunkIdx * 6) + 6;
  2276. mThunkStream.Write((int32)targetAddr);
  2277. }
  2278. }
  2279. BlChunk chunk;
  2280. chunk.mOffset = 0;
  2281. chunk.mAlignPad = 0;
  2282. chunk.mData = (void*)&mThunkStream.mData[0];
  2283. chunk.mSize = mThunkStream.GetSize();
  2284. thunkSect->mChunks.push_back(chunk);
  2285. BF_ASSERT(thunkSect->mCurSize == chunk.mSize);
  2286. }
  2287. namespace BeefyDbg64
  2288. {
  2289. void TestPDB(const StringImpl& fileName);
  2290. }
  2291. void BlContext::WriteOutSection(BlOutSection* outSection, DataStream* st)
  2292. {
  2293. int startPos = st->GetPos();
  2294. auto _FillBytes = [&](int size)
  2295. {
  2296. if ((outSection->mCharacteristics & IMAGE_SCN_MEM_EXECUTE) != 0)
  2297. {
  2298. uint64 fillData = 0xCCCCCCCCCCCCCCCCLL;
  2299. int alignLeft = size;
  2300. while (alignLeft > 0)
  2301. {
  2302. int alignWrite = std::min(alignLeft, 8);
  2303. st->Write(&fillData, alignWrite);
  2304. alignLeft -= alignWrite;
  2305. }
  2306. }
  2307. else
  2308. {
  2309. st->WriteZeros(size);
  2310. }
  2311. };
  2312. for (auto sect : outSection->mSegments)
  2313. {
  2314. int curPos = st->GetPos();
  2315. int wantPos = (curPos + (sect->mAlign - 1)) & ~(sect->mAlign - 1);
  2316. _FillBytes(wantPos - curPos);
  2317. int sectStartPos = wantPos;
  2318. BF_ASSERT(outSection->mRVA + sectStartPos - startPos == sect->mRVA);
  2319. BlReloc* nextReloc = NULL;
  2320. int curRelocIdx = 0;
  2321. if (!sect->mRelocs.empty())
  2322. nextReloc = &sect->mRelocs[0];
  2323. int curSectOfs = 0;
  2324. for (auto& chunk : sect->mChunks)
  2325. {
  2326. BF_ASSERT(st->GetPos() == sectStartPos + curSectOfs);
  2327. _FillBytes(chunk.mAlignPad);
  2328. curSectOfs += chunk.mAlignPad;
  2329. BF_ASSERT((chunk.mOffset == curSectOfs) || (chunk.mOffset == -1));
  2330. uint8* data = (uint8*)chunk.mData;
  2331. int sizeLeft = chunk.mSize;
  2332. while (sizeLeft > 0)
  2333. {
  2334. if (nextReloc != NULL)
  2335. {
  2336. int relocOfs = nextReloc->mOutOffset - curSectOfs;
  2337. BF_ASSERT(relocOfs >= 0);
  2338. if (relocOfs < sizeLeft)
  2339. {
  2340. st->Write(data, relocOfs);
  2341. curSectOfs += relocOfs;
  2342. data += relocOfs;
  2343. sizeLeft -= relocOfs;
  2344. int64 relocOutVal = 0;
  2345. int relocOutSize = 0;
  2346. int resolvedAddr;
  2347. bool wasAbs = false;
  2348. if (nextReloc->mSegmentIdx == (int)BlSymKind_ImageBaseRel)
  2349. {
  2350. resolvedAddr = nextReloc->mSegmentOffset;
  2351. }
  2352. else if (nextReloc->mSegmentIdx == (int)BlSymKind_Absolute)
  2353. {
  2354. resolvedAddr = nextReloc->mSegmentOffset;
  2355. wasAbs = true;
  2356. }
  2357. else
  2358. {
  2359. if (nextReloc->mKind == BlRelocKind_SECREL)
  2360. {
  2361. BlSegment* resolvedSect = mSegments[nextReloc->mSegmentIdx];
  2362. auto outSection = mOutSections[resolvedSect->mOutSectionIdx];
  2363. relocOutSize = 4;
  2364. relocOutVal = (resolvedSect->mRVA - outSection->mRVA) + nextReloc->mSegmentOffset + *(int32*)data;
  2365. }
  2366. else
  2367. {
  2368. BlSegment* resolvedSect = mSegments[nextReloc->mSegmentIdx];
  2369. resolvedAddr = resolvedSect->mRVA + nextReloc->mSegmentOffset;
  2370. }
  2371. }
  2372. switch (nextReloc->mKind)
  2373. {
  2374. case BlRelocKind_ADDR32NB:
  2375. relocOutVal = resolvedAddr + *(int32*)data;
  2376. relocOutSize = 4;
  2377. break;
  2378. case BlRelocKind_ADDR64:
  2379. if (wasAbs)
  2380. {
  2381. relocOutVal = resolvedAddr + *(int32*)data;
  2382. // In cases like loadcfg.obj, __guard_flags gets truncated at the end
  2383. relocOutVal = std::min(8, sizeLeft);
  2384. }
  2385. else
  2386. {
  2387. if (!mHasFixedBase)
  2388. mPeRelocs.Add(sect->mRVA + nextReloc->mOutOffset, IMAGE_REL_BASED_DIR64);
  2389. relocOutVal = mImageBase + resolvedAddr + *(int32*)data;
  2390. relocOutSize = 8;
  2391. }
  2392. break;
  2393. case BlRelocKind_REL32:
  2394. relocOutVal = resolvedAddr + *(int32*)data;
  2395. relocOutVal -= sect->mRVA + curSectOfs + 4;
  2396. relocOutSize = 4;
  2397. break;
  2398. case BlRelocKind_REL32_1:
  2399. relocOutVal = resolvedAddr + *(int32*)data;
  2400. relocOutVal -= sect->mRVA + curSectOfs + 5;
  2401. relocOutSize = 4;
  2402. break;
  2403. case BlRelocKind_REL32_4:
  2404. relocOutVal = resolvedAddr + *(int32*)data;
  2405. relocOutVal -= sect->mRVA + curSectOfs + 8;
  2406. relocOutSize = 4;
  2407. break;
  2408. case BlRelocKind_SECREL:
  2409. // Handled
  2410. break;
  2411. default:
  2412. NotImpl();
  2413. break;
  2414. }
  2415. st->Write(&relocOutVal, relocOutSize);
  2416. curSectOfs += relocOutSize;
  2417. data += relocOutSize;
  2418. sizeLeft -= relocOutSize;
  2419. curRelocIdx++;
  2420. if (curRelocIdx < (int)sect->mRelocs.size())
  2421. nextReloc = &sect->mRelocs[curRelocIdx];
  2422. else
  2423. nextReloc = NULL;
  2424. continue;
  2425. }
  2426. }
  2427. st->Write(data, sizeLeft);
  2428. curSectOfs += sizeLeft;
  2429. sizeLeft = 0;
  2430. break;
  2431. }
  2432. BF_ASSERT(sizeLeft == 0);
  2433. //TODO:
  2434. }
  2435. }
  2436. }
  2437. static void FormatNZ(char* toStr, const char* fmt ...)
  2438. {
  2439. char buffer[32];
  2440. va_list argList;
  2441. va_start(argList, fmt);
  2442. int result = _vsprintf_l(buffer, fmt, NULL, argList);
  2443. va_end(argList);
  2444. memcpy(toStr, buffer, result);
  2445. }
  2446. // If this fails, then investigate the SectionRef vs SectionDef rules in BeCOFFObject::MarkSectionUsed
  2447. void BlContext::WriteDLLLib(const StringImpl& libName)
  2448. {
  2449. FileStream fs;
  2450. if (!fs.Open(libName, "wb"))
  2451. {
  2452. Fail(StrFormat("Unable to create file \"%s\"", libName.c_str()));
  2453. return;
  2454. }
  2455. //mExports.clear();
  2456. struct _LibSym
  2457. {
  2458. int mOfsIdx;
  2459. int mDataPos;
  2460. BlExport* mExport;
  2461. String mName;
  2462. String mExportName;
  2463. _LibSym* mImp;
  2464. void* mData;
  2465. int mDataSize;
  2466. _LibSym()
  2467. {
  2468. mOfsIdx = -1;
  2469. mDataPos = -1;
  2470. mExport = NULL;
  2471. mImp = NULL;
  2472. mData = NULL;
  2473. mDataSize = 0;
  2474. }
  2475. };
  2476. OwnedVector<_LibSym> libSyms;
  2477. String dllName = GetFileName(mOutName);
  2478. String baseName = dllName.Substring(0, dllName.length() - 4);
  2479. auto _CreateDebugSect = [] (BeCOFFObject& coffObject)
  2480. {
  2481. // Not actually needed
  2482. return;
  2483. /*auto debugSect = coffObject.CreateSect(".debug$S", IMAGE_SCN_ALIGN_1BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_DISCARDABLE, false);
  2484. unsigned char hexData[66] = {
  2485. 0x02, 0x00, 0x00, 0x00, 0x13, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x54, 0x65, 0x73,
  2486. 0x74, 0x44, 0x6C, 0x6C, 0x32, 0x2E, 0x64, 0x6C, 0x6C, 0x27, 0x00, 0x13, 0x10, 0x07, 0x00, 0x00,
  2487. 0x00, 0xD0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x97, 0x5E, 0x12,
  2488. 0x4D, 0x69, 0x63, 0x72, 0x6F, 0x73, 0x6F, 0x66, 0x74, 0x20, 0x28, 0x52, 0x29, 0x20, 0x4C, 0x49,
  2489. 0x4E, 0x4B
  2490. };
  2491. debugSect->mData.Write(hexData, 0x42);*/
  2492. };
  2493. String importDescriptorName = "__IMPORT_DESCRIPTOR_" + baseName;
  2494. String nullImportDescriptorName = "__NULL_IMPORT_DESCRIPTOR";
  2495. String nullThunkDataName = "\x7F";
  2496. nullThunkDataName += baseName;
  2497. nullThunkDataName += "_NULL_THUNK_DATA";
  2498. //
  2499. DynMemStream importDescriptorStream;
  2500. {
  2501. BeCOFFObject coffObject;
  2502. coffObject.mStream = &importDescriptorStream;
  2503. coffObject.mTimestamp = mTimestamp;
  2504. // iData entry
  2505. auto idata2Sect = coffObject.CreateSect(".idata$2", IMAGE_SCN_ALIGN_4BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE);
  2506. idata2Sect->mData.WriteZeros(0x14);
  2507. // Dll name entry
  2508. auto idata6Sect = coffObject.CreateSect(".idata$6", IMAGE_SCN_ALIGN_2BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, false);
  2509. idata6Sect->mData.WriteSZ(dllName);
  2510. idata6Sect->mData.Align(2);
  2511. BeMCSymbol* nameSectSym = coffObject.mSymbols.Alloc();
  2512. nameSectSym->mSymKind = BeMCSymbolKind_External;
  2513. nameSectSym->mIsStatic = true;
  2514. nameSectSym->mSectionNum = idata6Sect->mSectionIdx + 1;
  2515. nameSectSym->mName = ".idata$6";
  2516. nameSectSym->mIdx = (int)coffObject.mSymbols.size() - 1;
  2517. BeMCSymbol* coffSym = coffObject.mSymbols.Alloc();
  2518. coffSym->mSymKind = BeMCSymbolKind_External;
  2519. coffSym->mSectionNum = idata2Sect->mSectionIdx + 1;
  2520. coffSym->mName = importDescriptorName;
  2521. coffSym->mIsStatic = false;
  2522. BeMCSymbol* idata4Sym = coffObject.mSymbols.Alloc();
  2523. idata4Sym->mSymKind = BeMCSymbolKind_SectionRef;
  2524. idata4Sym->mName = ".idata$4";
  2525. idata4Sym->mIdx = (int)coffObject.mSymbols.size() - 1;
  2526. BeMCSymbol* idata5Sym = coffObject.mSymbols.Alloc();
  2527. idata5Sym->mSymKind = BeMCSymbolKind_SectionRef;
  2528. idata5Sym->mName = ".idata$5";
  2529. idata5Sym->mIdx = (int)coffObject.mSymbols.size() - 1;
  2530. BeMCSymbol* nullImportDescSym = coffObject.mSymbols.Alloc();
  2531. nullImportDescSym->mSymKind = BeMCSymbolKind_External;
  2532. nullImportDescSym->mName = nullImportDescriptorName;
  2533. BeMCSymbol* nullThunkDataSym = coffObject.mSymbols.Alloc();
  2534. nullThunkDataSym->mSymKind = BeMCSymbolKind_External;
  2535. nullThunkDataSym->mName = nullThunkDataName;
  2536. BeMCRelocation reloc;
  2537. reloc.mKind = BeMCRelocationKind_ADDR32NB;
  2538. reloc.mOffset = 0x0C;
  2539. //reloc.mSymTableIdx = idata6Sect->mSymbolIdx;
  2540. reloc.mSymTableIdx = nameSectSym->mIdx;
  2541. idata2Sect->mRelocs.push_back(reloc);
  2542. reloc.mKind = BeMCRelocationKind_ADDR32NB;
  2543. reloc.mOffset = 0x00;
  2544. reloc.mSymTableIdx = idata4Sym->mIdx;
  2545. idata2Sect->mRelocs.push_back(reloc);
  2546. reloc.mKind = BeMCRelocationKind_ADDR32NB;
  2547. reloc.mOffset = 0x10;
  2548. reloc.mSymTableIdx = idata5Sym->mIdx;
  2549. idata2Sect->mRelocs.push_back(reloc);
  2550. _CreateDebugSect(coffObject);
  2551. coffObject.Finish();
  2552. _LibSym* libSym = libSyms.Alloc();
  2553. libSym->mName = importDescriptorName;
  2554. libSym->mData = importDescriptorStream.GetPtr();
  2555. libSym->mDataSize = importDescriptorStream.GetSize();
  2556. }
  2557. DynMemStream nullImportDescriptorStream;
  2558. {
  2559. BeCOFFObject coffObject;
  2560. coffObject.mStream = &nullImportDescriptorStream;
  2561. coffObject.mTimestamp = mTimestamp;
  2562. // iData entry terminator
  2563. auto idata3Sect = coffObject.CreateSect(".idata$3", IMAGE_SCN_ALIGN_4BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE);
  2564. idata3Sect->mData.WriteZeros(0x14);
  2565. BeMCSymbol* coffSym = coffObject.mSymbols.Alloc();
  2566. coffSym->mSymKind = BeMCSymbolKind_External;
  2567. coffSym->mSectionNum = idata3Sect->mSectionIdx + 1;
  2568. coffSym->mName = nullImportDescriptorName;
  2569. coffSym->mIsStatic = false;
  2570. _CreateDebugSect(coffObject);
  2571. coffObject.Finish();
  2572. _LibSym* libSym = libSyms.Alloc();
  2573. libSym->mName = nullImportDescriptorName;
  2574. libSym->mData = nullImportDescriptorStream.GetPtr();
  2575. libSym->mDataSize = nullImportDescriptorStream.GetSize();
  2576. }
  2577. DynMemStream nullThunkDataStream;
  2578. {
  2579. BeCOFFObject coffObject;
  2580. coffObject.mStream = &nullThunkDataStream;
  2581. coffObject.mTimestamp = mTimestamp;
  2582. // iData entry terminator
  2583. auto idata5Sect = coffObject.CreateSect(".idata$5", IMAGE_SCN_ALIGN_8BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE);
  2584. idata5Sect->mData.WriteZeros(0x8);
  2585. auto idata4Sect = coffObject.CreateSect(".idata$4", IMAGE_SCN_ALIGN_8BYTES | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE);
  2586. idata4Sect->mData.WriteZeros(0x8);
  2587. BeMCSymbol* coffSym = coffObject.mSymbols.Alloc();
  2588. coffSym->mSymKind = BeMCSymbolKind_External;
  2589. coffSym->mSectionNum = idata5Sect->mSectionIdx + 1;
  2590. coffSym->mName = nullThunkDataName;
  2591. coffSym->mIsStatic = false;
  2592. _CreateDebugSect(coffObject);
  2593. coffObject.Finish();
  2594. _LibSym* libSym = libSyms.Alloc();
  2595. libSym->mName = nullThunkDataName;
  2596. libSym->mData = nullThunkDataStream.GetPtr();
  2597. libSym->mDataSize = nullThunkDataStream.GetSize();
  2598. }
  2599. for (auto& exportPair : mExports)
  2600. {
  2601. auto& blExport = exportPair.second;
  2602. if (blExport.mIsPrivate)
  2603. continue;
  2604. _LibSym* impSym = libSyms.Alloc();
  2605. impSym->mExport = &exportPair.second;
  2606. impSym->mName = "__imp_" + exportPair.first;
  2607. impSym->mExportName = exportPair.first;
  2608. impSym->mExport = &blExport;
  2609. impSym->mDataSize = (int)sizeof(PEImportObjectHeader) + (int)dllName.length() + 1 + (int)impSym->mExportName.length() + 1;
  2610. if (!blExport.mIsData)
  2611. {
  2612. _LibSym* refSym = libSyms.Alloc();
  2613. refSym->mName = exportPair.first;
  2614. refSym->mImp = impSym;
  2615. }
  2616. }
  2617. // Sort symbol names, required by Second Linker Member
  2618. std::sort(libSyms.begin(), libSyms.end(), [] (const _LibSym* lhs, const _LibSym* rhs)
  2619. {
  2620. return lhs->mName < rhs->mName;
  2621. });
  2622. int numExports = (int)libSyms.size();
  2623. int namesLen = 0;
  2624. DynMemStream syms0;
  2625. int ofsIdx = 0;
  2626. for (auto& libSym : libSyms)
  2627. {
  2628. namesLen += (int)libSym->mName.length() + 1;
  2629. if (libSym->mDataSize > 0)
  2630. libSym->mOfsIdx = ofsIdx++;
  2631. }
  2632. syms0.Write(numExports);
  2633. int headerSize = 8;
  2634. fs.WriteSNZ("!<arch>\n");
  2635. int expectedPos = headerSize;
  2636. int member0Size = sizeof(BlLibMemberHeader) + 4 + (numExports * 4) + (namesLen);
  2637. int member1Size = sizeof(BlLibMemberHeader) + 4 + (ofsIdx * 4) + 4 + (numExports * 2) + (namesLen);
  2638. int nameMemberSize = 0;
  2639. if (dllName.length() > 16)
  2640. {
  2641. nameMemberSize = sizeof(BlLibMemberHeader) + dllName.length() + 1;
  2642. }
  2643. int startExpOfs = expectedPos + BF_ALIGN(member0Size, 2) + BF_ALIGN(member1Size, 2) + BF_ALIGN(nameMemberSize, 2);
  2644. int curExpOfs = startExpOfs;
  2645. for (auto& libSym : libSyms)
  2646. {
  2647. if (libSym->mDataSize > 0)
  2648. {
  2649. int exportSize = (int)sizeof(BlLibMemberHeader) + libSym->mDataSize;
  2650. libSym->mDataPos = curExpOfs;
  2651. curExpOfs += BF_ALIGN(exportSize, 2);
  2652. }
  2653. }
  2654. BlLibMemberHeader member;
  2655. // First Linker Member (unordered symbol list)
  2656. member.Init();
  2657. FormatNZ(member.mName, "/");
  2658. FormatNZ(member.mDate, "%d", mTimestamp);
  2659. FormatNZ(member.mMode, "0");
  2660. FormatNZ(member.mSize, "%d", member0Size - (int)sizeof(BlLibMemberHeader));
  2661. fs.WriteT(member);
  2662. fs.Write(ToBigEndian(numExports));
  2663. for (auto libSym : libSyms)
  2664. {
  2665. if (libSym->mDataPos >= 0)
  2666. fs.Write(ToBigEndian(libSym->mDataPos));
  2667. else
  2668. fs.Write(ToBigEndian(libSym->mImp->mDataPos));
  2669. }
  2670. for (auto& libSym : libSyms)
  2671. {
  2672. fs.WriteSZ(libSym->mName);
  2673. }
  2674. expectedPos += member0Size;
  2675. BF_ASSERT(fs.GetPos() == expectedPos);
  2676. fs.Align(2);
  2677. expectedPos = fs.GetPos();
  2678. // Second Linker Member (ordered symbol map)
  2679. curExpOfs = startExpOfs;
  2680. member.Init();
  2681. FormatNZ(member.mName, "/");
  2682. FormatNZ(member.mDate, "%d", mTimestamp);
  2683. FormatNZ(member.mMode, "0");
  2684. FormatNZ(member.mSize, "%d", member1Size - (int)sizeof(BlLibMemberHeader));
  2685. fs.WriteT(member);
  2686. fs.Write(ofsIdx);
  2687. for (auto libSym : libSyms)
  2688. {
  2689. if (libSym->mDataSize <= 0)
  2690. continue;
  2691. int exportSize = (int)sizeof(BlLibMemberHeader) + libSym->mDataSize;
  2692. fs.Write(curExpOfs);
  2693. curExpOfs += BF_ALIGN(exportSize, 2);
  2694. }
  2695. fs.Write(numExports);
  2696. for (auto libSym : libSyms)
  2697. {
  2698. if (libSym->mOfsIdx >= 0)
  2699. fs.Write((int16)(libSym->mOfsIdx + 1));
  2700. else
  2701. {
  2702. BF_ASSERT(libSym->mImp != NULL);
  2703. fs.Write((int16)(libSym->mImp->mOfsIdx + 1));
  2704. }
  2705. }
  2706. for (auto libSym : libSyms)
  2707. {
  2708. fs.WriteSZ(libSym->mName);
  2709. }
  2710. expectedPos += member1Size;
  2711. BF_ASSERT(fs.GetPos() == expectedPos);
  2712. fs.Align(2);
  2713. expectedPos = fs.GetPos();
  2714. if (nameMemberSize != 0)
  2715. {
  2716. member.Init();
  2717. FormatNZ(member.mName, "//");
  2718. FormatNZ(member.mDate, "%d", mTimestamp);
  2719. FormatNZ(member.mMode, "0");
  2720. FormatNZ(member.mSize, "%d", nameMemberSize - (int)sizeof(BlLibMemberHeader));
  2721. fs.WriteT(member);
  2722. fs.WriteSZ(dllName);
  2723. fs.Align(2);
  2724. }
  2725. // Create import entries
  2726. curExpOfs = startExpOfs;
  2727. for (auto libSym : libSyms)
  2728. {
  2729. if (libSym->mDataSize <= 0)
  2730. continue;
  2731. BF_ASSERT(fs.GetPos() == curExpOfs);
  2732. int exportSize = (int)sizeof(BlLibMemberHeader) + libSym->mDataSize;
  2733. member.Init();
  2734. if (nameMemberSize != 0)
  2735. FormatNZ(member.mName, "/0"); // Reference name in string table
  2736. else
  2737. FormatNZ(member.mName, "%s/", dllName.c_str());
  2738. FormatNZ(member.mDate, "%d", mTimestamp);
  2739. FormatNZ(member.mMode, "0");
  2740. FormatNZ(member.mSize, "%d", exportSize - (int)sizeof(BlLibMemberHeader));
  2741. fs.WriteT(member);
  2742. if (libSym->mData != NULL)
  2743. {
  2744. fs.Write(libSym->mData, libSym->mDataSize);
  2745. }
  2746. else
  2747. {
  2748. BF_ASSERT(libSym->mExport != NULL);
  2749. PEImportObjectHeader importHdr = { 0 };
  2750. importHdr.mSig1 = 0;
  2751. importHdr.mSig2 = IMPORT_OBJECT_HDR_SIG2;
  2752. importHdr.mVersion = 0;
  2753. importHdr.mMachine = PE_MACHINE_X64;
  2754. importHdr.mTimeDateStamp = mTimestamp;
  2755. importHdr.mDataSize = (int)libSym->mExportName.length() + 1 + (int)dllName.length() + 1;
  2756. importHdr.mHint = libSym->mExport->mOrdinal;
  2757. if (!libSym->mExport->mOrdinalSpecified)
  2758. importHdr.mType |= IMPORT_OBJECT_NAME << 2;
  2759. if (libSym->mExport->mIsData)
  2760. importHdr.mType |= IMPORT_OBJECT_DATA;
  2761. fs.WriteT(importHdr);
  2762. fs.WriteSZ(libSym->mExportName);
  2763. fs.WriteSZ(dllName);
  2764. }
  2765. if ((exportSize % 2) == 1)
  2766. fs.Write((uint8)0xA);
  2767. curExpOfs += BF_ALIGN(exportSize, 2);
  2768. }
  2769. }
  2770. void BlContext::PrintStats()
  2771. {
  2772. OutputDebugStrF("Symbols: %d\n", mSymTable.mMap.size());
  2773. OutputDebugStrF("Obj files: %d\n", mNumObjFiles);
  2774. OutputDebugStrF("Libs: %d\n", mNumLibs);
  2775. OutputDebugStrF("Imported objs: %d\n", mNumImportedObjs);
  2776. OutputDebugStrF("Weak symbols: %d\n", mNumWeakSymbols);
  2777. OutputDebugStrF("Syms not found: %d\n", mSymNotFounds.size());
  2778. OutputDebugStrF("Import Groups: %d\n", mImportGroups.size());
  2779. if (mCodeView != NULL)
  2780. {
  2781. OutputDebugStrF("PDB TPI Types: %d\n", mCodeView->mTPI.mCurTagId - 0x1000);
  2782. OutputDebugStrF("PDB IPI Types: %d\n", mCodeView->mIPI.mCurTagId - 0x1000);
  2783. OutputDebugStrF("PDB Globals: %d\n", mCodeView->mGlobals.mNumEntries);
  2784. OutputDebugStrF("DbgSymSectsFound: %d\n", mDbgSymSectsFound);
  2785. OutputDebugStrF("DbgSymSectsUsed: %d\n", mDbgSymSectsUsed);
  2786. OutputDebugStrF("Stat_ParseTagFuncs: %d\n", mCodeView->mStat_ParseTagFuncs);
  2787. OutputDebugStrF("Stat_TypeMapInserts: %d\n", mCodeView->mStat_TypeMapInserts);
  2788. }
  2789. }
  2790. void BlContext::Link()
  2791. {
  2792. //smap.insert()
  2793. //BeefyDbg64::TestPDB("C:\\temp\\out.pdbf");
  2794. //BeefyDbg64::TestPDB("C:\\proj\\TestCPP\\x64\\Debug\\TestCPP.pdb");
  2795. //BeefyDbg64::TestPDB("C:\\llvm-3.9.0\\bin64\\Debug\\bin\\Clang.pdb");
  2796. //
  2797. BL_AUTOPERF("BlContext::Link");
  2798. BF_ASSERT(mCodeView == NULL);
  2799. /*mTextSeg = CreateSegment(".text", IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE, 1);
  2800. mTextSeg->mOutSectionIdx = 0;
  2801. mRDataSeg = CreateSegment(".rdata", IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ, 1);
  2802. mRDataSeg->mOutSectionIdx = 1;
  2803. mDataSeg = CreateSegment(".data", IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, 1);
  2804. mDataSeg->mOutSectionIdx = 2;
  2805. // We add the BSS data to the end of .data
  2806. //mBSSSeg = CreateSegment(".data$\xFF", IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, 1);
  2807. // We used to name .BSS as ".data$\xFF" to make sure it appended to .data, but now we keep those segments separate so we can
  2808. // parallelize the COFF generation*/
  2809. mBSSSeg = CreateSegment(".bss", IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE, 1);
  2810. //mBSSSeg->mOutSectionIdx = 3;
  2811. //mNumFixedSegs = 4;
  2812. if ((mImageBase & 0xFFFF) != 0)
  2813. Fail(StrFormat("Image base, specified as 0x%p, must be a multiple of 64k (0x10000)", mImageBase));
  2814. // Make sure this is set to 'false' unless debugging
  2815. bool deferThreads = false;
  2816. if (mDebugKind != 0)
  2817. {
  2818. mCodeView = new BlCodeView();
  2819. mCodeView->mContext = this;
  2820. if (!deferThreads)
  2821. mCodeView->StartWorkThreads();
  2822. }
  2823. if (mOutName.empty())
  2824. {
  2825. char cwd[MAX_PATH];
  2826. _getcwd(cwd, MAX_PATH);
  2827. mOutName = String(cwd) + "\\" + GetFileName(cwd);
  2828. if (mIsDLL)
  2829. mOutName += ".dll";
  2830. else
  2831. mOutName += ".exe";
  2832. }
  2833. // Create PDB
  2834. if (mCodeView != NULL)
  2835. {
  2836. if (mPDBPath.empty())
  2837. {
  2838. String pdbFileName = mOutName;
  2839. pdbFileName.RemoveToEnd(pdbFileName.length() - 4);
  2840. pdbFileName += ".pdb";
  2841. mPDBPath = pdbFileName;
  2842. }
  2843. // Use .pdbf for PDB file
  2844. // The rationale is to allow alternating between the MS linker and the Beef linker. The MS linker
  2845. // currently chokes while trying to update PDBs built by the Beef linker
  2846. mPDBPath += "f";
  2847. if (!mCodeView->Create(mPDBPath))
  2848. {
  2849. Fail(StrFormat("Failed to create \"%s\"", mPDBPath.c_str()));
  2850. return;
  2851. }
  2852. }
  2853. auto imageBaseSym = mSymTable.Add("__ImageBase");
  2854. //TODO: Set up ImageBase properly
  2855. imageBaseSym->mObjectDataIdx = -1;
  2856. imageBaseSym->mKind = BlSymKind_ImageBaseRel;
  2857. imageBaseSym->mSegmentOffset = 0;
  2858. // We do not support /guard:cf (control flow protection) yet.
  2859. // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
  2860. AddAbsoluteSym("__guard_fids_table", 0);
  2861. AddAbsoluteSym("__guard_fids_count", 0);
  2862. AddAbsoluteSym("__guard_flags", 0x100);
  2863. BlSymbol* entrySym = NULL;
  2864. BlSymbol* configSym = NULL;
  2865. int workLoopIdx = 0;
  2866. String entryPointName;
  2867. if (!mEntryPoint.empty())
  2868. entryPointName = mEntryPoint;
  2869. else if (mIsDLL)
  2870. entryPointName = "_DllMainCRTStartup";
  2871. else if (mPeSubsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
  2872. entryPointName = "mainCRTStartup";
  2873. else if (mPeSubsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
  2874. entryPointName = "WinMainCRTStartup";
  2875. while (!mObjectDataWorkQueue.empty())
  2876. {
  2877. LoadFiles();
  2878. ResolveRelocs();
  2879. for (auto& forcedSym : mForcedSyms)
  2880. ResolveSym(forcedSym.c_str());
  2881. mForcedSyms.clear();
  2882. if (workLoopIdx == 0)
  2883. {
  2884. if (!entryPointName.empty())
  2885. entrySym = ResolveSym(entryPointName.c_str());
  2886. configSym = ResolveSym("_load_config_used");
  2887. }
  2888. if (mObjectDataWorkQueue.empty())
  2889. {
  2890. for (auto& symNotFound : mSymNotFounds)
  2891. {
  2892. if ((symNotFound.mSym->mKind == BlSymKind_LibSymbolRef) || (symNotFound.mSym->mKind == BlSymKind_LibSymbolGroupRef))
  2893. ProcessSymbol(symNotFound.mSym);
  2894. }
  2895. }
  2896. workLoopIdx++;
  2897. }
  2898. // Check for any unresolved symbols
  2899. for (auto& symNotFound : mSymNotFounds)
  2900. {
  2901. auto sym = symNotFound.mSym;
  2902. if (sym->mKind != BlSymKind_Undefined)
  2903. continue;
  2904. int curOffset = 0;
  2905. int objectDataIdx = -1;
  2906. if (symNotFound.mSegmentIdx != -1)
  2907. {
  2908. auto seg = mSegments[symNotFound.mSegmentIdx];
  2909. // Find the chunk that this symbol is referenced from
  2910. for (auto& chunk : seg->mChunks)
  2911. {
  2912. curOffset += chunk.mAlignPad;
  2913. BF_ASSERT(curOffset == chunk.mOffset);
  2914. if ((symNotFound.mOutOffset >= curOffset) && (symNotFound.mOutOffset < curOffset + chunk.mSize))
  2915. {
  2916. objectDataIdx = chunk.mObjectDataIdx;
  2917. break;
  2918. }
  2919. curOffset += chunk.mSize;
  2920. }
  2921. }
  2922. if (objectDataIdx != -1)
  2923. {
  2924. Fail(StrFormat("Unable to find symbol %s referenced from %s", GetSymDisp(sym->mName).c_str(), ObjectDataIdxToString(objectDataIdx).c_str()));
  2925. }
  2926. else
  2927. {
  2928. Fail(StrFormat("Unable to find symbol %s", GetSymDisp(sym->mName).c_str()));
  2929. }
  2930. }
  2931. if (mFailed)
  2932. return;
  2933. mIDataSeg = CreateIData();
  2934. BlSegment* thunkSeg = CreateThunkData();
  2935. BlSegment* cvInfoSeg = CreateCvInfoData();
  2936. BlSegment* debugDirSeg = NULL;
  2937. if (mCodeView != NULL)
  2938. debugDirSeg = CreateDebugDirData();
  2939. BlSegment* resSeg = CreateResData();
  2940. BlSegment* exportSeg = CreateExportData();
  2941. PlaceSections();
  2942. PopulateIData(mIDataSeg);
  2943. if (thunkSeg != NULL)
  2944. PopulateThunkData(thunkSeg, mIDataSeg);
  2945. if (cvInfoSeg != NULL)
  2946. PopulateCvInfoData(cvInfoSeg);
  2947. PopulateDebugDirData(debugDirSeg, cvInfoSeg);
  2948. PopulateResData(resSeg);
  2949. if (exportSeg != NULL)
  2950. PopulateExportData(exportSeg);
  2951. if (mFailed)
  2952. return;
  2953. // The .reloc table is a special case because we don't know its size until after we process
  2954. // the relocations of all the other sections
  2955. auto lastOutSection = mOutSections.back();
  2956. auto relocOutSection = mOutSections.Alloc();
  2957. relocOutSection->mIdx = (int)mOutSections.size() - 1;
  2958. relocOutSection->mName = ".reloc";
  2959. relocOutSection->mCharacteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA;
  2960. relocOutSection->mRVA = lastOutSection->mRVA + lastOutSection->mVirtualSize;
  2961. relocOutSection->mRVA = (relocOutSection->mRVA + (0x1000 - 1)) & ~(0x1000 - 1);
  2962. relocOutSection->mRawDataPos = lastOutSection->mRawDataPos + lastOutSection->mRawSize;
  2963. relocOutSection->mRawSize = 0;
  2964. relocOutSection->mVirtualSize = 0;
  2965. // Finish relocs. Primary reloc loop.
  2966. {
  2967. BL_AUTOPERF("BlContext::Link Finish Relocs");
  2968. for (auto sect : mSegments)
  2969. {
  2970. for (auto& reloc : sect->mRelocs)
  2971. {
  2972. int sectionIdx = -1;
  2973. int sectionOffset = 0;
  2974. int64 outRVA = sect->mRVA + reloc.mOutOffset;
  2975. if ((reloc.mFlags & BeRelocFlags_Sym) != 0)
  2976. {
  2977. auto sym = reloc.mSym;
  2978. if (sym->mKind == BlSymKind_WeakSymbol)
  2979. {
  2980. sym = mSymTable.Add(mRemapStrs[sym->mParam].c_str());
  2981. if (sym->mKind == BlSymKind_Undefined)
  2982. {
  2983. Fail(StrFormat("Unable to resolve weak symbol %s", GetSymDisp(sym->mName).c_str()));
  2984. continue;
  2985. }
  2986. }
  2987. reloc.mFlags = (BeRelocFlags)(reloc.mFlags & ~BeRelocFlags_Sym | BeRelocFlags_Loc);
  2988. if (sym->mKind == BlSymKind_Import)
  2989. {
  2990. // It's a thunk
  2991. reloc.mSegmentIdx = thunkSeg->mSegmentIdx;
  2992. auto lookup = mImportLookups[sym->mParam];
  2993. reloc.mSegmentOffset = lookup->mThunkIdx * 6;
  2994. continue;
  2995. }
  2996. if (sym->mKind == BlSymKind_ImportImp)
  2997. {
  2998. BF_ASSERT((reloc.mFlags & BeRelocFlags_Func) == 0);
  2999. reloc.mSegmentIdx = mIDataSeg->mSegmentIdx;
  3000. auto lookup = mImportLookups[sym->mParam];
  3001. reloc.mSegmentOffset = lookup->mIDataIdx * 8;
  3002. continue;
  3003. }
  3004. else if ((sym->mKind == BlSymKind_ImageBaseRel) || (sym->mKind == BlSymKind_Absolute))
  3005. {
  3006. // Fine
  3007. }
  3008. else if (sym->mKind < 0)
  3009. {
  3010. AssertFailed();
  3011. Fail(StrFormat("Unable to find symbol %s", GetSymDisp(sym->mName).c_str()));
  3012. }
  3013. reloc.mSegmentIdx = sym->mSegmentIdx;
  3014. reloc.mSegmentOffset = sym->mSegmentOffset;
  3015. }
  3016. else
  3017. {
  3018. sectionIdx = reloc.mSegmentIdx;
  3019. sectionOffset = reloc.mSegmentOffset;
  3020. }
  3021. }
  3022. }
  3023. }
  3024. SysFileStream fs;
  3025. //if (!fs.Open(mOutName, GENERIC_WRITE | GENERIC_READ))
  3026. if (!fs.Open(mOutName, BfpFileCreateKind_CreateAlways, (BfpFileCreateFlags)(BfpFileCreateFlag_Read | BfpFileCreateFlag_Write)))
  3027. {
  3028. Fail(StrFormat("Unable to create file \"%s\"", mOutName.c_str()));
  3029. return;
  3030. }
  3031. PEHeader hdr = { 0 };
  3032. hdr.e_magic = PE_DOS_SIGNATURE;
  3033. hdr.e_cblp = 0x90;
  3034. hdr.e_cp = 0x03;
  3035. hdr.e_cparhdr = 4;
  3036. hdr.e_maxalloc = 0xFFFF;
  3037. hdr.e_sp = 0xB8;
  3038. hdr.e_lfarlc = 0x40;
  3039. hdr.e_lfanew = 0xF0;
  3040. PE_NTHeaders64 ntHdr = { 0 };
  3041. ntHdr.mSignature = PE_NT_SIGNATURE;
  3042. ntHdr.mFileHeader.mMachine = PE_MACHINE_X64;
  3043. ntHdr.mFileHeader.mNumberOfSections = (int)mOutSections.size();
  3044. ntHdr.mFileHeader.mTimeDateStamp = mTimestamp;
  3045. ntHdr.mFileHeader.mSizeOfOptionalHeader = 0xF0;
  3046. ntHdr.mFileHeader.mCharacteristics = IMAGE_FILE_LARGE_ADDRESS_AWARE | IMAGE_FILE_EXECUTABLE_IMAGE;
  3047. if (mIsDLL)
  3048. ntHdr.mFileHeader.mCharacteristics |= IMAGE_FILE_DLL;
  3049. if (mHasFixedBase)
  3050. ntHdr.mFileHeader.mCharacteristics |= IMAGE_FILE_RELOCS_STRIPPED;
  3051. ntHdr.mOptionalHeader.mMagic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
  3052. ntHdr.mOptionalHeader.mMajorLinkerVersion = 0xE;
  3053. // Export Directory
  3054. if (exportSeg != NULL)
  3055. {
  3056. ntHdr.mOptionalHeader.mDataDirectory[0].mVirtualAddress = exportSeg->mRVA;
  3057. ntHdr.mOptionalHeader.mDataDirectory[0].mSize = exportSeg->mCurSize;
  3058. }
  3059. auto tlsUsedSym = mSymTable.Add("_tls_used");
  3060. if (tlsUsedSym->mKind != BlSymKind_Undefined)
  3061. {
  3062. // TLS Directory
  3063. ntHdr.mOptionalHeader.mDataDirectory[9].mVirtualAddress = (uint32)GetSymAddr(tlsUsedSym);
  3064. ntHdr.mOptionalHeader.mDataDirectory[9].mSize = 0x28;
  3065. }
  3066. // Debug Directory
  3067. ntHdr.mOptionalHeader.mDataDirectory[6].mVirtualAddress = debugDirSeg->mRVA;
  3068. ntHdr.mOptionalHeader.mDataDirectory[6].mSize = debugDirSeg->mCurSize;
  3069. // Load Config Directory
  3070. ntHdr.mOptionalHeader.mDataDirectory[10].mVirtualAddress = (uint32)GetSymAddr(configSym);
  3071. ntHdr.mOptionalHeader.mDataDirectory[10].mSize = 0x94;
  3072. BlOutSection* pdataSection = NULL;
  3073. int imageSize = 0;
  3074. for (auto outSection : mOutSections)
  3075. {
  3076. if ((outSection->mCharacteristics & IMAGE_SCN_MEM_EXECUTE) != 0)
  3077. ntHdr.mOptionalHeader.mSizeOfCode += outSection->mVirtualSize;
  3078. if ((outSection->mCharacteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) != 0)
  3079. ntHdr.mOptionalHeader.mSizeOfInitializedData += outSection->mVirtualSize;
  3080. if ((outSection->mCharacteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0)
  3081. ntHdr.mOptionalHeader.mSizeOfUninitializedData += outSection->mVirtualSize;
  3082. int dirIdx = -1;
  3083. if (outSection->mName == ".pdata")
  3084. {
  3085. pdataSection = outSection;
  3086. dirIdx = 3; // Exception Directory
  3087. }
  3088. else if (outSection->mName == ".rsrc")
  3089. {
  3090. dirIdx = 2; // Resource Directory
  3091. }
  3092. else if (outSection->mName == ".idata")
  3093. {
  3094. dirIdx = 1; // Import Directory
  3095. int importLookupTableSize = ((int)mImportLookups.size() + (int)mImportFiles.size()) * 8;
  3096. ntHdr.mOptionalHeader.mDataDirectory[dirIdx].mVirtualAddress = outSection->mRVA + importLookupTableSize;
  3097. ntHdr.mOptionalHeader.mDataDirectory[dirIdx].mSize = outSection->mVirtualSize;
  3098. dirIdx = 12; // Import Address Table
  3099. }
  3100. if (dirIdx != -1)
  3101. {
  3102. ntHdr.mOptionalHeader.mDataDirectory[dirIdx].mVirtualAddress = outSection->mRVA;
  3103. ntHdr.mOptionalHeader.mDataDirectory[dirIdx].mSize = outSection->mVirtualSize;
  3104. }
  3105. //TODO: Set up data directories
  3106. imageSize = (outSection->mRVA + outSection->mVirtualSize + (0x1000 - 1)) & ~(0x1000 - 1);
  3107. }
  3108. if (entrySym != NULL)
  3109. {
  3110. auto entrySection = mSegments[entrySym->mSegmentIdx];
  3111. ntHdr.mOptionalHeader.mAddressOfEntryPoint = entrySection->mRVA + entrySym->mSegmentOffset;
  3112. }
  3113. ntHdr.mOptionalHeader.mBaseOfCode = 0x1000;
  3114. ntHdr.mOptionalHeader.mImageBase = mImageBase;
  3115. ntHdr.mOptionalHeader.mSectionAlignment = 0x1000;
  3116. ntHdr.mOptionalHeader.mFileAlignment = 0x200;
  3117. ntHdr.mOptionalHeader.mMajorOperatingSystemVersion = 6;
  3118. ntHdr.mOptionalHeader.mMinorOperatingSystemVersion = 0;
  3119. ntHdr.mOptionalHeader.mMinorImageVersion = 0;
  3120. ntHdr.mOptionalHeader.mMajorImageVersion = 0;
  3121. ntHdr.mOptionalHeader.mMajorSubsystemVersion = 6;
  3122. ntHdr.mOptionalHeader.mMinorSubsystemVersion = 0;
  3123. ntHdr.mOptionalHeader.mSizeOfImage = imageSize;
  3124. ntHdr.mOptionalHeader.mSizeOfHeaders = 0x400;
  3125. if (mIsDLL)
  3126. ntHdr.mOptionalHeader.mSubsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI;
  3127. else
  3128. ntHdr.mOptionalHeader.mSubsystem = mPeSubsystem;
  3129. ntHdr.mOptionalHeader.mDllCharacteristics = 0;
  3130. if (mIsTerminalServerAware)
  3131. ntHdr.mOptionalHeader.mDllCharacteristics |= IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE;
  3132. if (mIsNXCompat)
  3133. ntHdr.mOptionalHeader.mDllCharacteristics |= IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
  3134. if (mHasDynamicBase)
  3135. ntHdr.mOptionalHeader.mDllCharacteristics |= IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE;
  3136. if (mHighEntropyVA)
  3137. ntHdr.mOptionalHeader.mDllCharacteristics |= IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA;
  3138. ntHdr.mOptionalHeader.mSizeOfStackReserve = mStackReserve;
  3139. ntHdr.mOptionalHeader.mSizeOfStackCommit = mStackCommit;
  3140. ntHdr.mOptionalHeader.mSizeOfHeapReserve = mHeapReserve;
  3141. ntHdr.mOptionalHeader.mSizeOfHeapCommit = mHeapCommit;
  3142. ntHdr.mOptionalHeader.mNumberOfRvaAndSizes = 0x10;
  3143. fs.WriteT(hdr);
  3144. uint8 dosProgram[0xB0] = {
  3145. 0x0E, 0x1F, 0xBA, 0x0E, 0x00, 0xB4, 0x09, 0xCD, 0x21, 0xB8, 0x01, 0x4C, 0xCD, 0x21, 0x54, 0x68,
  3146. 0x69, 0x73, 0x20, 0x70, 0x72, 0x6F, 0x67, 0x72, 0x61, 0x6D, 0x20, 0x63, 0x61, 0x6E, 0x6E, 0x6F,
  3147. 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6E, 0x20, 0x69, 0x6E, 0x20, 0x44, 0x4F, 0x53, 0x20,
  3148. 0x6D, 0x6F, 0x64, 0x65, 0x2E, 0x0D, 0x0D, 0x0A, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  3149. 0x87, 0x9B, 0xD3, 0xE0, 0xC3, 0xFA, 0xBD, 0xB3, 0xC3, 0xFA, 0xBD, 0xB3, 0xC3, 0xFA, 0xBD, 0xB3,
  3150. 0x77, 0x66, 0x52, 0xB3, 0xC1, 0xFA, 0xBD, 0xB3, 0xF8, 0xA4, 0xBC, 0xB2, 0xC0, 0xFA, 0xBD, 0xB3,
  3151. 0xF8, 0xA4, 0xBE, 0xB2, 0xC1, 0xFA, 0xBD, 0xB3, 0xF8, 0xA4, 0xB8, 0xB2, 0xD2, 0xFA, 0xBD, 0xB3,
  3152. 0xF8, 0xA4, 0xB9, 0xB2, 0xCF, 0xFA, 0xBD, 0xB3, 0x1E, 0x05, 0x76, 0xB3, 0xC1, 0xFA, 0xBD, 0xB3,
  3153. 0xC3, 0xFA, 0xBC, 0xB3, 0xEF, 0xFA, 0xBD, 0xB3, 0x54, 0xA4, 0xB8, 0xB2, 0xC2, 0xFA, 0xBD, 0xB3,
  3154. 0x51, 0xA4, 0x42, 0xB3, 0xC2, 0xFA, 0xBD, 0xB3, 0x54, 0xA4, 0xBF, 0xB2, 0xC2, 0xFA, 0xBD, 0xB3,
  3155. 0x52, 0x69, 0x63, 0x68, 0xC3, 0xFA, 0xBD, 0xB3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  3156. };
  3157. fs.WriteT(dosProgram);
  3158. int ntHdrFilePos = fs.GetPos();
  3159. fs.WriteT(ntHdr);
  3160. int numSections = (int)mOutSections.size();
  3161. int rawDataPos = (fs.GetPos() + (numSections * sizeof(PESectionHeader)) + (512 - 1)) & ~(512 - 1);
  3162. int rawDataStart = rawDataPos;
  3163. int32 sectStartPos = fs.GetPos();
  3164. // This doesn't include reloc data, it's just an estimate for optimization
  3165. int wantSize = mOutSections.back()->mRawDataPos + mOutSections.back()->mRawSize;
  3166. fs.SetSizeFast(wantSize);
  3167. for (auto outSection : mOutSections)
  3168. {
  3169. PESectionHeader sectHdr = { 0 };
  3170. if (outSection->mName.length() <= 8)
  3171. {
  3172. memcpy(sectHdr.mName, outSection->mName.c_str(), (int)outSection->mName.length());
  3173. }
  3174. else
  3175. NotImpl();
  3176. BF_ASSERT(rawDataPos == outSection->mRawDataPos);
  3177. sectHdr.mVirtualAddress = outSection->mRVA;
  3178. sectHdr.mVirtualSize = outSection->mVirtualSize;
  3179. sectHdr.mSizeOfRawData = outSection->mRawSize;
  3180. sectHdr.mPointerToRawData = rawDataPos;
  3181. sectHdr.mCharacteristics = outSection->mCharacteristics;
  3182. rawDataPos += outSection->mRawSize;
  3183. fs.WriteT(sectHdr);
  3184. if (mCodeView != NULL)
  3185. mCodeView->mSectionHeaders.WriteT(sectHdr);
  3186. }
  3187. fs.Align(512);
  3188. BF_ASSERT(fs.GetPos() == rawDataStart);
  3189. if (mCodeView != NULL)
  3190. {
  3191. //BL_AUTOPERF("BlContext::Link CodeViewFinish");
  3192. //mCodeView->Finish();
  3193. }
  3194. int itrIdx = 0;
  3195. // Actually write section data
  3196. for (auto outSection : mOutSections)
  3197. {
  3198. BL_AUTOPERF("BlContext::Link Write OutSections");
  3199. int startPos = fs.GetPos();
  3200. if (outSection == relocOutSection)
  3201. {
  3202. outSection->mVirtualSize = mPeRelocs.mData.GetSize();
  3203. outSection->mRawSize = (outSection->mVirtualSize + (512 - 1)) & ~(512 - 1);
  3204. mPeRelocs.mData.Read(fs, mPeRelocs.mData.GetSize());
  3205. // Reloc Directory
  3206. ntHdr.mOptionalHeader.mDataDirectory[5].mVirtualAddress = outSection->mRVA;
  3207. ntHdr.mOptionalHeader.mDataDirectory[5].mSize = outSection->mVirtualSize;
  3208. //sectHdr.mVirtualAddress = ;
  3209. imageSize = (outSection->mRVA + outSection->mVirtualSize + (0x1000 - 1)) & ~(0x1000 - 1);
  3210. ntHdr.mOptionalHeader.mSizeOfImage = imageSize;
  3211. int endPos = fs.GetPos();
  3212. fs.SetPos(ntHdrFilePos);
  3213. fs.WriteT(ntHdr);
  3214. fs.SetPos(sectStartPos + ((int)mOutSections.size() - 1)*sizeof(PESectionHeader));
  3215. PESectionHeader sectHdr = { 0 };
  3216. strcpy(sectHdr.mName, ".reloc");
  3217. sectHdr.mVirtualAddress = outSection->mRVA;
  3218. sectHdr.mVirtualSize = outSection->mVirtualSize;
  3219. sectHdr.mSizeOfRawData = outSection->mRawSize;
  3220. sectHdr.mPointerToRawData = outSection->mRawDataPos;
  3221. sectHdr.mCharacteristics = outSection->mCharacteristics;
  3222. fs.WriteT(sectHdr);
  3223. fs.SetPos(endPos);
  3224. }
  3225. else if (outSection == pdataSection)
  3226. {
  3227. // We need to sort the pdata addresses, but we can sort until after we apply all the relocs which
  3228. // doesn't occur until WriteOutSection
  3229. struct _PDataEntry
  3230. {
  3231. uint32 mStartAddr;
  3232. uint32 mEndAddr;
  3233. uint32 mUnwindData;
  3234. };
  3235. std::vector<_PDataEntry> pdataVector;
  3236. pdataVector.resize(outSection->mVirtualSize / 12);
  3237. MemStream memStream((void*)&pdataVector[0], outSection->mVirtualSize, false);
  3238. WriteOutSection(outSection, &memStream);
  3239. std::sort(pdataVector.begin(), pdataVector.end(), [] (const _PDataEntry& lhs, const _PDataEntry& rhs)
  3240. {
  3241. return lhs.mStartAddr < rhs.mStartAddr;
  3242. });
  3243. fs.Write((void*)&pdataVector[0], outSection->mVirtualSize);
  3244. }
  3245. else
  3246. {
  3247. CachedDataStream cachedStream(&fs);
  3248. WriteOutSection(outSection, &cachedStream);
  3249. }
  3250. fs.Align(512);
  3251. int actualLen = fs.GetPos() - startPos;
  3252. BF_ASSERT(actualLen == outSection->mRawSize);
  3253. }
  3254. if (mCodeView != NULL)
  3255. {
  3256. if (deferThreads)
  3257. {
  3258. bool noThreads = false;
  3259. if (noThreads)
  3260. {
  3261. //
  3262. {
  3263. BL_AUTOPERF("Run TypeWorkThread");
  3264. mCodeView->mTypeWorkThread.mTypesDone = true;
  3265. mCodeView->mTypeWorkThread.Run();
  3266. }
  3267. //
  3268. {
  3269. BL_AUTOPERF("Run ModuleWorkThread");
  3270. mCodeView->mModuleWorkThread.mModulesDone = true;
  3271. mCodeView->mModuleWorkThread.Run();
  3272. }
  3273. }
  3274. else
  3275. {
  3276. mCodeView->StartWorkThreads();
  3277. }
  3278. }
  3279. BL_AUTOPERF("BfContext::Link StopWorkingThread");
  3280. mCodeView->Finish();
  3281. mCodeView->StopWorkThreads();
  3282. }
  3283. if (mIsDLL)
  3284. {
  3285. BL_AUTOPERF("BfContext::Link WriteDLLLib");
  3286. if (mImpLibName.empty())
  3287. {
  3288. String libFileName = mOutName;
  3289. libFileName.RemoveToEnd(libFileName.length() - 4);
  3290. libFileName += ".lib";
  3291. mImpLibName = libFileName;
  3292. }
  3293. WriteDLLLib(mImpLibName);
  3294. }
  3295. #ifdef BL_PERFTIME
  3296. PrintStats();
  3297. #endif
  3298. /*if (mCodeView != NULL)
  3299. BeefyDbg64::TestPDB(mCodeView->mFileName);*/
  3300. }
  3301. //////////////////////////////////////////////////////////////////////////
  3302. BF_EXPORT BlContext* BF_CALLTYPE BlContext_Create()
  3303. {
  3304. return new BlContext();
  3305. }
  3306. BF_EXPORT void BF_CALLTYPE BlContext_Delete(BlContext* blContext)
  3307. {
  3308. BL_AUTOPERF("BlContext_Delete");
  3309. delete blContext;
  3310. }
  3311. BF_EXPORT void BF_CALLTYPE BlContext_Init(BlContext* blContext, bool is64Bit, bool isDebug)
  3312. {
  3313. blContext->Init(is64Bit, isDebug);
  3314. }
  3315. BF_EXPORT void BF_CALLTYPE BlContext_AddSearchPath(BlContext* blContext, const char* directory)
  3316. {
  3317. blContext->AddSearchPath(directory);
  3318. }
  3319. BF_EXPORT bool BF_CALLTYPE BlContext_AddFile(BlContext* blContext, const char* fileName)
  3320. {
  3321. return blContext->AddFile(fileName, BlObjectDataKind_SpecifiedObj);
  3322. }
  3323. BF_EXPORT bool BF_CALLTYPE BlContext_Link(BlContext* blContext)
  3324. {
  3325. blContext->Link();
  3326. return !blContext->mFailed;
  3327. }
  3328. BF_EXPORT void BF_CALLTYPE BlContext_SetOutName(BlContext* blContext, const char* outName)
  3329. {
  3330. blContext->mOutName = outName;
  3331. }
  3332. BF_EXPORT void BF_CALLTYPE BlContext_SetEntryPoint(BlContext* blContext, const char* entryPoint)
  3333. {
  3334. blContext->mEntryPoint = entryPoint;
  3335. }
  3336. BF_EXPORT void BF_CALLTYPE BlContext_SetImpLib(BlContext* blContext, const char* impLibName)
  3337. {
  3338. blContext->mImpLibName = impLibName;
  3339. }
  3340. BF_EXPORT void BF_CALLTYPE BlContext_SetDebug(BlContext* blContext, int debugMode)
  3341. {
  3342. blContext->mDebugKind = debugMode;
  3343. }
  3344. BF_EXPORT void BF_CALLTYPE BlContext_SetPDBName(BlContext* blContext, const char* pdbPath)
  3345. {
  3346. blContext->mPDBPath = pdbPath;
  3347. }
  3348. BF_EXPORT void BF_CALLTYPE BlContext_SetIsDLL(BlContext* blContext)
  3349. {
  3350. blContext->mIsDLL = true;
  3351. }
  3352. BF_EXPORT void BF_CALLTYPE BlContext_SetVerbose(BlContext* blContext, bool enabled)
  3353. {
  3354. blContext->mVerbose = true;
  3355. }
  3356. BF_EXPORT void BF_CALLTYPE BlContext_SetNoDefaultLib(BlContext* blContext, bool enabled)
  3357. {
  3358. blContext->mNoDefaultLib = enabled;
  3359. }
  3360. BF_EXPORT void BF_CALLTYPE BlContext_AddNoDefaultLib(BlContext* blContext, const char* name)
  3361. {
  3362. String libName = name;
  3363. FixLibName(libName);
  3364. String libCanonName = FixPathAndCase(libName);
  3365. blContext->mNoDefaultLibs.insert(libCanonName);
  3366. }
  3367. BF_EXPORT void BF_CALLTYPE BlContext_AddDefaultLib(BlContext* blContext, const char* name)
  3368. {
  3369. blContext->mDefaultLibs.push_back(name);
  3370. }
  3371. BF_EXPORT void BF_CALLTYPE BlContext_SetImageBase(BlContext* blContext, int64 base)
  3372. {
  3373. blContext->mImageBase = base;
  3374. }
  3375. BF_EXPORT void BF_CALLTYPE BlContext_SetFixedBase(BlContext* blContext, bool enabled)
  3376. {
  3377. blContext->mHasFixedBase = enabled;
  3378. }
  3379. BF_EXPORT void BF_CALLTYPE BlContext_SetDynamicBase(BlContext* blContext, bool enabled)
  3380. {
  3381. blContext->mHasDynamicBase = enabled;
  3382. }
  3383. BF_EXPORT void BF_CALLTYPE BlContext_SetHighEntropyVA(BlContext* blContext, bool enabled)
  3384. {
  3385. blContext->mHighEntropyVA = enabled;
  3386. }
  3387. BF_EXPORT void BF_CALLTYPE BlContext_ManifestUAC(BlContext* blContext, const char* manifestUAC)
  3388. {
  3389. blContext->mManifestUAC = manifestUAC;
  3390. }
  3391. BF_EXPORT void BF_CALLTYPE BlContext_SetSubsystem(BlContext* blContext, int subsystem)
  3392. {
  3393. blContext->mPeSubsystem = subsystem;
  3394. }
  3395. BF_EXPORT void BF_CALLTYPE BlContext_SetStack(BlContext* blContext, int reserve, int commit)
  3396. {
  3397. if (reserve > 0)
  3398. blContext->mStackReserve = BF_ALIGN(reserve, 4);
  3399. if (commit > 0)
  3400. blContext->mStackCommit = BF_ALIGN(commit, 4);
  3401. }
  3402. BF_EXPORT void BF_CALLTYPE BlContext_SetHeap(BlContext* blContext, int reserve, int commit)
  3403. {
  3404. if (reserve > 0)
  3405. blContext->mHeapReserve = BF_ALIGN(reserve, 4);
  3406. if (commit > 0)
  3407. blContext->mHeapCommit = BF_ALIGN(commit, 4);
  3408. }