manip.c 56 KB

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