manip.c 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919
  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)
  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. {
  847. // If no current merged section has been specified, make this
  848. // one current. Otherwise, merge the current merged section
  849. // into this one.
  850. if (CurMergedSection)
  851. {
  852. if (MergeForward)
  853. CurMergedSection = MergeSections (CurMergedSection, Section);
  854. else
  855. CurMergedSection = MergeSections (Section, CurMergedSection);
  856. if (!CurMergedSection)
  857. return NULL;
  858. }
  859. else
  860. {
  861. CurMergedSection = Section;
  862. if (!MergeForward)
  863. M68kFixCode (Section);
  864. }
  865. // If an explicit destination section exists, and this section
  866. // is the destination, set a flag to append all following
  867. // sections at the end.
  868. if (CurMergedSection == Dest)
  869. MergeForward = TRUE;
  870. }
  871. }
  872. if (CurMergedSection)
  873. {
  874. M68kFixCode (CurMergedSection);
  875. HandleSectionContents (CurMergedSection, CurMergedSection);
  876. }
  877. return CurMergedSection;
  878. }
  879. // Get the size that would result from padding a section of size
  880. // OrigSize to a multiple of Alignment.
  881. SIZE GetPaddedSize (SIZE OrigSize, COUNT Alignment)
  882. {
  883. return (((OrigSize + Alignment - 1) / Alignment) * Alignment);
  884. }
  885. // Pad the section so its size becomes a multiple of Alignment.
  886. BOOLEAN PadSection (SECTION *Section, COUNT Alignment)
  887. {
  888. SIZE OrigSize = Section->Size;
  889. SIZE NewSize = GetPaddedSize (OrigSize, Alignment);
  890. if (NewSize > OrigSize)
  891. {
  892. // Increase the size of the section data.
  893. if (Section->Data)
  894. {
  895. I1 *NewData = realloc (Section->Data, NewSize);
  896. if (NewData)
  897. {
  898. memset (NewData + OrigSize, 0, NewSize - OrigSize);
  899. Section->Data = NewData;
  900. }
  901. else
  902. {
  903. Error (NULL, "Out of memory.");
  904. return FALSE;
  905. }
  906. }
  907. // Increase the size field.
  908. Section->Size = NewSize;
  909. }
  910. return TRUE;
  911. }
  912. // Try to resolve and remove relative relocs.
  913. BOOLEAN FixupRelativeRelocs (PROGRAM *Program)
  914. {
  915. BOOLEAN Result = TRUE;
  916. SECTION *Section;
  917. // For each section...
  918. for_each (Section, Program->Sections)
  919. {
  920. // If it contains real data...
  921. if (Section->Data)
  922. {
  923. RELOC *Reloc, *NextReloc;
  924. // For each reloc in the section...
  925. for (Reloc = GetFirst (Section->Relocs); Reloc; Reloc = NextReloc)
  926. {
  927. // Get the next reloc now because we might remove this one.
  928. NextReloc = GetNext (Reloc);
  929. if (Reloc->Relative)
  930. {
  931. // Try to resolve and remove this reloc.
  932. if (!FixupRelativeReloc (Reloc))
  933. Result = FALSE;
  934. }
  935. }
  936. }
  937. }
  938. return Result;
  939. }
  940. // Try to resolve and remove a single relative reloc.
  941. // This may cause the reloc to be freed.
  942. BOOLEAN FixupRelativeReloc (RELOC *Reloc)
  943. {
  944. BOOLEAN Result = FALSE;
  945. SECTION *Section = Reloc->Parent, *RelationSection;
  946. const char *CurFileName = GetFileName (Section, Reloc->Location);
  947. if (Reloc->Relation && Reloc->Relation->Symbol)
  948. RelationSection = Reloc->Relation->Symbol->Parent;
  949. else
  950. RelationSection = Section;
  951. // Check if we can resolve the reloc.
  952. if (Reloc->Relative && Reloc->Target.Symbol && ((!(Reloc->Relation)) || Reloc->Relation->Symbol))
  953. {
  954. if (Reloc->Target.Symbol->Parent == RelationSection)
  955. {
  956. // Now there are hidden relocs in the section.
  957. DisableRangeCutting (Section);
  958. if ((Reloc->Location >= 0) && (Reloc->Location + Reloc->Size <= Section->Size))
  959. {
  960. OFFSET Relation;
  961. // Check if the section contents at the reloc are zero.
  962. if (!(IsZeroDataRange (Section, Reloc->Location, Reloc->Location + Reloc->Size)))
  963. Warning (CurFileName, "Reloc at 0x%lX to `%s' on nonzero section contents. Overlapping with another?", (long) Reloc->Location, Reloc->Target.SymbolName);
  964. // Get the relative position of the target symbol (plus offset).
  965. Relation = GetLocationOffset (RelationSection, &(Reloc->Target)) + Reloc->FixedOffset;
  966. if (Reloc->Relation)
  967. Relation -= GetLocationOffset (RelationSection, Reloc->Relation);
  968. else
  969. Relation -= Reloc->Location;
  970. {
  971. // Try to tack the difference onto another reloc in order to avoid a "reloc on nonzero section contents" warning:
  972. RELOC *AnotherReloc = FindCompatibleReloc (Reloc, TRUE);
  973. if (AnotherReloc)
  974. {
  975. // Resolve the reloc by writing the address difference into the
  976. // other reloc's fixed offset.
  977. AnotherReloc->FixedOffset += Relation;
  978. Result = TRUE;
  979. }
  980. else
  981. {
  982. // Resolve the reloc by writing the relative position into the section.
  983. Result = AddTI (Section->Data + Reloc->Location, Reloc->Size, Relation, TRUE, Reloc->Relation != NULL);
  984. if (!Result)
  985. Error (CurFileName, "Symbol `%s' too far for size %ld reloc at 0x%lX.", Reloc->Target.SymbolName, (long) Reloc->Size, (long) Reloc->Location);
  986. }
  987. }
  988. }
  989. else
  990. {
  991. Warning (CurFileName, "Removing reloc at 0x%lX to `%s' outside of section.", (long) Reloc->Location, Reloc->Target.SymbolName);
  992. Result = TRUE;
  993. }
  994. if (Result)
  995. FreeReloc (Reloc);
  996. }
  997. else
  998. Error (CurFileName, "Relative reloc at 0x%lX to `%s' in different section.", (long) Reloc->Location, Reloc->Target.SymbolName);
  999. }
  1000. else
  1001. Error (CurFileName, "Cannot resolve reloc at 0x%lX to `%s'.", (long) Reloc->Location, Reloc->Target.SymbolName);
  1002. return Result;
  1003. }
  1004. // Find a reloc with the same location and size as this one.
  1005. RELOC *FindCompatibleReloc (const RELOC *Reloc, BOOLEAN AllowRelative)
  1006. {
  1007. return FindMatchingReloc (Reloc->Parent, Reloc->Location, Reloc->Size, AllowRelative, Reloc, Reloc);
  1008. }
  1009. // Find a reloc which matches the specified criteria.
  1010. RELOC *FindMatchingReloc (const SECTION *Section, OFFSET Location, SIZE Size, BOOLEAN AllowRelative, const void *Exception, const RELOC *Hint)
  1011. {
  1012. if (Hint && (Hint->Parent != Section))
  1013. Hint = NULL;
  1014. // Find the first reloc at the position.
  1015. while (Hint && (Hint->Location >= Location))
  1016. Hint = GetPrev (Hint);
  1017. while (Hint && (Hint->Location < Location))
  1018. Hint = GetNext (Hint);
  1019. if (!Hint)
  1020. Hint = FindRelocAtPos (Section, Location, TRUE);
  1021. // For each reloc that still has the right location...
  1022. while (Hint && (Hint->Location == Location))
  1023. {
  1024. // Check whether it matches the criteria.
  1025. if ((Hint->Size == Size)
  1026. && (AllowRelative || (!(Hint->Relative)))
  1027. && (Hint != Exception))
  1028. return (RELOC *) Hint;
  1029. Hint = GetNext (Hint);
  1030. }
  1031. return NULL;
  1032. }
  1033. // Make a reloc relative, and set its relation to the beginning of
  1034. // the section plus Offset. If Section is NULL, the program entry
  1035. // point is used as the relation.
  1036. BOOLEAN SetRelocRelation (RELOC *Reloc, SECTION *Section, OFFSET Offset)
  1037. {
  1038. // Make this a relative reloc.
  1039. Reloc->Relative = TRUE;
  1040. // If it already has a relation, free it.
  1041. FreeRelocRelation (Reloc);
  1042. // Set the relation to the section's beginning.
  1043. if (Section)
  1044. {
  1045. if ((Reloc->Relation = calloc (1, sizeof (LOCATION))))
  1046. {
  1047. Reloc->Relation->Symbol = Section->SectionSymbol;
  1048. Reloc->Relation->SymbolName = Section->SectionSymbol->Name;
  1049. Reloc->Relation->Offset = Offset;
  1050. }
  1051. else
  1052. {
  1053. Error (NULL, "Out of memory.");
  1054. return FALSE;
  1055. }
  1056. }
  1057. else
  1058. {
  1059. PROGRAM *Program = Reloc->Parent->Parent;
  1060. // If Section is NULL, use the program's entry point, and
  1061. // adjust the fixed offset instead of the relation's offset.
  1062. Reloc->Relation = &(Program->EntryPoint);
  1063. Reloc->FixedOffset -= Offset;
  1064. }
  1065. return TRUE;
  1066. }
  1067. // Make a reloc relative to the program entry point.
  1068. BOOLEAN SetRelocProgramRelative (RELOC *Reloc)
  1069. {
  1070. return SetRelocRelation (Reloc, NULL, 0);
  1071. }
  1072. // Find or create a common symbol with specified name and size.
  1073. SYMBOL *MakeCommonSymbol (PROGRAM *Program, const char *SymName, SIZE Size, BOOLEAN Initialize, const char *FileName)
  1074. {
  1075. // We need to search for a BSS section with a symbol with the same name,
  1076. // and grow this section if necessary. If not found, we create a new
  1077. // small BSS section.
  1078. SECTION *CurSection;
  1079. // For each section...
  1080. for_each (CurSection, Program->Sections)
  1081. {
  1082. // Check only for sections with uninitialized or zeroed data.
  1083. // Check if it has at least one symbol in it.
  1084. if ((!(CurSection->Data)) && (!(IsEmpty (CurSection->Symbols))))
  1085. {
  1086. SYMBOL *CurSymbol;
  1087. // For each symbol...
  1088. for_each (CurSymbol, CurSection->Symbols)
  1089. {
  1090. // Check if the symbol name matches.
  1091. if (CurSymbol->Exported && (!(strcmp (CurSymbol->Name, SymName))))
  1092. {
  1093. // Yes, we have found our symbol.
  1094. // Check if the size is sufficient.
  1095. const SYMBOL *NextSymbol = GetNext (CurSymbol);
  1096. // If there is no symbol that follows this one, we
  1097. // assume the symbol takes up all the space from its
  1098. // label to the end of the section.
  1099. OFFSET SymEnd = NextSymbol ? NextSymbol->Location : CurSection->Size;
  1100. // Check if the size is sufficient.
  1101. if (SymEnd - CurSymbol->Location >= Size)
  1102. // We were lucky; we can use this symbol directly.
  1103. return CurSymbol;
  1104. else
  1105. {
  1106. // We need to grow the BSS section. However, we
  1107. // should do this only if the symbol is the last
  1108. // one; otherwise maybe we could adjust all other
  1109. // symbol locations, but I don't know if that is
  1110. // safe. Apart from that, sharing a common symbol
  1111. // with a probably non-common (e.g. A68k) BSS
  1112. // section is probably not a very good idea
  1113. // anyway.
  1114. if (!NextSymbol)
  1115. {
  1116. // Grow the section. If the symbol's location
  1117. // is not zero, we need to add this location
  1118. // to the section's new size.
  1119. CurSection->Size = CurSymbol->Location + Size;
  1120. return CurSymbol;
  1121. }
  1122. }
  1123. }
  1124. }
  1125. }
  1126. }
  1127. // The symbol doesn't exist yet. Fine, we need to create
  1128. // a new BSS block of specified size, with one symbol in
  1129. // it, and refer to this symbol. This is a little bit of
  1130. // work, but not very difficult.
  1131. {
  1132. // Create a new section, initialize it, and append it to the list of sections.
  1133. SECTION *Section = calloc (1, sizeof (SECTION));
  1134. if (!Section)
  1135. {
  1136. Error (FileName, "Out of memory.");
  1137. return NULL;
  1138. }
  1139. Section->Parent = Program;
  1140. Section->Initialized = Initialize;
  1141. Section->Size = Size;
  1142. Section->FileName = FileName;
  1143. Append (Program->Sections, Section);
  1144. {
  1145. // Create a symbol in the new section.
  1146. SYMBOL *Symbol = calloc (1, sizeof (SYMBOL));
  1147. if (!Symbol)
  1148. {
  1149. Error (FileName, "Out of memory.");
  1150. return NULL;
  1151. }
  1152. Symbol->Parent = Section;
  1153. strncpy (Symbol->Name, SymName, MAX_SYM_LEN);
  1154. Symbol->Exported = TRUE;
  1155. Append (Section->Symbols, Symbol);
  1156. // Since the new symbol is at the beginning of the section, it is
  1157. // sufficient as a section symbol.
  1158. Section->SectionSymbol = Symbol;
  1159. // Return the symbol.
  1160. return Symbol;
  1161. }
  1162. }
  1163. }
  1164. // Try to find and import a symbol with a given name in some archive.
  1165. BOOLEAN ImportSymbolFromArchive (PROGRAM *Program, const char *SymName)
  1166. {
  1167. ARCHIVE *Archive;
  1168. // For each archive...
  1169. for_each (Archive, Program->Archives)
  1170. {
  1171. ARCHIVE_SYMBOL *Symbol;
  1172. // For each symbol...
  1173. for_each (Symbol, Archive->Symbols)
  1174. {
  1175. // If the name matches...
  1176. if (!(strcmp (SymName, Symbol->Name)))
  1177. // Import it.
  1178. return (ImportArchiveSymbol (Program, Symbol));
  1179. }
  1180. }
  1181. return FALSE;
  1182. }
  1183. // Create marker symbols at the beginning and end of the section, and write
  1184. // them to Marker. Returns NULL on error.
  1185. SECTION_MARKERS *CreateSectionMarkers (SECTION_MARKERS *Marker, SECTION *Section)
  1186. {
  1187. // Check if the parameters are valid.
  1188. if (Marker && Section)
  1189. {
  1190. SYMBOL *Symbol;
  1191. // Mark the section as essential so it isn't removed.
  1192. Section->Essential = TRUE;
  1193. // Use the section symbol for the beginning.
  1194. Marker->Start = Section->SectionSymbol;
  1195. // Create a symbol at the end.
  1196. Symbol = calloc (1, sizeof (SYMBOL));
  1197. if (!Symbol)
  1198. {
  1199. Error (NULL, "Out of memory.");
  1200. return NULL;
  1201. }
  1202. Symbol->Parent = Section;
  1203. Symbol->Location = Section->Size;
  1204. strcpy (Symbol->Name, Section->SectionSymbol->Name);
  1205. if (strlen (Symbol->Name) + sizeof (" end") - 1 <= MAX_SYM_LEN)
  1206. strcat (Symbol->Name, " end");
  1207. Append (Section->Symbols, Symbol);
  1208. Marker->End = Symbol;
  1209. return Marker;
  1210. }
  1211. else
  1212. return NULL;
  1213. }
  1214. // Get the object file at the specified position in the archive.
  1215. ARCHIVE_OBJECT *GetArchiveObject (ARCHIVE *Archive, FILE_PTR FileOffset)
  1216. {
  1217. ARCHIVE_OBJECT *Object;
  1218. // Look whether an object file at this position is already known.
  1219. for_each (Object, Archive->ObjectFiles)
  1220. {
  1221. if (Object->FileOffset == FileOffset)
  1222. // Yes, so no need to do anything.
  1223. return Object;
  1224. }
  1225. // Allocate a new library.
  1226. Object = calloc (1, sizeof (ARCHIVE_OBJECT));
  1227. if (!Object)
  1228. {
  1229. Error (NULL, "Out of memory.");
  1230. return NULL;
  1231. }
  1232. // Assign the data.
  1233. Object->Parent = Archive;
  1234. Object->FileOffset = FileOffset;
  1235. // Add the object file.
  1236. Append (Archive->ObjectFiles, Object);
  1237. return Object;
  1238. }
  1239. // Get a reference to the library identified in the string. The library is
  1240. // added to the program's used libraries if necessary.
  1241. LIBRARY *GetLibrary (PROGRAM *Program, const char *LibName)
  1242. {
  1243. LIBRARY *Library;
  1244. // Look whether a library with this name already exists.
  1245. for_each (Library, Program->Libraries)
  1246. {
  1247. if (!(strcmp (Library->Name, LibName)))
  1248. // Yes, so no need to do anything.
  1249. return Library;
  1250. }
  1251. // Allocate a new library.
  1252. Library = calloc (1, sizeof (LIBRARY));
  1253. if (!Library)
  1254. {
  1255. Error (NULL, "Out of memory.");
  1256. return NULL;
  1257. }
  1258. // Assign the data.
  1259. Library->Parent = Program;
  1260. strncpy (Library->Name, LibName, MAX_SYM_LEN);
  1261. // Add the library.
  1262. Append (Program->Libraries, Library);
  1263. return Library;
  1264. }
  1265. // Add a global import. This means that all archive members which export this
  1266. // symbol should be imported (unlike the import done by a reloc, which only
  1267. // imports the first member exporting the symbol).
  1268. GLOBAL_IMPORT *AddGlobalImport (PROGRAM *Program, const char *SymName)
  1269. {
  1270. GLOBAL_IMPORT *Import = CreateGlobalImport (Program, SymName);
  1271. if (Import)
  1272. ResolveGlobalImport (Program, Import);
  1273. return Import;
  1274. }
  1275. // First part of AddGlobalImport. Add a global import to the list.
  1276. GLOBAL_IMPORT *CreateGlobalImport (PROGRAM *Program, const char *SymName)
  1277. {
  1278. GLOBAL_IMPORT *Import;
  1279. // Look whether an import with this name already exists.
  1280. for_each (Import, Program->GlobalImports)
  1281. {
  1282. if (!(strcmp (Import->SymbolName, SymName)))
  1283. // Yes, so no need to do anything.
  1284. // Otherwise, we could even end up in infinite recursion.
  1285. // I don't know whether we should return NULL instead.
  1286. return Import;
  1287. }
  1288. // Allocate a new import.
  1289. Import = calloc (1, sizeof (GLOBAL_IMPORT));
  1290. if (!Import)
  1291. {
  1292. Error (NULL, "Out of memory.");
  1293. return NULL;
  1294. }
  1295. // Assign the data.
  1296. Import->Parent = Program;
  1297. strncpy (Import->SymbolName, SymName, MAX_SYM_LEN);
  1298. // Add the import.
  1299. Append (Program->GlobalImports, Import);
  1300. return Import;
  1301. }
  1302. // Second part of AddGlobalImport only. Try to resolve the newly added global
  1303. // import against already available archives.
  1304. void ResolveGlobalImport (PROGRAM *Program, GLOBAL_IMPORT *Import)
  1305. {
  1306. ARCHIVE *Archive;
  1307. // For each archive...
  1308. for_each (Archive, Program->Archives)
  1309. {
  1310. ARCHIVE_SYMBOL *Symbol;
  1311. // For each symbol...
  1312. for_each (Symbol, Archive->Symbols)
  1313. // Check if the import and the symbol match.
  1314. CheckGlobalImport (Import, Symbol);
  1315. }
  1316. }
  1317. // Check whether the symbol matches any global import,
  1318. // performing the appropriate actions if necessary.
  1319. GLOBAL_IMPORT *CheckGlobalImports (PROGRAM *Program, ARCHIVE_SYMBOL *Symbol)
  1320. {
  1321. GLOBAL_IMPORT *Import;
  1322. for_each (Import, Program->GlobalImports)
  1323. if (CheckGlobalImport (Import, Symbol))
  1324. return Import;
  1325. return NULL;
  1326. }
  1327. // Check whether the symbol matches the specified global import,
  1328. // performing the appropriate actions if necessary.
  1329. BOOLEAN CheckGlobalImport (GLOBAL_IMPORT *Import, ARCHIVE_SYMBOL *Symbol)
  1330. {
  1331. PROGRAM *Program = Import->Parent;
  1332. if (Symbol->ContainsInversion && (!(Program->GlobalImports.ResolveInversions)))
  1333. return FALSE;
  1334. // If the name matches, import the appropriate file.
  1335. if (!(strcmp (Symbol->Name, Import->SymbolName)))
  1336. {
  1337. Import->Succeeded = TRUE;
  1338. ImportArchiveSymbol (Program, Symbol);
  1339. if ((Import == Program->BSSImport) && Program->BSSSection)
  1340. Program->BSSSection->Handled = TRUE;
  1341. return TRUE;
  1342. }
  1343. // If the symbol contains the name of the global import, it is probably an
  1344. // ANDed combination with other imports. In that case, import it if all
  1345. // conditions are met.
  1346. else if (strstr (Symbol->Name, Import->SymbolName))
  1347. return CheckMultiConditionSymbol (Program, Symbol);
  1348. else
  1349. return FALSE;
  1350. }
  1351. // Check whether all conditions are met for an archive symbol with multiple
  1352. // or inverted conditions. If they are, import the appropriate file, and
  1353. // increment the counters of all global imports fulfilling non-inverted
  1354. // conditions.
  1355. BOOLEAN CheckMultiConditionSymbol (PROGRAM *Program, ARCHIVE_SYMBOL *Symbol)
  1356. {
  1357. BOOLEAN Result = TRUE;
  1358. BOOLEAN ContainsBSSImport = FALSE;
  1359. const char *SymName = Symbol->Name;
  1360. const char *AndOperatorPos;
  1361. if (Symbol->ContainsInversion && (!(Program->GlobalImports.ResolveInversions)))
  1362. return FALSE;
  1363. // Parse the symbol name from left to right, taking care of all operators.
  1364. do {
  1365. BOOLEAN Inverted = FALSE;
  1366. unsigned long SymNameLen;
  1367. GLOBAL_IMPORT *CurImport;
  1368. // Check whether condition is inverted.
  1369. if (!(strncmp (SYMOP_NOT, SymName, sizeof (SYMOP_NOT) - 1)))
  1370. {
  1371. if (!(Program->GlobalImports.ResolveInversions))
  1372. {
  1373. // This cannot happen actually due to the check at the
  1374. // beginning, but it makes sense to check it anyway.
  1375. Symbol->ContainsInversion = TRUE;
  1376. return FALSE;
  1377. }
  1378. Inverted = TRUE;
  1379. SymName += sizeof (SYMOP_NOT) - 1;
  1380. }
  1381. // Search for the next operator.
  1382. AndOperatorPos = strstr (SymName, SYMOP_AND);
  1383. if (AndOperatorPos)
  1384. SymNameLen = AndOperatorPos - SymName;
  1385. else
  1386. SymNameLen = strlen (SymName);
  1387. // Search for a global import which matches this part of the
  1388. // symbol name.
  1389. for_each (CurImport, Program->GlobalImports)
  1390. {
  1391. if ((!(strncmp (SymName, CurImport->SymbolName, SymNameLen))) && (SymNameLen == strlen (CurImport->SymbolName)))
  1392. {
  1393. Inverted = !Inverted;
  1394. CurImport->Succeeded = TRUE;
  1395. if (CurImport == Program->BSSImport)
  1396. ContainsBSSImport = TRUE;
  1397. break;
  1398. }
  1399. }
  1400. // If the condition is inverted and a symbol is found, or it is
  1401. // not inverted and no symbol is found, the import failed on this
  1402. // symbol (at least for now).
  1403. if (!Inverted)
  1404. Result = FALSE;
  1405. // Skip the operator.
  1406. if (AndOperatorPos)
  1407. SymName = AndOperatorPos + sizeof (SYMOP_AND) - 1;
  1408. } while (AndOperatorPos);
  1409. // All conditions have been met. Import the file.
  1410. if (Result)
  1411. {
  1412. ImportArchiveSymbol (Program, Symbol);
  1413. if (ContainsBSSImport && Program->BSSSection)
  1414. Program->BSSSection->Handled = TRUE;
  1415. }
  1416. return Result;
  1417. }
  1418. // Resolve all remaining global imports. Usually, global imports are
  1419. // processed directly, but if a symbol contains an inverted condition, we
  1420. // have to wait until we really know that no such global import exists.
  1421. void ResolveRemainingGlobalImports (PROGRAM *Program)
  1422. {
  1423. ARCHIVE *Archive;
  1424. // All negated symbols which appear now are to be seen as "not succeeded".
  1425. Program->GlobalImports.ResolveInversions = TRUE;
  1426. // For each archive...
  1427. for_each (Archive, Program->Archives)
  1428. {
  1429. ARCHIVE_SYMBOL *Symbol;
  1430. // For each symbol...
  1431. for_each (Symbol, Archive->Symbols)
  1432. {
  1433. // If it contains an inversion, we prevented it from being added
  1434. // before. Import it now.
  1435. if (Symbol->ContainsInversion)
  1436. CheckMultiConditionSymbol (Program, Symbol);
  1437. }
  1438. }
  1439. }
  1440. // Check whether all global imports have succeeded at least once.
  1441. BOOLEAN CheckAllGlobalImports (PROGRAM *Program)
  1442. {
  1443. BOOLEAN Result = TRUE;
  1444. GLOBAL_IMPORT *Import;
  1445. // For each import...
  1446. for_each (Import, Program->GlobalImports)
  1447. {
  1448. // Check whether it has succeeded.
  1449. if (!(Import->Succeeded))
  1450. {
  1451. Warning (NULL, "Unresolved global import `%s'.", Import->SymbolName);
  1452. Result = FALSE;
  1453. }
  1454. }
  1455. return Result;
  1456. }
  1457. // Find the first segment that overlaps with the specified range.
  1458. SEGMENT *FindSegment (const SECTION *Section, OFFSET Start, OFFSET End)
  1459. {
  1460. // Find the first segment that affects this range.
  1461. SEGMENT *Segment = FindSegmentAtPos (Section, Start, FALSE) ? : GetFirst (Section->Segments);
  1462. // Check whether it really hits the specified range.
  1463. if (Segment && (RangesOverlap (Segment->Location.Start->Location, Segment->Location.End->Location, Start, End)))
  1464. return Segment;
  1465. else
  1466. return NULL;
  1467. }
  1468. // Check whether the specified range is declared to contain code.
  1469. BOOLEAN IsCodeRange (const SECTION *Section, OFFSET Start, OFFSET End)
  1470. {
  1471. if (Section->Code)
  1472. {
  1473. // If no segments are specified, the entire section is one segment.
  1474. if (IsEmpty (Section->Segments))
  1475. return TRUE;
  1476. // Otherwise, find the correct segment and look at it.
  1477. else
  1478. {
  1479. const SEGMENT *Segment = FindSegment (Section, Start, End);
  1480. return (Segment && Segment->Code);
  1481. }
  1482. }
  1483. return FALSE;
  1484. }
  1485. // Check whether the section data in the specified range is zero. This only
  1486. // checks the actual data, not the relocs, ROM calls, etc.
  1487. BOOLEAN IsZeroDataRange (const SECTION *Section, OFFSET Start, OFFSET End)
  1488. {
  1489. if (Section->Data)
  1490. {
  1491. OFFSET CurOffset;
  1492. for (CurOffset = Start; CurOffset < End; CurOffset++)
  1493. {
  1494. if (!(IsZero (Section->Data [CurOffset])))
  1495. return FALSE;
  1496. }
  1497. return TRUE;
  1498. }
  1499. else
  1500. return Section->Initialized;
  1501. }
  1502. // Check whether the specified range contains only binary data, without
  1503. // relocs, ROM calls, or anything similar. The range includes Start, but not
  1504. // End.
  1505. // The Exception parameter specifies an item to skip when searching for
  1506. // possible problems.
  1507. BOOLEAN IsBinaryDataRange (const SECTION *Section, OFFSET Start, OFFSET End, const void *Exception)
  1508. {
  1509. if ((Start < 0) || (End > Section->Size))
  1510. return FALSE;
  1511. {
  1512. const SYMBOL *Symbol = FindSymbolAtPos (Section, Start, TRUE);
  1513. while (Symbol && (Symbol->Location < End))
  1514. {
  1515. if ((Symbol != Exception) && (Symbol->Location > Start))
  1516. return FALSE;
  1517. Symbol = GetNext (Symbol);
  1518. }
  1519. }
  1520. // Define a macro to make checking items more simple.
  1521. #define CheckItems(Type,Item) \
  1522. ({ \
  1523. const Type *Item = Find##Item##AtPos (Section, Start, FALSE) ? : GetFirst (Section->Item##s); \
  1524. while (Item && (Item->Location < End)) \
  1525. { \
  1526. if ((Item != Exception) && (RangesOverlap (Start, End, Item->Location, Item->Location + Item->Size))) \
  1527. return FALSE; \
  1528. Item = GetNext (Item); \
  1529. } \
  1530. })
  1531. CheckItems (RELOC, Reloc);
  1532. CheckItems (ROM_CALL, ROMCall);
  1533. CheckItems (RAM_CALL, RAMCall);
  1534. CheckItems (LIB_CALL, LibCall);
  1535. #undef CheckItems
  1536. return TRUE;
  1537. }
  1538. // Check whether there is a reloc or symbol or something similar which
  1539. // prevents us from optimizing away some code at the end of the section.
  1540. // The Exception parameter specifies an item to skip when searching for
  1541. // possible problems.
  1542. BOOLEAN CanShrinkSection (const SECTION *Section, OFFSET Location, const void *Exception)
  1543. {
  1544. // If we are not actually shrinking the section, either return value does
  1545. // not make much sense. We return a negative result to stop the
  1546. // optimization which is about to be done.
  1547. if (Location >= Section->Size)
  1548. return FALSE;
  1549. else
  1550. {
  1551. // Define a macro to make checking items more simple.
  1552. #define CheckItems(Type,Item,LocationSuffix) \
  1553. ({ \
  1554. const Type *Item = Find##Item##AtPos (Section, Location LocationSuffix, TRUE); \
  1555. while (Item) \
  1556. { \
  1557. if (Item != Exception) \
  1558. return FALSE; \
  1559. Item = GetNext (Item); \
  1560. } \
  1561. })
  1562. CheckItems (SYMBOL, Symbol, + 1);
  1563. CheckItems (RELOC, Reloc, );
  1564. CheckItems (ROM_CALL, ROMCall, );
  1565. CheckItems (RAM_CALL, RAMCall, );
  1566. CheckItems (LIB_CALL, LibCall, );
  1567. #undef CheckItems
  1568. return TRUE;
  1569. }
  1570. }
  1571. // Cut the section off at the specified location. All items behind this
  1572. // location are removed.
  1573. void CutSection (SECTION *Section, OFFSET Location)
  1574. {
  1575. if (Section->Size > Location)
  1576. {
  1577. Section->Size = Location;
  1578. if (Section->Data)
  1579. {
  1580. I1 *NewData = realloc (Section->Data, Location);
  1581. if (NewData || (!Location))
  1582. Section->Data = NewData;
  1583. }
  1584. // Define a macro to make removing items more simple.
  1585. #define CutItems(Type,Item,ExtraCode) \
  1586. ({ \
  1587. Type *Item = Find##Item##AtPos (Section, Location, TRUE), *Next##Item; \
  1588. while (Item) \
  1589. { \
  1590. Next##Item = GetNext (Item); \
  1591. if (!(ExtraCode)) \
  1592. { \
  1593. Unlink (Section->Item##s, Item); \
  1594. free (Item); \
  1595. } \
  1596. Item = Next##Item; \
  1597. } \
  1598. })
  1599. // Do not cut symbols, since they might be referenced.
  1600. CutItems (RELOC, Reloc, ({ FreeReloc (Reloc); TRUE; }));
  1601. CutItems (ROM_CALL, ROMCall, FALSE);
  1602. CutItems (RAM_CALL, RAMCall, FALSE);
  1603. CutItems (LIB_CALL, LibCall, FALSE);
  1604. #undef CutItems
  1605. }
  1606. }
  1607. // Allocate space at the end of the section and return a pointer to it (NULL
  1608. // in case of error, or if Size is 0). The data is initialized to zero.
  1609. I1 *AllocateSpaceInSection (SECTION *Section, SIZE Size)
  1610. {
  1611. if (Size)
  1612. {
  1613. // The old data size specifies how much we need to initialize to 0.
  1614. SIZE OldSize = Section->Size, OldDataSize = (Section->Data ? OldSize : 0);
  1615. // Allocate the new space. If the section does not have any data, allocate
  1616. // data for it.
  1617. I1 *NewData = realloc (Section->Data, OldSize + Size);
  1618. // OldSize + Size should never be 0, so if NewData is NULL,
  1619. // this really means "out of memory", and the original
  1620. // pointer will still be valid.
  1621. if (NewData)
  1622. {
  1623. Section->Data = NewData;
  1624. // Set everything to 0.
  1625. memset (NewData + OldDataSize, 0, OldSize + Size - OldDataSize);
  1626. Section->Size += Size;
  1627. return (NewData + OldSize);
  1628. }
  1629. else
  1630. Error (NULL, "Out of memory.");
  1631. }
  1632. return NULL;
  1633. }
  1634. // Apply general architecture-specific code fixes and optimizations to the
  1635. // program.
  1636. void FixCode (PROGRAM *Program)
  1637. {
  1638. SIZE OldSize, NewSize; // Used for repeated optimization.
  1639. // When cutting ranges, do the optimizations in a loop
  1640. // because optimizing might bring targets into range.
  1641. do {
  1642. SECTION *Section;
  1643. // Initialize the size counts in each iteration of the outer loop.
  1644. OldSize = 0;
  1645. NewSize = 0;
  1646. // For each section...
  1647. for_each (Section, Program->Sections)
  1648. {
  1649. if (Section->Code)
  1650. {
  1651. // Count the section size before optimizing it.
  1652. OldSize += Section->Size;
  1653. // If it contains code, apply fixes.
  1654. M68kFixCode (Section);
  1655. // Count the section size after optimizing it.
  1656. NewSize += Section->Size;
  1657. }
  1658. }
  1659. } while (Program->OptimizeInfo->CutRanges && (NewSize < OldSize));
  1660. }
  1661. // Disable range cutting for an entire section.
  1662. void DisableRangeCutting (SECTION *Section)
  1663. {
  1664. // Disable range cutting in the entire section.
  1665. Section->CanCutRanges = FALSE;
  1666. // Disable range cutting in all segments.
  1667. {
  1668. SEGMENT *Segment;
  1669. for_each (Segment, Section->Segments)
  1670. Segment->CanCutRanges = FALSE;
  1671. }
  1672. }