manip.c 57 KB

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