manip.c 57 KB

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