manip.c 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920
  1. /* manip.c: Routines to manipulate the internal data
  2. Copyright (C) 2002-2004 Sebastian Reichelt
  3. Copyright (C) 2003-2005 Kevin Kofler
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software Foundation,
  14. Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
  15. #include "manip.h"
  16. #include "integers.h"
  17. #include "special.h"
  18. #include "import/imp_ar.h"
  19. #include "bincode/fix_m68k.h"
  20. #include <stdlib.h>
  21. #include <string.h>
  22. // Free the program tree.
  23. void FreeProgram (PROGRAM *Program)
  24. {
  25. SECTION *Section, *NextSection;
  26. LIBRARY *Library, *NextLibrary;
  27. ARCHIVE *Archive, *NextArchive;
  28. GLOBAL_IMPORT *GlobalImport, *NextGlobalImport;
  29. for (GlobalImport = GetLast (Program->GlobalImports); GlobalImport; GlobalImport = NextGlobalImport)
  30. {
  31. NextGlobalImport = GetPrev (GlobalImport);
  32. free (GlobalImport);
  33. }
  34. for (Archive = GetLast (Program->Archives); Archive; Archive = NextArchive)
  35. {
  36. ARCHIVE_OBJECT *Object, *NextObject;
  37. ARCHIVE_SYMBOL *Symbol, *NextSymbol;
  38. NextArchive = GetPrev (Archive);
  39. for (Object = GetLast (Archive->ObjectFiles); Object; Object = NextObject)
  40. {
  41. NextObject = GetPrev (Object);
  42. free (Object);
  43. }
  44. for (Symbol = GetLast (Archive->Symbols); Symbol; Symbol = NextSymbol)
  45. {
  46. NextSymbol = GetPrev (Symbol);
  47. free (Symbol);
  48. }
  49. free ((I1 *) (Archive->Data));
  50. free (Archive);
  51. }
  52. for (Library = GetLast (Program->Libraries); Library; Library = NextLibrary)
  53. {
  54. NextLibrary = GetPrev (Library);
  55. free (Library);
  56. }
  57. for (Section = GetLast (Program->Sections); Section; Section = NextSection)
  58. {
  59. NextSection = GetPrev (Section);
  60. FreeSection (Section);
  61. }
  62. // Set all data to 0.
  63. memset (Program, 0, sizeof (PROGRAM));
  64. }
  65. // Free a section. The section is assumed not to be referenced.
  66. void FreeSection (SECTION *Section)
  67. {
  68. PROGRAM *Program = Section->Parent;
  69. // Need to free the data, if any.
  70. if (Section->Data)
  71. free (Section->Data);
  72. // Define a macro to make things easier.
  73. #define FreeItems(Type,Item) \
  74. ({ \
  75. Type *Item, *Next##Item; \
  76. for (Item = GetLast (Section->Item##s); Item; Item = Next##Item) \
  77. { \
  78. Next##Item = GetPrev (Item); \
  79. free (Item); \
  80. } \
  81. })
  82. FreeItems (SEGMENT, Segment);
  83. FreeItems (LIB_CALL, LibCall);
  84. FreeItems (RAM_CALL, RAMCall);
  85. FreeItems (ROM_CALL, ROMCall);
  86. {
  87. RELOC *Reloc, *NextReloc;
  88. for (Reloc = GetLast (Section->Relocs); Reloc; Reloc = NextReloc)
  89. {
  90. NextReloc = GetPrev (Reloc);
  91. FreeReloc (Reloc);
  92. }
  93. }
  94. FreeItems (SYMBOL, Symbol);
  95. #undef FreeItems
  96. if (Program->MainSection == Section)
  97. Program->MainSection = NULL;
  98. if (Program->BSSSection == Section)
  99. Program->BSSSection = NULL;
  100. if (Program->DataSection == Section)
  101. Program->DataSection = NULL;
  102. Unlink (Program->Sections, Section);
  103. free (Section);
  104. }
  105. // Free a relocation entry.
  106. void FreeReloc (RELOC *Reloc)
  107. {
  108. SECTION *Section = Reloc->Parent;
  109. Unlink (Section->Relocs, Reloc);
  110. // Need to free the symbol name, if it is not a reference to Symbol->Name.
  111. FreeLocationSymbolName (Section, &(Reloc->Target));
  112. // Need to free the relation if it exists.
  113. FreeRelocRelation (Reloc);
  114. free (Reloc);
  115. }
  116. // Free the relation reference of a relocation entry, and set it to
  117. // NULL.
  118. void FreeRelocRelation (RELOC *Reloc)
  119. {
  120. LOCATION *Relation = Reloc->Relation;
  121. SECTION *Section = Reloc->Parent;
  122. Reloc->Relation = NULL;
  123. if (Relation && (Relation != &(Section->Parent->EntryPoint)))
  124. {
  125. FreeLocationSymbolName (Section, Relation);
  126. free (Relation);
  127. }
  128. }
  129. // Free the symbol name of a location, if this is necessary.
  130. // If a symbol is already known, set the symbol name to its name.
  131. // Decrease the number of unresolved relocs in the section.
  132. void FreeLocationSymbolName (SECTION *Section, LOCATION *Location)
  133. {
  134. if (((!(Location->Symbol)) || (Location->SymbolName != Location->Symbol->Name)) && Location->SymbolName && (Location != &(Section->Parent->EntryPoint)))
  135. {
  136. if (--Section->Relocs.UnresolvedCount < 0)
  137. Warning (Section->FileName, "Internal unresolved count mismatch.");
  138. free ((char *) Location->SymbolName);
  139. }
  140. Location->SymbolName = (Location->Symbol ? Location->Symbol->Name : NULL);
  141. }
  142. // Create a section symbol for the given section, if none has been
  143. // created yet. If there already is one, set its name accordingly.
  144. // Return the section symbol.
  145. SYMBOL *CreateSectionSymbol (SECTION *Section, const char *SectionName)
  146. {
  147. char *SymName;
  148. // Create a new symbol.
  149. SYMBOL *Symbol = (Section->SectionSymbol ? : calloc (1, sizeof (SYMBOL)));
  150. if (!Symbol)
  151. {
  152. Error (Section->FileName, "Out of memory.");
  153. return NULL;
  154. }
  155. // Set the basic attributes of the symbol.
  156. Symbol->Parent = Section;
  157. // Insert the section's file name in front of the section name.
  158. if (Section->FileName)
  159. {
  160. strncpy (Symbol->Name, Section->FileName, MAX_SYM_LEN);
  161. SymName = Symbol->Name + strlen (Symbol->Name);
  162. if (SectionName && (SymName < Symbol->Name + MAX_SYM_LEN))
  163. *(SymName++) = ' ';
  164. }
  165. else
  166. SymName = Symbol->Name;
  167. // Insert the section name.
  168. if (SectionName)
  169. strncpy (SymName, SectionName, Symbol->Name + MAX_SYM_LEN - SymName);
  170. if (!(Section->SectionSymbol))
  171. {
  172. // Insert the symbol at the beginning of the linked list.
  173. Push (Section->Symbols, Symbol);
  174. // Mark the symbol as the section's beginning symbol.
  175. Section->SectionSymbol = Symbol;
  176. }
  177. return Symbol;
  178. }
  179. // Create a segment for the entire given section, if none has been
  180. // created yet. If the section already contains segments, return
  181. // NULL.
  182. SEGMENT *CreateSectionSegment (SECTION *Section)
  183. {
  184. if ((IsEmpty (Section->Segments)) && (Section->Size > 0))
  185. {
  186. SEGMENT *Segment = calloc (1, sizeof (SEGMENT));
  187. if (!Segment)
  188. {
  189. Error (Section->FileName, "Out of memory.");
  190. return NULL;
  191. }
  192. if (!(CreateSectionMarkers (&(Segment->Location), Section)))
  193. {
  194. free (Segment);
  195. return NULL;
  196. }
  197. Segment->Code = Section->Code;
  198. Segment->CanCutRanges = Section->CanCutRanges;
  199. Segment->FileName = Section->FileName;
  200. Push (Section->Segments, Segment);
  201. return Segment;
  202. }
  203. return NULL;
  204. }
  205. // If the section is a startup section, insert it at the place where
  206. // it belongs. Otherwise, append it to the end of the program.
  207. void InsertSection (PROGRAM *Program, SECTION *Section)
  208. {
  209. // Check if it is a startup section.
  210. if (Section->StartupNumber)
  211. {
  212. // Find the location where we have to insert the
  213. // section.
  214. SECTION *PrevStartupSection = FindStartupSection (Program, Section->StartupNumber);
  215. // If the entry point is already fixed, and this will insert the
  216. // section in front of the entry point symbol, the program will
  217. // probably fail.
  218. if (Program->EntryPoint.Symbol && (PrevStartupSection == GetFirst (Program->Sections)))
  219. Warning (Section->FileName, "Inserting startup section with number %ld in front of entry point.", (long) Section->StartupNumber);
  220. // Cannot remove startup sections.
  221. Section->Essential = TRUE;
  222. // Insert the section where it belongs.
  223. InsertAfter (Program->Sections, Section, PrevStartupSection);
  224. }
  225. // If it is not a startup section, append it at the end.
  226. else
  227. Append (Program->Sections, Section);
  228. }
  229. // Find the last startup section below or at StartupNumber.
  230. // If there is no such section, the function returns NULL.
  231. SECTION *FindStartupSection (const PROGRAM *Program, OFFSET StartupNumber)
  232. {
  233. SECTION *Section;
  234. // For each section...
  235. for_each (Section, Program->Sections)
  236. {
  237. // If it is not a startup section, or the startup number is higher,
  238. // the previous section was the one (may be NULL).
  239. if ((!(Section->StartupNumber)) || (Section->StartupNumber > StartupNumber))
  240. return (GetPrev (Section));
  241. }
  242. // After all the startup sections that were below the number, the
  243. // list ended. Or maybe there are no sections at all. In any case,
  244. // this is the correct thing to do.
  245. return (GetLast (Program->Sections));
  246. }
  247. // Insert the symbol at the correct place in the section.
  248. void InsertSymbol (SECTION *Section, SYMBOL *Symbol)
  249. {
  250. const SYMBOL *NextSymbol = FindSymbolAtPos (Section, Symbol->Location, TRUE);
  251. InsertBefore (Section->Symbols, Symbol, NextSymbol);
  252. }
  253. // Increase the counters for references between the two sections, if the sections
  254. // are different.
  255. static void IncRefCounts (SECTION *SourceSection, SECTION *TargetSection, const RELOC *Reloc)
  256. {
  257. if (SourceSection != TargetSection)
  258. {
  259. if (Reloc->Relative && (!(Reloc->Relation)))
  260. {
  261. SourceSection->Relocs.RelativeRefs = TRUE;
  262. TargetSection->Relocs.RelativeRefs = TRUE;
  263. }
  264. else if (M68kIsRelocOptimizable (Reloc))
  265. {
  266. SourceSection->Relocs.OptRefCount++;
  267. TargetSection->Relocs.OptRefCount++;
  268. }
  269. if (SourceSection->StartupNumber || TargetSection->StartupNumber)
  270. {
  271. SourceSection->Relocs.StartupRefs = TRUE;
  272. TargetSection->Relocs.StartupRefs = TRUE;
  273. }
  274. }
  275. }
  276. // Insert the reloc at the correct place in the section, and update the appropriate
  277. // counters. Also possibly mark the target section as referenced.
  278. void InsertReloc (SECTION *Section, RELOC *Reloc)
  279. {
  280. const RELOC *NextReloc = FindRelocAtPos (Section, Reloc->Location, TRUE);
  281. InsertBefore (Section->Relocs, Reloc, NextReloc);
  282. HandleLocation (Reloc, &(Reloc->Target));
  283. HandleLocation (Reloc, Reloc->Relation);
  284. {
  285. SYMBOL *TargetSymbol = Reloc->Target.Symbol;
  286. if (TargetSymbol)
  287. IncRefCounts (Section, TargetSymbol->Parent, Reloc);
  288. }
  289. }
  290. // Find the item preceding or following the given location. May return NULL.
  291. #define DefineFindItemAtPos(Type,Item,LocationSuffix) \
  292. Type *Find##Item##AtPos (const SECTION *Section, OFFSET Location, BOOLEAN Following) \
  293. { \
  294. /* Find the place so that Item->Location is always less than Location */ \
  295. /* and Next##Item->Location is always greater or equal. */ \
  296. Type *Item = NULL, *Next##Item = NULL; \
  297. if (Location > Section->Size >> 1) \
  298. { \
  299. Item = GetLast (Section->Item##s); \
  300. while (Item && (Item->Location LocationSuffix >= Location)) \
  301. { \
  302. Next##Item = Item; \
  303. Item = GetPrev (Item); \
  304. } \
  305. } \
  306. else \
  307. { \
  308. Next##Item = GetFirst (Section->Item##s); \
  309. while (Next##Item && (Next##Item->Location LocationSuffix < Location)) \
  310. { \
  311. Item = Next##Item; \
  312. Next##Item = GetNext (Next##Item); \
  313. } \
  314. } \
  315. /* If we are looking for something that follows, the case is clear. */ \
  316. /* Otherwise, we need to check whether the next item is also OK. */ \
  317. if (Following || (Next##Item && (Next##Item->Location LocationSuffix <= Location))) \
  318. return Next##Item; \
  319. else \
  320. return Item; \
  321. }
  322. DefineFindItemAtPos (SYMBOL, Symbol, );
  323. DefineFindItemAtPos (RELOC, Reloc, );
  324. DefineFindItemAtPos (ROM_CALL, ROMCall, );
  325. DefineFindItemAtPos (RAM_CALL, RAMCall, );
  326. DefineFindItemAtPos (LIB_CALL, LibCall, );
  327. DefineFindItemAtPos (SEGMENT, Segment, .Start->Location);
  328. #undef DefineFindItemAtPos
  329. // Get the file name where the code at a given location in the
  330. // section came from. May return NULL.
  331. const char *GetFileName (const SECTION *Section, OFFSET Location)
  332. {
  333. const SEGMENT *Segment = FindSegmentAtPos (Section, Location, FALSE);
  334. // Check whether the location is inside the segment.
  335. // It can be at the beginning, but not at the very end.
  336. if (Segment && (Location < Segment->Location.End->Location) && Segment->FileName)
  337. // Return the segment's file name.
  338. return Segment->FileName;
  339. // If no segment was found, return the section's file name.
  340. return Section->FileName;
  341. }
  342. // Return the offset of the specified location into the section. If the
  343. // offset is unknown, emit a warning and return 0.
  344. OFFSET GetLocationOffset (const SECTION *Section, const LOCATION *Location)
  345. {
  346. if (Location && Location->Symbol && (Location->Symbol->Parent == Section))
  347. return Location->Symbol->Location + Location->Offset;
  348. else
  349. {
  350. Warning (Section->FileName, "Symbol `%s' is not in section `%s'; using arbitrary location.", Location->SymbolName ? : "(unknown)", Section->SectionSymbol->Name);
  351. return 0;
  352. }
  353. }
  354. // Increase the counters and reference information necessary when this
  355. // location is used in the specified reloc.
  356. void HandleLocation (RELOC *Reloc, LOCATION *Location)
  357. {
  358. if (Location)
  359. {
  360. SECTION *Section = Reloc->Parent;
  361. if (!Location->Symbol)
  362. {
  363. Section->Relocs.UnresolvedCount++;
  364. }
  365. }
  366. }
  367. // Point the location to the appropriate symbol, if one is found.
  368. SYMBOL *ResolveLocation (PROGRAM *Program, SECTION *Section, LOCATION *Location)
  369. {
  370. if (Location->Symbol)
  371. return Location->Symbol;
  372. else
  373. {
  374. SECTION *CurSection;
  375. // For each section...
  376. for_each (CurSection, Program->Sections)
  377. {
  378. SYMBOL *CurSymbol;
  379. // For each symbol...
  380. for_each (CurSymbol, CurSection->Symbols)
  381. {
  382. // If the name matches, we have found the right symbol.
  383. if (CurSymbol->Exported && (!(strcmp (Location->SymbolName, CurSymbol->Name))))
  384. {
  385. // Set up the reloc accordingly, freeing its
  386. // destination string.
  387. Location->Symbol = CurSymbol;
  388. FreeLocationSymbolName (Section, Location);
  389. return CurSymbol;
  390. }
  391. }
  392. }
  393. return NULL;
  394. }
  395. }
  396. // If the reloc's target symbol name identifies a ROM, RAM,
  397. // or library call, replace it with the appropriate item.
  398. // This must be called in order, as the items are appended
  399. // unconditionally.
  400. static BOOLEAN ResolveSpecialExternalSymbolReloc (RELOC *Reloc)
  401. {
  402. SECTION *Section = Reloc->Parent;
  403. PROGRAM *Program = Section->Parent;
  404. const char *CurFileName = NULL;
  405. // Translate the reloc's symbol name.
  406. void *SymRef = NULL;
  407. OFFSET SymNum = 0;
  408. SpecialExternalSymbolTypes SymType = TranslateSpecialExternalSymbol (Program, (char *) (Reloc->Target.SymbolName), &SymRef, &SymNum);
  409. if (SymType != ST_NORMAL)
  410. CurFileName = GetFileName (Section, Reloc->Location);
  411. // Replace the reloc with the another item.
  412. switch (SymType)
  413. {
  414. case ST_ROM_CALL:
  415. {
  416. // Create a new ROM call.
  417. ROM_CALL *ROMCall = calloc (1, sizeof (ROM_CALL));
  418. if (!ROMCall)
  419. {
  420. Error (CurFileName, "Out of memory while resolving relocs.");
  421. return FALSE;
  422. }
  423. // Assign the attributes of the reloc to the ROM call.
  424. ROMCall->Parent = Section;
  425. ROMCall->Location = Reloc->Location;
  426. ROMCall->Number = SymNum;
  427. ROMCall->Size = Reloc->Size;
  428. ROMCall->FixedOffset = Reloc->Target.Offset + Reloc->FixedOffset;
  429. if (Reloc->Relative)
  430. Warning (CurFileName, "ROM calls cannot be relative; changing to absolute.");
  431. // Remove the reloc.
  432. FreeReloc (Reloc);
  433. // Add the ROM call.
  434. Append (Section->ROMCalls, ROMCall);
  435. // Adjust ROM call statistics.
  436. if (Program->HighestROMCall < SymNum)
  437. Program->HighestROMCall = SymNum;
  438. Section->ROMCalls.Handled = FALSE;
  439. }
  440. return TRUE;
  441. case ST_RAM_CALL:
  442. case ST_EXTRA_RAM:
  443. {
  444. // Create a new ROM call.
  445. RAM_CALL *RAMCall = calloc (1, sizeof (RAM_CALL));
  446. if (!RAMCall)
  447. {
  448. Error (CurFileName, "Out of memory while resolving relocs.");
  449. return FALSE;
  450. }
  451. // Assign the attributes of the reloc to the ROM call.
  452. RAMCall->Parent = Section;
  453. RAMCall->Location = Reloc->Location;
  454. RAMCall->Number = SymNum;
  455. RAMCall->Size = Reloc->Size;
  456. RAMCall->FixedOffset = Reloc->Target.Offset + Reloc->FixedOffset;
  457. RAMCall->ExtraRAMAddr = (SymType == ST_EXTRA_RAM);
  458. if (Reloc->Relative)
  459. Warning (CurFileName, "RAM calls cannot be relative; changing to absolute.");
  460. // Remove the reloc.
  461. FreeReloc (Reloc);
  462. // Add the RAM call.
  463. Append (Section->RAMCalls, RAMCall);
  464. // Adjust RAM call statistics.
  465. if (Program->HighestRAMCall < SymNum)
  466. Program->HighestRAMCall = SymNum;
  467. Section->RAMCalls.Handled = FALSE;
  468. }
  469. return TRUE;
  470. case ST_LIB_CALL:
  471. {
  472. // Create a new library call.
  473. LIB_CALL *LibCall = calloc (1, sizeof (LIB_CALL));
  474. if (!LibCall)
  475. {
  476. Error (CurFileName, "Out of memory while resolving relocs.");
  477. return FALSE;
  478. }
  479. // Assign the attributes of the reloc to the library call.
  480. LibCall->Parent = Section;
  481. LibCall->Location = Reloc->Location;
  482. LibCall->Library = SymRef;
  483. LibCall->Number = SymNum;
  484. LibCall->Size = Reloc->Size;
  485. LibCall->FixedOffset = Reloc->Target.Offset + Reloc->FixedOffset;
  486. if (Reloc->Relative)
  487. Warning (CurFileName, "Library calls cannot be relative; changing to absolute.");
  488. // Remove the reloc.
  489. FreeReloc (Reloc);
  490. // Add the library call.
  491. Append (Section->LibCalls, LibCall);
  492. if (LibCall->Library->Highest < SymNum)
  493. LibCall->Library->Highest = SymNum;
  494. if (!(LibCall->Library->Referenced))
  495. {
  496. LibCall->Library->Referenced = TRUE;
  497. Program->Libraries.ReferencedCount++;
  498. }
  499. Section->LibCalls.Handled = FALSE;
  500. }
  501. return TRUE;
  502. default:
  503. return FALSE;
  504. }
  505. }
  506. // Resolve the reloc's target, if possible.
  507. // Force: Fail on unresolvable reference.
  508. static BOOLEAN ResolveRelocTarget (RELOC *Reloc, BOOLEAN Force)
  509. {
  510. SECTION *Section = Reloc->Parent;
  511. PROGRAM *Program = Section->Parent;
  512. // If the target needs to be resolved, then try to do this.
  513. if (!(Reloc->Target.Symbol))
  514. {
  515. COUNT LoopCount = 0;
  516. do {
  517. BOOLEAN TryAgain = FALSE;
  518. SYMBOL *Symbol;
  519. // Resolve it as a reloc to a symbol.
  520. if ((Symbol = ResolveLocation (Program, Section, &(Reloc->Target))))
  521. {
  522. IncRefCounts (Section, Symbol->Parent, Reloc);
  523. return TRUE;
  524. }
  525. // Resolve it as a ROM/RAM/library call.
  526. else if (ResolveSpecialExternalSymbolReloc (Reloc))
  527. return TRUE;
  528. // Resolve it as a special ld-exported symbol reloc.
  529. else if (ResolveSpecialSymbolRelocTarget (Reloc, &TryAgain))
  530. {
  531. if (!TryAgain)
  532. return TRUE;
  533. }
  534. // Import the symbol from an archive.
  535. else if ((!(Program->Frozen)) && (ImportSymbolFromArchive (Program, Reloc->Target.SymbolName)))
  536. // Continue to loop.
  537. ;
  538. // It seems the reloc is currently unresolvable.
  539. else if (Force)
  540. {
  541. Error (GetFileName (Section, Reloc->Location), "Unresolved reference to `%s'.", Reloc->Target.SymbolName);
  542. return FALSE;
  543. }
  544. // Increase loop counter.
  545. LoopCount++;
  546. // Only re-loop twice. This enables us to use the
  547. // "TryAgain" from ResolveSpecialSymbolReloc and
  548. // ImportSymbolFromArchive, but prevents us from
  549. // entering an infinite loop.
  550. } while (LoopCount <= 2);
  551. return FALSE;
  552. }
  553. return TRUE;
  554. }
  555. // Resolve the reloc's relation, if possible.
  556. // Force: Fail on unresolvable reference.
  557. static BOOLEAN ResolveRelocRelation (RELOC *Reloc, BOOLEAN Force)
  558. {
  559. SECTION *Section = Reloc->Parent;
  560. PROGRAM *Program = Section->Parent;
  561. // If the relation needs to be resolved, then try to do this.
  562. if (Reloc->Relation && (!(Reloc->Relation->Symbol)))
  563. {
  564. COUNT LoopCount = 0;
  565. do {
  566. BOOLEAN TryAgain = FALSE;
  567. // Resolve it as a (negative) reloc to a symbol.
  568. if (ResolveLocation (Program, Section, Reloc->Relation))
  569. return TRUE;
  570. // Resolve it as a special ld-exported symbol reloc.
  571. else if (ResolveSpecialSymbolRelocRelation (Reloc, &TryAgain))
  572. {
  573. if (!TryAgain)
  574. return TRUE;
  575. }
  576. // Import the symbol from an archive.
  577. else if ((!(Program->Frozen)) && (ImportSymbolFromArchive (Program, Reloc->Relation->SymbolName)))
  578. // Continue to loop.
  579. ;
  580. // It seems the reloc is currently unresolvable.
  581. else if (Force)
  582. {
  583. Error (GetFileName (Section, Reloc->Location), "Unresolved reference to `%s'.", Reloc->Relation->SymbolName);
  584. return FALSE;
  585. }
  586. // Increase loop counter.
  587. LoopCount++;
  588. // Only re-loop twice. This enables us to use the
  589. // "TryAgain" from ResolveSpecialSymbolReloc and
  590. // ImportSymbolFromArchive, but prevents us from
  591. // entering an infinite loop.
  592. } while (LoopCount <= 2);
  593. return FALSE;
  594. }
  595. return TRUE;
  596. }
  597. // Resolve the reloc, if possible.
  598. // Force: Fail on unresolvable references.
  599. BOOLEAN ResolveReloc (RELOC *Reloc, BOOLEAN Force)
  600. {
  601. // First, resolve the relation. This might add the
  602. // resulting value to the reloc's target offset.
  603. BOOLEAN Result = ResolveRelocRelation (Reloc, Force);
  604. // Then resolve the target.
  605. if (ResolveRelocTarget (Reloc, Force))
  606. return Result;
  607. else
  608. return FALSE;
  609. }
  610. // Resolve all relocs in the program, if possible.
  611. // Force: Fail on unresolvable references.
  612. BOOLEAN ResolveRelocs (PROGRAM *Program, BOOLEAN Force)
  613. {
  614. BOOLEAN Result = TRUE;
  615. SECTION *Section;
  616. // For each section...
  617. for_each (Section, Program->Sections)
  618. {
  619. // Only do something if it contains unresolved references at all.
  620. if (Section->Relocs.UnresolvedCount > 0)
  621. {
  622. RELOC *Reloc, *NextReloc;
  623. // For each reloc...
  624. for (Reloc = GetFirst (Section->Relocs); Reloc; Reloc = NextReloc)
  625. {
  626. NextReloc = GetNext (Reloc);
  627. // Try to resolve it.
  628. if (!(ResolveReloc (Reloc, Force)))
  629. Result = FALSE;
  630. }
  631. }
  632. }
  633. return Result;
  634. }
  635. // Optimize the location to have the least possible offset.
  636. void OptimizeLocation (LOCATION *Location)
  637. {
  638. if (Location)
  639. {
  640. SYMBOL *OldSymbol = Location->Symbol;
  641. // Only proceed if the location points to a real symbol.
  642. if (OldSymbol)
  643. {
  644. // Find the symbol the reloc really points to.
  645. SYMBOL *NewSymbol = FindSymbolAtPos (OldSymbol->Parent, OldSymbol->Location, FALSE);
  646. // If we found a symbol that is closer, use that one.
  647. if (NewSymbol && (NewSymbol->Location != OldSymbol->Location))
  648. {
  649. Location->Offset += OldSymbol->Location - NewSymbol->Location;
  650. Location->Symbol = NewSymbol;
  651. Location->SymbolName = NewSymbol->Name;
  652. }
  653. }
  654. }
  655. }
  656. // Optimize all relocs to have the least possible target and relation offset.
  657. void OptimizeRelocs (PROGRAM *Program)
  658. {
  659. SECTION *Section;
  660. // For each section...
  661. for_each (Section, Program->Sections)
  662. {
  663. RELOC *Reloc;
  664. // For each reloc...
  665. for_each (Reloc, Section->Relocs)
  666. {
  667. // Optimize the target.
  668. OptimizeLocation (&(Reloc->Target));
  669. // Optimize the relation, if any.
  670. OptimizeLocation (Reloc->Relation);
  671. }
  672. }
  673. }
  674. // Merge section Src into Dest.
  675. SECTION *MergeSections (SECTION *Dest, SECTION *Src)
  676. {
  677. PROGRAM *Program = Dest->Parent;
  678. SIZE OrigSize, OrigSizePadded = 0;
  679. // Merging a section into itself should succeed without doing anything.
  680. if (Dest == Src)
  681. return Dest;
  682. // Handle the insertions at the end of the destination section, assuming
  683. // that the source section contains everything we need to output. This
  684. // is the best we can do.
  685. HandleSectionContents (Dest, Src);
  686. #ifdef FLASH_OS_SUPPORT
  687. // In Flash OS mode, if we are merging the startup and normal parts, pad the
  688. // startup part to 32 KB.
  689. if ((Program->Type == PT_FLASH_OS) && Dest->StartupNumber && (!(Src->StartupNumber)))
  690. OrigSizePadded = 0x8000;
  691. #endif /* FLASH_OS_SUPPORT */
  692. // Fix the code for the two sections.
  693. if (Dest->Code)
  694. M68kFixCodePreMerge (Dest, Src, OrigSizePadded);
  695. // If the destination size is fixed, disable range cutting.
  696. if (OrigSizePadded)
  697. DisableRangeCutting (Dest);
  698. // Create segments covering the entire source and destination sections.
  699. CreateSectionSegment (Dest);
  700. CreateSectionSegment (Src);
  701. // A startup section in a nostub program is against the rules of "nostub",
  702. // which means that no data except the raw program is included.
  703. if ((Program->Type == PT_NOSTUB) && (Dest->StartupNumber || Src->StartupNumber))
  704. {
  705. Warning (Dest->FileName, "Program declared as `nostub' contains startup sections.");
  706. // Switch to native mode to prevent more warnings, and because it makes sense.
  707. Program->Type = PT_NATIVE;
  708. }
  709. if (Program->Library && (Dest->StartupNumber < 0) && (Src->StartupNumber > 0))
  710. Warning (Dest->FileName, "Adding program startup section to library.");
  711. // Store the size of the destination section.
  712. OrigSize = Dest->Size;
  713. // If no size is specified yet, pad the destination section to have an even length.
  714. if (!OrigSizePadded)
  715. OrigSizePadded = GetPaddedSize (OrigSize, M68K_SECTION_ALIGNMENT);
  716. // Check whether the current size exceeds a fixed maximum.
  717. {
  718. SIZE MaxSize = OrigSizePadded;
  719. #ifdef FLASH_OS_SUPPORT
  720. // In Flash OS mode, the maximum size for the startup part is actually 8 KB less.
  721. if ((Program->Type == PT_FLASH_OS) && Dest->StartupNumber && (!(Src->StartupNumber)))
  722. MaxSize -= 0x2000;
  723. #endif /* FLASH_OS_SUPPORT */
  724. if (OrigSize > MaxSize)
  725. Warning (Dest->FileName, "Section size of %ld bytes is larger than requested size of %ld.", (long) OrigSize, (long) MaxSize);
  726. }
  727. // Check whether the padded size is really larger than the current size.
  728. // If not, this has already generated the warning above.
  729. // We check here (not above) because it's safer.
  730. if (OrigSizePadded < OrigSize)
  731. OrigSizePadded = OrigSize;
  732. // Adjust the size of the destination.
  733. Dest->Size = OrigSizePadded + Src->Size;
  734. // If one of the two sections has data, we need to keep it, so adjust the
  735. // other section accordingly. Otherwise, merging is simple.
  736. if (Dest->Data || Src->Data)
  737. {
  738. // Grow (or allocate) the data area of the destination section.
  739. if (Dest->Data)
  740. {
  741. Dest->Data = realloc (Dest->Data, Dest->Size);
  742. // Pad with zeroes if necessary.
  743. if (Dest->Data && (OrigSizePadded > OrigSize))
  744. memset (Dest->Data + OrigSize, 0, OrigSizePadded - OrigSize);
  745. }
  746. else if (Dest->Size)
  747. Dest->Data = calloc (Dest->Size, 1);
  748. if (Dest->Data || (!(Dest->Size)))
  749. {
  750. if (Dest->Data)
  751. {
  752. // Copy the data.
  753. if (Src->Data)
  754. memcpy (Dest->Data + OrigSizePadded, Src->Data, Src->Size);
  755. else
  756. memset (Dest->Data + OrigSizePadded, 0, Src->Size);
  757. }
  758. }
  759. else
  760. {
  761. Error (Dest->FileName, "Out of memory while merging sections.");
  762. return NULL;
  763. }
  764. Dest->Initialized = TRUE;
  765. }
  766. else
  767. {
  768. // Just need to merge attributes.
  769. Dest->Initialized |= Src->Initialized;
  770. }
  771. Dest->Mergeable = Dest->Mergeable && Src->Mergeable;
  772. Dest->Unaligned = Dest->Unaligned && Src->Unaligned;
  773. Dest->Essential |= Src->Essential;
  774. Dest->Constructors = Dest->Constructors && Src->Constructors;
  775. Dest->Destructors = Dest->Destructors && Src->Destructors;
  776. Dest->CanCutRanges |= Src->CanCutRanges;
  777. Dest->Frozen |= Src->Frozen;
  778. // Enable code optimizations if they are enabled for one of the sections.
  779. // It will be disabled on a segment basis if necessary.
  780. Dest->Code |= Src->Code;
  781. #define MergeHandling(Items) (Dest->Items.Handled = (Dest->Items.Handled && Src->Items.Handled) || (Dest->Items.Handled && IsEmpty(Src->Items)) || (Src->Items.Handled && IsEmpty(Dest->Items)))
  782. MergeHandling (ROMCalls);
  783. MergeHandling (RAMCalls);
  784. MergeHandling (LibCalls);
  785. #undef MergeHandling
  786. // Define a macro to make merging items more simple.
  787. #define MergeItems(Type,Item) \
  788. ({ \
  789. Type *Item, *Next##Item; \
  790. for (Item = GetFirst (Src->Item##s); Item; Item = Next##Item) \
  791. { \
  792. Next##Item = GetNext (Item); \
  793. Unlink (Src->Item##s, Item); \
  794. Item->Location += OrigSizePadded; \
  795. Append (Dest->Item##s, Item); \
  796. Item->Parent = Dest; \
  797. } \
  798. })
  799. // Merge everything, except segments.
  800. MergeItems (SYMBOL, Symbol);
  801. MergeItems (RELOC, Reloc);
  802. MergeItems (ROM_CALL, ROMCall);
  803. MergeItems (RAM_CALL, RAMCall);
  804. MergeItems (LIB_CALL, LibCall);
  805. #undef MergeItems
  806. // Merge segments.
  807. {
  808. SEGMENT *Segment, *NextSegment;
  809. for (Segment = GetFirst (Src->Segments); Segment; Segment = NextSegment)
  810. {
  811. NextSegment = GetNext (Segment);
  812. Unlink (Src->Segments, Segment);
  813. Append (Dest->Segments, Segment);
  814. }
  815. }
  816. Dest->Relocs.UnresolvedCount += Src->Relocs.UnresolvedCount;
  817. Dest->Relocs.EmittedCount += Src->Relocs.EmittedCount;
  818. // Free the source section.
  819. FreeSection (Src);
  820. return Dest;
  821. }
  822. // Merge all sections of the specified type.
  823. SECTION *MergeAllSections (PROGRAM *Program, SECTION *Dest, BOOLEAN AcceptInitialized, BOOLEAN AcceptUninitialized, BOOLEAN AcceptZeroes, BOOLEAN AcceptContents, BOOLEAN AcceptData, BOOLEAN AcceptCode, BOOLEAN AcceptNonConstructors, BOOLEAN AcceptConstructors, BOOLEAN AcceptDestructors, BOOLEAN AcceptNonStartup, BOOLEAN AcceptStartup, DebuggingInfoTypes AcceptDebuggingInfo)
  824. {
  825. BOOLEAN MergeForward = FALSE;
  826. SECTION *CurMergedSection = NULL, *Section, *NextSection;
  827. // For each section...
  828. for (Section = GetLast (Program->Sections); Section; Section = NextSection)
  829. {
  830. // Get the next section now, since GetNext won't work once the section
  831. // has been freed.
  832. NextSection = GetPrev (Section);
  833. // Check if the section meets the specified requirements.
  834. if ((!(Section->Handled))
  835. && (AcceptInitialized || (!(Section->Initialized)))
  836. && (AcceptUninitialized || Section->Initialized)
  837. && (AcceptZeroes || Section->Data || (!(Section->Initialized)) || Section->StartupNumber)
  838. && (AcceptContents || (!(Section->Data)) || (!(Section->Initialized)))
  839. && (AcceptData || Section->Code)
  840. && (AcceptCode || (!(Section->Code)))
  841. && (AcceptNonConstructors || Section->Constructors || Section->Destructors)
  842. && (AcceptConstructors || (!(Section->Constructors)))
  843. && (AcceptDestructors || (!(Section->Destructors)))
  844. && (AcceptNonStartup || Section->StartupNumber)
  845. && (AcceptStartup || (!(Section->StartupNumber)))
  846. && (AcceptDebuggingInfo == Section->DebuggingInfoType))
  847. {
  848. // If no current merged section has been specified, make this
  849. // one current. Otherwise, merge the current merged section
  850. // into this one.
  851. if (CurMergedSection)
  852. {
  853. if (MergeForward)
  854. CurMergedSection = MergeSections (CurMergedSection, Section);
  855. else
  856. CurMergedSection = MergeSections (Section, CurMergedSection);
  857. if (!CurMergedSection)
  858. return NULL;
  859. }
  860. else
  861. {
  862. CurMergedSection = Section;
  863. if (!MergeForward)
  864. M68kFixCode (Section);
  865. }
  866. // If an explicit destination section exists, and this section
  867. // is the destination, set a flag to append all following
  868. // sections at the end.
  869. if (CurMergedSection == Dest)
  870. MergeForward = TRUE;
  871. }
  872. }
  873. if (CurMergedSection)
  874. {
  875. M68kFixCode (CurMergedSection);
  876. HandleSectionContents (CurMergedSection, CurMergedSection);
  877. }
  878. return CurMergedSection;
  879. }
  880. // Get the size that would result from padding a section of size
  881. // OrigSize to a multiple of Alignment.
  882. SIZE GetPaddedSize (SIZE OrigSize, COUNT Alignment)
  883. {
  884. return (((OrigSize + Alignment - 1) / Alignment) * Alignment);
  885. }
  886. // Pad the section so its size becomes a multiple of Alignment.
  887. BOOLEAN PadSection (SECTION *Section, COUNT Alignment)
  888. {
  889. SIZE OrigSize = Section->Size;
  890. SIZE NewSize = GetPaddedSize (OrigSize, Alignment);
  891. if (NewSize > OrigSize)
  892. {
  893. // Increase the size of the section data.
  894. if (Section->Data)
  895. {
  896. I1 *NewData = realloc (Section->Data, NewSize);
  897. if (NewData)
  898. {
  899. memset (NewData + OrigSize, 0, NewSize - OrigSize);
  900. Section->Data = NewData;
  901. }
  902. else
  903. {
  904. Error (NULL, "Out of memory.");
  905. return FALSE;
  906. }
  907. }
  908. // Increase the size field.
  909. Section->Size = NewSize;
  910. }
  911. return TRUE;
  912. }
  913. // Try to resolve and remove relative relocs.
  914. BOOLEAN FixupRelativeRelocs (PROGRAM *Program)
  915. {
  916. BOOLEAN Result = TRUE;
  917. SECTION *Section;
  918. // For each section...
  919. for_each (Section, Program->Sections)
  920. {
  921. // If it contains real data...
  922. if (Section->Data)
  923. {
  924. RELOC *Reloc, *NextReloc;
  925. // For each reloc in the section...
  926. for (Reloc = GetFirst (Section->Relocs); Reloc; Reloc = NextReloc)
  927. {
  928. // Get the next reloc now because we might remove this one.
  929. NextReloc = GetNext (Reloc);
  930. if (Reloc->Relative)
  931. {
  932. // Try to resolve and remove this reloc.
  933. if (!FixupRelativeReloc (Reloc))
  934. Result = FALSE;
  935. }
  936. }
  937. }
  938. }
  939. return Result;
  940. }
  941. // Try to resolve and remove a single relative reloc.
  942. // This may cause the reloc to be freed.
  943. BOOLEAN FixupRelativeReloc (RELOC *Reloc)
  944. {
  945. BOOLEAN Result = FALSE;
  946. SECTION *Section = Reloc->Parent, *RelationSection;
  947. const char *CurFileName = GetFileName (Section, Reloc->Location);
  948. if (Reloc->Relation && Reloc->Relation->Symbol)
  949. RelationSection = Reloc->Relation->Symbol->Parent;
  950. else
  951. RelationSection = Section;
  952. // Check if we can resolve the reloc.
  953. if (Reloc->Relative && Reloc->Target.Symbol && ((!(Reloc->Relation)) || Reloc->Relation->Symbol))
  954. {
  955. if (Reloc->Target.Symbol->Parent == RelationSection)
  956. {
  957. // Now there are hidden relocs in the section.
  958. DisableRangeCutting (Section);
  959. if ((Reloc->Location >= 0) && (Reloc->Location + Reloc->Size <= Section->Size))
  960. {
  961. OFFSET Relation;
  962. // Check if the section contents at the reloc are zero.
  963. if (!(IsZeroDataRange (Section, Reloc->Location, Reloc->Location + Reloc->Size)))
  964. Warning (CurFileName, "Reloc at 0x%lX to `%s' on nonzero section contents. Overlapping with another?", (long) Reloc->Location, Reloc->Target.SymbolName);
  965. // Get the relative position of the target symbol (plus offset).
  966. Relation = GetLocationOffset (RelationSection, &(Reloc->Target)) + Reloc->FixedOffset;
  967. if (Reloc->Relation)
  968. Relation -= GetLocationOffset (RelationSection, Reloc->Relation);
  969. else
  970. Relation -= Reloc->Location;
  971. {
  972. // Try to tack the difference onto another reloc in order to avoid a "reloc on nonzero section contents" warning:
  973. RELOC *AnotherReloc = FindCompatibleReloc (Reloc, TRUE);
  974. if (AnotherReloc)
  975. {
  976. // Resolve the reloc by writing the address difference into the
  977. // other reloc's fixed offset.
  978. AnotherReloc->FixedOffset += Relation;
  979. Result = TRUE;
  980. }
  981. else
  982. {
  983. // Resolve the reloc by writing the relative position into the section.
  984. Result = AddTI (Section->Data + Reloc->Location, Reloc->Size, Relation, TRUE, Reloc->Relation != NULL);
  985. if (!Result)
  986. Error (CurFileName, "Symbol `%s' too far for size %ld reloc at 0x%lX.", Reloc->Target.SymbolName, (long) Reloc->Size, (long) Reloc->Location);
  987. }
  988. }
  989. }
  990. else
  991. {
  992. Warning (CurFileName, "Removing reloc at 0x%lX to `%s' outside of section.", (long) Reloc->Location, Reloc->Target.SymbolName);
  993. Result = TRUE;
  994. }
  995. if (Result)
  996. FreeReloc (Reloc);
  997. }
  998. else
  999. Error (CurFileName, "Relative reloc at 0x%lX to `%s' in different section.", (long) Reloc->Location, Reloc->Target.SymbolName);
  1000. }
  1001. else
  1002. Error (CurFileName, "Cannot resolve reloc at 0x%lX to `%s'.", (long) Reloc->Location, Reloc->Target.SymbolName);
  1003. return Result;
  1004. }
  1005. // Find a reloc with the same location and size as this one.
  1006. RELOC *FindCompatibleReloc (const RELOC *Reloc, BOOLEAN AllowRelative)
  1007. {
  1008. return FindMatchingReloc (Reloc->Parent, Reloc->Location, Reloc->Size, AllowRelative, Reloc, Reloc);
  1009. }
  1010. // Find a reloc which matches the specified criteria.
  1011. RELOC *FindMatchingReloc (const SECTION *Section, OFFSET Location, SIZE Size, BOOLEAN AllowRelative, const void *Exception, const RELOC *Hint)
  1012. {
  1013. if (Hint && (Hint->Parent != Section))
  1014. Hint = NULL;
  1015. // Find the first reloc at the position.
  1016. while (Hint && (Hint->Location >= Location))
  1017. Hint = GetPrev (Hint);
  1018. while (Hint && (Hint->Location < Location))
  1019. Hint = GetNext (Hint);
  1020. if (!Hint)
  1021. Hint = FindRelocAtPos (Section, Location, TRUE);
  1022. // For each reloc that still has the right location...
  1023. while (Hint && (Hint->Location == Location))
  1024. {
  1025. // Check whether it matches the criteria.
  1026. if ((Hint->Size == Size)
  1027. && (AllowRelative || (!(Hint->Relative)))
  1028. && (Hint != Exception))
  1029. return (RELOC *) Hint;
  1030. Hint = GetNext (Hint);
  1031. }
  1032. return NULL;
  1033. }
  1034. // Make a reloc relative, and set its relation to the beginning of
  1035. // the section plus Offset. If Section is NULL, the program entry
  1036. // point is used as the relation.
  1037. BOOLEAN SetRelocRelation (RELOC *Reloc, SECTION *Section, OFFSET Offset)
  1038. {
  1039. // Make this a relative reloc.
  1040. Reloc->Relative = TRUE;
  1041. // If it already has a relation, free it.
  1042. FreeRelocRelation (Reloc);
  1043. // Set the relation to the section's beginning.
  1044. if (Section)
  1045. {
  1046. if ((Reloc->Relation = calloc (1, sizeof (LOCATION))))
  1047. {
  1048. Reloc->Relation->Symbol = Section->SectionSymbol;
  1049. Reloc->Relation->SymbolName = Section->SectionSymbol->Name;
  1050. Reloc->Relation->Offset = Offset;
  1051. }
  1052. else
  1053. {
  1054. Error (NULL, "Out of memory.");
  1055. return FALSE;
  1056. }
  1057. }
  1058. else
  1059. {
  1060. PROGRAM *Program = Reloc->Parent->Parent;
  1061. // If Section is NULL, use the program's entry point, and
  1062. // adjust the fixed offset instead of the relation's offset.
  1063. Reloc->Relation = &(Program->EntryPoint);
  1064. Reloc->FixedOffset -= Offset;
  1065. }
  1066. return TRUE;
  1067. }
  1068. // Make a reloc relative to the program entry point.
  1069. BOOLEAN SetRelocProgramRelative (RELOC *Reloc)
  1070. {
  1071. return SetRelocRelation (Reloc, NULL, 0);
  1072. }
  1073. // Find or create a common symbol with specified name and size.
  1074. SYMBOL *MakeCommonSymbol (PROGRAM *Program, const char *SymName, SIZE Size, BOOLEAN Initialize, const char *FileName)
  1075. {
  1076. // We need to search for a BSS section with a symbol with the same name,
  1077. // and grow this section if necessary. If not found, we create a new
  1078. // small BSS section.
  1079. SECTION *CurSection;
  1080. // For each section...
  1081. for_each (CurSection, Program->Sections)
  1082. {
  1083. // Check only for sections with uninitialized or zeroed data.
  1084. // Check if it has at least one symbol in it.
  1085. if ((!(CurSection->Data)) && (!(IsEmpty (CurSection->Symbols))))
  1086. {
  1087. SYMBOL *CurSymbol;
  1088. // For each symbol...
  1089. for_each (CurSymbol, CurSection->Symbols)
  1090. {
  1091. // Check if the symbol name matches.
  1092. if (CurSymbol->Exported && (!(strcmp (CurSymbol->Name, SymName))))
  1093. {
  1094. // Yes, we have found our symbol.
  1095. // Check if the size is sufficient.
  1096. const SYMBOL *NextSymbol = GetNext (CurSymbol);
  1097. // If there is no symbol that follows this one, we
  1098. // assume the symbol takes up all the space from its
  1099. // label to the end of the section.
  1100. OFFSET SymEnd = NextSymbol ? NextSymbol->Location : CurSection->Size;
  1101. // Check if the size is sufficient.
  1102. if (SymEnd - CurSymbol->Location >= Size)
  1103. // We were lucky; we can use this symbol directly.
  1104. return CurSymbol;
  1105. else
  1106. {
  1107. // We need to grow the BSS section. However, we
  1108. // should do this only if the symbol is the last
  1109. // one; otherwise maybe we could adjust all other
  1110. // symbol locations, but I don't know if that is
  1111. // safe. Apart from that, sharing a common symbol
  1112. // with a probably non-common (e.g. A68k) BSS
  1113. // section is probably not a very good idea
  1114. // anyway.
  1115. if (!NextSymbol)
  1116. {
  1117. // Grow the section. If the symbol's location
  1118. // is not zero, we need to add this location
  1119. // to the section's new size.
  1120. CurSection->Size = CurSymbol->Location + Size;
  1121. return CurSymbol;
  1122. }
  1123. }
  1124. }
  1125. }
  1126. }
  1127. }
  1128. // The symbol doesn't exist yet. Fine, we need to create
  1129. // a new BSS block of specified size, with one symbol in
  1130. // it, and refer to this symbol. This is a little bit of
  1131. // work, but not very difficult.
  1132. {
  1133. // Create a new section, initialize it, and append it to the list of sections.
  1134. SECTION *Section = calloc (1, sizeof (SECTION));
  1135. if (!Section)
  1136. {
  1137. Error (FileName, "Out of memory.");
  1138. return NULL;
  1139. }
  1140. Section->Parent = Program;
  1141. Section->Initialized = Initialize;
  1142. Section->Size = Size;
  1143. Section->FileName = FileName;
  1144. Append (Program->Sections, Section);
  1145. {
  1146. // Create a symbol in the new section.
  1147. SYMBOL *Symbol = calloc (1, sizeof (SYMBOL));
  1148. if (!Symbol)
  1149. {
  1150. Error (FileName, "Out of memory.");
  1151. return NULL;
  1152. }
  1153. Symbol->Parent = Section;
  1154. strncpy (Symbol->Name, SymName, MAX_SYM_LEN);
  1155. Symbol->Exported = TRUE;
  1156. Append (Section->Symbols, Symbol);
  1157. // Since the new symbol is at the beginning of the section, it is
  1158. // sufficient as a section symbol.
  1159. Section->SectionSymbol = Symbol;
  1160. // Return the symbol.
  1161. return Symbol;
  1162. }
  1163. }
  1164. }
  1165. // Try to find and import a symbol with a given name in some archive.
  1166. BOOLEAN ImportSymbolFromArchive (PROGRAM *Program, const char *SymName)
  1167. {
  1168. ARCHIVE *Archive;
  1169. // For each archive...
  1170. for_each (Archive, Program->Archives)
  1171. {
  1172. ARCHIVE_SYMBOL *Symbol;
  1173. // For each symbol...
  1174. for_each (Symbol, Archive->Symbols)
  1175. {
  1176. // If the name matches...
  1177. if (!(strcmp (SymName, Symbol->Name)))
  1178. // Import it.
  1179. return (ImportArchiveSymbol (Program, Symbol));
  1180. }
  1181. }
  1182. return FALSE;
  1183. }
  1184. // Create marker symbols at the beginning and end of the section, and write
  1185. // them to Marker. Returns NULL on error.
  1186. SECTION_MARKERS *CreateSectionMarkers (SECTION_MARKERS *Marker, SECTION *Section)
  1187. {
  1188. // Check if the parameters are valid.
  1189. if (Marker && Section)
  1190. {
  1191. SYMBOL *Symbol;
  1192. // Mark the section as essential so it isn't removed.
  1193. Section->Essential = TRUE;
  1194. // Use the section symbol for the beginning.
  1195. Marker->Start = Section->SectionSymbol;
  1196. // Create a symbol at the end.
  1197. Symbol = calloc (1, sizeof (SYMBOL));
  1198. if (!Symbol)
  1199. {
  1200. Error (NULL, "Out of memory.");
  1201. return NULL;
  1202. }
  1203. Symbol->Parent = Section;
  1204. Symbol->Location = Section->Size;
  1205. strcpy (Symbol->Name, Section->SectionSymbol->Name);
  1206. if (strlen (Symbol->Name) + sizeof (" end") - 1 <= MAX_SYM_LEN)
  1207. strcat (Symbol->Name, " end");
  1208. Append (Section->Symbols, Symbol);
  1209. Marker->End = Symbol;
  1210. return Marker;
  1211. }
  1212. else
  1213. return NULL;
  1214. }
  1215. // Get the object file at the specified position in the archive.
  1216. ARCHIVE_OBJECT *GetArchiveObject (ARCHIVE *Archive, FILE_PTR FileOffset)
  1217. {
  1218. ARCHIVE_OBJECT *Object;
  1219. // Look whether an object file at this position is already known.
  1220. for_each (Object, Archive->ObjectFiles)
  1221. {
  1222. if (Object->FileOffset == FileOffset)
  1223. // Yes, so no need to do anything.
  1224. return Object;
  1225. }
  1226. // Allocate a new library.
  1227. Object = calloc (1, sizeof (ARCHIVE_OBJECT));
  1228. if (!Object)
  1229. {
  1230. Error (NULL, "Out of memory.");
  1231. return NULL;
  1232. }
  1233. // Assign the data.
  1234. Object->Parent = Archive;
  1235. Object->FileOffset = FileOffset;
  1236. // Add the object file.
  1237. Append (Archive->ObjectFiles, Object);
  1238. return Object;
  1239. }
  1240. // Get a reference to the library identified in the string. The library is
  1241. // added to the program's used libraries if necessary.
  1242. LIBRARY *GetLibrary (PROGRAM *Program, const char *LibName)
  1243. {
  1244. LIBRARY *Library;
  1245. // Look whether a library with this name already exists.
  1246. for_each (Library, Program->Libraries)
  1247. {
  1248. if (!(strcmp (Library->Name, LibName)))
  1249. // Yes, so no need to do anything.
  1250. return Library;
  1251. }
  1252. // Allocate a new library.
  1253. Library = calloc (1, sizeof (LIBRARY));
  1254. if (!Library)
  1255. {
  1256. Error (NULL, "Out of memory.");
  1257. return NULL;
  1258. }
  1259. // Assign the data.
  1260. Library->Parent = Program;
  1261. strncpy (Library->Name, LibName, MAX_SYM_LEN);
  1262. // Add the library.
  1263. Append (Program->Libraries, Library);
  1264. return Library;
  1265. }
  1266. // Add a global import. This means that all archive members which export this
  1267. // symbol should be imported (unlike the import done by a reloc, which only
  1268. // imports the first member exporting the symbol).
  1269. GLOBAL_IMPORT *AddGlobalImport (PROGRAM *Program, const char *SymName)
  1270. {
  1271. GLOBAL_IMPORT *Import = CreateGlobalImport (Program, SymName);
  1272. if (Import)
  1273. ResolveGlobalImport (Program, Import);
  1274. return Import;
  1275. }
  1276. // First part of AddGlobalImport. Add a global import to the list.
  1277. GLOBAL_IMPORT *CreateGlobalImport (PROGRAM *Program, const char *SymName)
  1278. {
  1279. GLOBAL_IMPORT *Import;
  1280. // Look whether an import with this name already exists.
  1281. for_each (Import, Program->GlobalImports)
  1282. {
  1283. if (!(strcmp (Import->SymbolName, SymName)))
  1284. // Yes, so no need to do anything.
  1285. // Otherwise, we could even end up in infinite recursion.
  1286. // I don't know whether we should return NULL instead.
  1287. return Import;
  1288. }
  1289. // Allocate a new import.
  1290. Import = calloc (1, sizeof (GLOBAL_IMPORT));
  1291. if (!Import)
  1292. {
  1293. Error (NULL, "Out of memory.");
  1294. return NULL;
  1295. }
  1296. // Assign the data.
  1297. Import->Parent = Program;
  1298. strncpy (Import->SymbolName, SymName, MAX_SYM_LEN);
  1299. // Add the import.
  1300. Append (Program->GlobalImports, Import);
  1301. return Import;
  1302. }
  1303. // Second part of AddGlobalImport only. Try to resolve the newly added global
  1304. // import against already available archives.
  1305. void ResolveGlobalImport (PROGRAM *Program, GLOBAL_IMPORT *Import)
  1306. {
  1307. ARCHIVE *Archive;
  1308. // For each archive...
  1309. for_each (Archive, Program->Archives)
  1310. {
  1311. ARCHIVE_SYMBOL *Symbol;
  1312. // For each symbol...
  1313. for_each (Symbol, Archive->Symbols)
  1314. // Check if the import and the symbol match.
  1315. CheckGlobalImport (Import, Symbol);
  1316. }
  1317. }
  1318. // Check whether the symbol matches any global import,
  1319. // performing the appropriate actions if necessary.
  1320. GLOBAL_IMPORT *CheckGlobalImports (PROGRAM *Program, ARCHIVE_SYMBOL *Symbol)
  1321. {
  1322. GLOBAL_IMPORT *Import;
  1323. for_each (Import, Program->GlobalImports)
  1324. if (CheckGlobalImport (Import, Symbol))
  1325. return Import;
  1326. return NULL;
  1327. }
  1328. // Check whether the symbol matches the specified global import,
  1329. // performing the appropriate actions if necessary.
  1330. BOOLEAN CheckGlobalImport (GLOBAL_IMPORT *Import, ARCHIVE_SYMBOL *Symbol)
  1331. {
  1332. PROGRAM *Program = Import->Parent;
  1333. if (Symbol->ContainsInversion && (!(Program->GlobalImports.ResolveInversions)))
  1334. return FALSE;
  1335. // If the name matches, import the appropriate file.
  1336. if (!(strcmp (Symbol->Name, Import->SymbolName)))
  1337. {
  1338. Import->Succeeded = TRUE;
  1339. ImportArchiveSymbol (Program, Symbol);
  1340. if ((Import == Program->BSSImport) && Program->BSSSection)
  1341. Program->BSSSection->Handled = TRUE;
  1342. return TRUE;
  1343. }
  1344. // If the symbol contains the name of the global import, it is probably an
  1345. // ANDed combination with other imports. In that case, import it if all
  1346. // conditions are met.
  1347. else if (strstr (Symbol->Name, Import->SymbolName))
  1348. return CheckMultiConditionSymbol (Program, Symbol);
  1349. else
  1350. return FALSE;
  1351. }
  1352. // Check whether all conditions are met for an archive symbol with multiple
  1353. // or inverted conditions. If they are, import the appropriate file, and
  1354. // increment the counters of all global imports fulfilling non-inverted
  1355. // conditions.
  1356. BOOLEAN CheckMultiConditionSymbol (PROGRAM *Program, ARCHIVE_SYMBOL *Symbol)
  1357. {
  1358. BOOLEAN Result = TRUE;
  1359. BOOLEAN ContainsBSSImport = FALSE;
  1360. const char *SymName = Symbol->Name;
  1361. const char *AndOperatorPos;
  1362. if (Symbol->ContainsInversion && (!(Program->GlobalImports.ResolveInversions)))
  1363. return FALSE;
  1364. // Parse the symbol name from left to right, taking care of all operators.
  1365. do {
  1366. BOOLEAN Inverted = FALSE;
  1367. unsigned long SymNameLen;
  1368. GLOBAL_IMPORT *CurImport;
  1369. // Check whether condition is inverted.
  1370. if (!(strncmp (SYMOP_NOT, SymName, sizeof (SYMOP_NOT) - 1)))
  1371. {
  1372. if (!(Program->GlobalImports.ResolveInversions))
  1373. {
  1374. // This cannot happen actually due to the check at the
  1375. // beginning, but it makes sense to check it anyway.
  1376. Symbol->ContainsInversion = TRUE;
  1377. return FALSE;
  1378. }
  1379. Inverted = TRUE;
  1380. SymName += sizeof (SYMOP_NOT) - 1;
  1381. }
  1382. // Search for the next operator.
  1383. AndOperatorPos = strstr (SymName, SYMOP_AND);
  1384. if (AndOperatorPos)
  1385. SymNameLen = AndOperatorPos - SymName;
  1386. else
  1387. SymNameLen = strlen (SymName);
  1388. // Search for a global import which matches this part of the
  1389. // symbol name.
  1390. for_each (CurImport, Program->GlobalImports)
  1391. {
  1392. if ((!(strncmp (SymName, CurImport->SymbolName, SymNameLen))) && (SymNameLen == strlen (CurImport->SymbolName)))
  1393. {
  1394. Inverted = !Inverted;
  1395. CurImport->Succeeded = TRUE;
  1396. if (CurImport == Program->BSSImport)
  1397. ContainsBSSImport = TRUE;
  1398. break;
  1399. }
  1400. }
  1401. // If the condition is inverted and a symbol is found, or it is
  1402. // not inverted and no symbol is found, the import failed on this
  1403. // symbol (at least for now).
  1404. if (!Inverted)
  1405. Result = FALSE;
  1406. // Skip the operator.
  1407. if (AndOperatorPos)
  1408. SymName = AndOperatorPos + sizeof (SYMOP_AND) - 1;
  1409. } while (AndOperatorPos);
  1410. // All conditions have been met. Import the file.
  1411. if (Result)
  1412. {
  1413. ImportArchiveSymbol (Program, Symbol);
  1414. if (ContainsBSSImport && Program->BSSSection)
  1415. Program->BSSSection->Handled = TRUE;
  1416. }
  1417. return Result;
  1418. }
  1419. // Resolve all remaining global imports. Usually, global imports are
  1420. // processed directly, but if a symbol contains an inverted condition, we
  1421. // have to wait until we really know that no such global import exists.
  1422. void ResolveRemainingGlobalImports (PROGRAM *Program)
  1423. {
  1424. ARCHIVE *Archive;
  1425. // All negated symbols which appear now are to be seen as "not succeeded".
  1426. Program->GlobalImports.ResolveInversions = TRUE;
  1427. // For each archive...
  1428. for_each (Archive, Program->Archives)
  1429. {
  1430. ARCHIVE_SYMBOL *Symbol;
  1431. // For each symbol...
  1432. for_each (Symbol, Archive->Symbols)
  1433. {
  1434. // If it contains an inversion, we prevented it from being added
  1435. // before. Import it now.
  1436. if (Symbol->ContainsInversion)
  1437. CheckMultiConditionSymbol (Program, Symbol);
  1438. }
  1439. }
  1440. }
  1441. // Check whether all global imports have succeeded at least once.
  1442. BOOLEAN CheckAllGlobalImports (PROGRAM *Program)
  1443. {
  1444. BOOLEAN Result = TRUE;
  1445. GLOBAL_IMPORT *Import;
  1446. // For each import...
  1447. for_each (Import, Program->GlobalImports)
  1448. {
  1449. // Check whether it has succeeded.
  1450. if (!(Import->Succeeded))
  1451. {
  1452. Warning (NULL, "Unresolved global import `%s'.", Import->SymbolName);
  1453. Result = FALSE;
  1454. }
  1455. }
  1456. return Result;
  1457. }
  1458. // Find the first segment that overlaps with the specified range.
  1459. SEGMENT *FindSegment (const SECTION *Section, OFFSET Start, OFFSET End)
  1460. {
  1461. // Find the first segment that affects this range.
  1462. SEGMENT *Segment = FindSegmentAtPos (Section, Start, FALSE) ? : GetFirst (Section->Segments);
  1463. // Check whether it really hits the specified range.
  1464. if (Segment && (RangesOverlap (Segment->Location.Start->Location, Segment->Location.End->Location, Start, End)))
  1465. return Segment;
  1466. else
  1467. return NULL;
  1468. }
  1469. // Check whether the specified range is declared to contain code.
  1470. BOOLEAN IsCodeRange (const SECTION *Section, OFFSET Start, OFFSET End)
  1471. {
  1472. if (Section->Code)
  1473. {
  1474. // If no segments are specified, the entire section is one segment.
  1475. if (IsEmpty (Section->Segments))
  1476. return TRUE;
  1477. // Otherwise, find the correct segment and look at it.
  1478. else
  1479. {
  1480. const SEGMENT *Segment = FindSegment (Section, Start, End);
  1481. return (Segment && Segment->Code);
  1482. }
  1483. }
  1484. return FALSE;
  1485. }
  1486. // Check whether the section data in the specified range is zero. This only
  1487. // checks the actual data, not the relocs, ROM calls, etc.
  1488. BOOLEAN IsZeroDataRange (const SECTION *Section, OFFSET Start, OFFSET End)
  1489. {
  1490. if (Section->Data)
  1491. {
  1492. OFFSET CurOffset;
  1493. for (CurOffset = Start; CurOffset < End; CurOffset++)
  1494. {
  1495. if (!(IsZero (Section->Data [CurOffset])))
  1496. return FALSE;
  1497. }
  1498. return TRUE;
  1499. }
  1500. else
  1501. return Section->Initialized;
  1502. }
  1503. // Check whether the specified range contains only binary data, without
  1504. // relocs, ROM calls, or anything similar. The range includes Start, but not
  1505. // End.
  1506. // The Exception parameter specifies an item to skip when searching for
  1507. // possible problems.
  1508. BOOLEAN IsBinaryDataRange (const SECTION *Section, OFFSET Start, OFFSET End, const void *Exception)
  1509. {
  1510. if ((Start < 0) || (End > Section->Size))
  1511. return FALSE;
  1512. {
  1513. const SYMBOL *Symbol = FindSymbolAtPos (Section, Start, TRUE);
  1514. while (Symbol && (Symbol->Location < End))
  1515. {
  1516. if ((Symbol != Exception) && (Symbol->Location > Start))
  1517. return FALSE;
  1518. Symbol = GetNext (Symbol);
  1519. }
  1520. }
  1521. // Define a macro to make checking items more simple.
  1522. #define CheckItems(Type,Item) \
  1523. ({ \
  1524. const Type *Item = Find##Item##AtPos (Section, Start, FALSE) ? : GetFirst (Section->Item##s); \
  1525. while (Item && (Item->Location < End)) \
  1526. { \
  1527. if ((Item != Exception) && (RangesOverlap (Start, End, Item->Location, Item->Location + Item->Size))) \
  1528. return FALSE; \
  1529. Item = GetNext (Item); \
  1530. } \
  1531. })
  1532. CheckItems (RELOC, Reloc);
  1533. CheckItems (ROM_CALL, ROMCall);
  1534. CheckItems (RAM_CALL, RAMCall);
  1535. CheckItems (LIB_CALL, LibCall);
  1536. #undef CheckItems
  1537. return TRUE;
  1538. }
  1539. // Check whether there is a reloc or symbol or something similar which
  1540. // prevents us from optimizing away some code at the end of the section.
  1541. // The Exception parameter specifies an item to skip when searching for
  1542. // possible problems.
  1543. BOOLEAN CanShrinkSection (const SECTION *Section, OFFSET Location, const void *Exception)
  1544. {
  1545. // If we are not actually shrinking the section, either return value does
  1546. // not make much sense. We return a negative result to stop the
  1547. // optimization which is about to be done.
  1548. if (Location >= Section->Size)
  1549. return FALSE;
  1550. else
  1551. {
  1552. // Define a macro to make checking items more simple.
  1553. #define CheckItems(Type,Item,LocationSuffix) \
  1554. ({ \
  1555. const Type *Item = Find##Item##AtPos (Section, Location LocationSuffix, TRUE); \
  1556. while (Item) \
  1557. { \
  1558. if (Item != Exception) \
  1559. return FALSE; \
  1560. Item = GetNext (Item); \
  1561. } \
  1562. })
  1563. CheckItems (SYMBOL, Symbol, + 1);
  1564. CheckItems (RELOC, Reloc, );
  1565. CheckItems (ROM_CALL, ROMCall, );
  1566. CheckItems (RAM_CALL, RAMCall, );
  1567. CheckItems (LIB_CALL, LibCall, );
  1568. #undef CheckItems
  1569. return TRUE;
  1570. }
  1571. }
  1572. // Cut the section off at the specified location. All items behind this
  1573. // location are removed.
  1574. void CutSection (SECTION *Section, OFFSET Location)
  1575. {
  1576. if (Section->Size > Location)
  1577. {
  1578. Section->Size = Location;
  1579. if (Section->Data)
  1580. {
  1581. I1 *NewData = realloc (Section->Data, Location);
  1582. if (NewData || (!Location))
  1583. Section->Data = NewData;
  1584. }
  1585. // Define a macro to make removing items more simple.
  1586. #define CutItems(Type,Item,ExtraCode) \
  1587. ({ \
  1588. Type *Item = Find##Item##AtPos (Section, Location, TRUE), *Next##Item; \
  1589. while (Item) \
  1590. { \
  1591. Next##Item = GetNext (Item); \
  1592. if (!(ExtraCode)) \
  1593. { \
  1594. Unlink (Section->Item##s, Item); \
  1595. free (Item); \
  1596. } \
  1597. Item = Next##Item; \
  1598. } \
  1599. })
  1600. // Do not cut symbols, since they might be referenced.
  1601. CutItems (RELOC, Reloc, ({ FreeReloc (Reloc); TRUE; }));
  1602. CutItems (ROM_CALL, ROMCall, FALSE);
  1603. CutItems (RAM_CALL, RAMCall, FALSE);
  1604. CutItems (LIB_CALL, LibCall, FALSE);
  1605. #undef CutItems
  1606. }
  1607. }
  1608. // Allocate space at the end of the section and return a pointer to it (NULL
  1609. // in case of error, or if Size is 0). The data is initialized to zero.
  1610. I1 *AllocateSpaceInSection (SECTION *Section, SIZE Size)
  1611. {
  1612. if (Size)
  1613. {
  1614. // The old data size specifies how much we need to initialize to 0.
  1615. SIZE OldSize = Section->Size, OldDataSize = (Section->Data ? OldSize : 0);
  1616. // Allocate the new space. If the section does not have any data, allocate
  1617. // data for it.
  1618. I1 *NewData = realloc (Section->Data, OldSize + Size);
  1619. // OldSize + Size should never be 0, so if NewData is NULL,
  1620. // this really means "out of memory", and the original
  1621. // pointer will still be valid.
  1622. if (NewData)
  1623. {
  1624. Section->Data = NewData;
  1625. // Set everything to 0.
  1626. memset (NewData + OldDataSize, 0, OldSize + Size - OldDataSize);
  1627. Section->Size += Size;
  1628. return (NewData + OldSize);
  1629. }
  1630. else
  1631. Error (NULL, "Out of memory.");
  1632. }
  1633. return NULL;
  1634. }
  1635. // Apply general architecture-specific code fixes and optimizations to the
  1636. // program.
  1637. void FixCode (PROGRAM *Program)
  1638. {
  1639. SIZE OldSize, NewSize; // Used for repeated optimization.
  1640. // When cutting ranges, do the optimizations in a loop
  1641. // because optimizing might bring targets into range.
  1642. do {
  1643. SECTION *Section;
  1644. // Initialize the size counts in each iteration of the outer loop.
  1645. OldSize = 0;
  1646. NewSize = 0;
  1647. // For each section...
  1648. for_each (Section, Program->Sections)
  1649. {
  1650. if (Section->Code)
  1651. {
  1652. // Count the section size before optimizing it.
  1653. OldSize += Section->Size;
  1654. // If it contains code, apply fixes.
  1655. M68kFixCode (Section);
  1656. // Count the section size after optimizing it.
  1657. NewSize += Section->Size;
  1658. }
  1659. }
  1660. } while (Program->OptimizeInfo->CutRanges && (NewSize < OldSize));
  1661. }
  1662. // Disable range cutting for an entire section.
  1663. void DisableRangeCutting (SECTION *Section)
  1664. {
  1665. // Disable range cutting in the entire section.
  1666. Section->CanCutRanges = FALSE;
  1667. // Disable range cutting in all segments.
  1668. {
  1669. SEGMENT *Segment;
  1670. for_each (Segment, Section->Segments)
  1671. Segment->CanCutRanges = FALSE;
  1672. }
  1673. }