comprrlc.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  1. /* comprrlc.c: Routines for compressed relocation tables
  2. Copyright (C) 2003-2005 Kevin Kofler
  3. Portions copyright (C) 2002-2003 Sebastian Reichelt
  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 "comprrlc.h"
  16. #include "../integers.h"
  17. #include "../special.h"
  18. #include "../manip.h"
  19. #include "model/list.h"
  20. #include <stdlib.h>
  21. #include <string.h>
  22. // Append a new I1 to the section. Return TRUE on success, FALSE on failure.
  23. static BOOLEAN AppendI1ToSection (SECTION *Section, I1 NewI1)
  24. {
  25. TI1 *NewSpace = (TI1 *) AllocateSpaceInSection (Section, 1);
  26. if (!NewSpace)
  27. return FALSE;
  28. WriteTI1 (*NewSpace, NewI1);
  29. return TRUE;
  30. }
  31. // Append a new I2 to the section. Return TRUE on success, FALSE on failure.
  32. static BOOLEAN AppendI2ToSection (SECTION *Section, I2 NewI2)
  33. {
  34. TI2 *NewSpace = (TI2 *) AllocateSpaceInSection (Section, 2);
  35. if (!NewSpace)
  36. return FALSE;
  37. WriteTI2 (*NewSpace, NewI2);
  38. return TRUE;
  39. }
  40. // Emit a compressed reloc nibble buffer. Return TRUE on success, FALSE on
  41. // failure.
  42. static BOOLEAN EmitCompressedRelocNibbles (SECTION *Section, I4 NibbleCount, I1 *NibbleBuffer)
  43. {
  44. I4 CurrentNibble;
  45. I4 ByteCount = (NibbleCount + 1) >> 1; // number of bytes emitted as nibbles
  46. #define AppendI1(i1) ({if (!AppendI1ToSection (Section, (i1))) return FALSE;})
  47. #define AppendNibbles(n1, n2) AppendI1 (((n1) << 4) + (n2))
  48. if (NibbleCount < 3)
  49. {
  50. // Too few entries for nibbles, emit bytes.
  51. for (CurrentNibble = 0; CurrentNibble < NibbleCount; CurrentNibble++)
  52. AppendI1 (NibbleBuffer[CurrentNibble] + 1);
  53. return TRUE;
  54. }
  55. // Emit the first nibble pair.
  56. AppendNibbles (ByteCount + 6, *NibbleBuffer);
  57. // Emit the remaining nibble pairs.
  58. for (CurrentNibble = 1; CurrentNibble < NibbleCount - 1; CurrentNibble += 2)
  59. AppendNibbles (NibbleBuffer[CurrentNibble], NibbleBuffer[CurrentNibble + 1]);
  60. // If the number of nibbles is even, emit the last one as a byte.
  61. if (!(NibbleCount & 1))
  62. AppendI1 (NibbleBuffer[NibbleCount - 1] + 1);
  63. #undef AppendI1
  64. #undef AppendNibbles
  65. return TRUE;
  66. }
  67. // Emit a compressed reloc. If Offset is -1, end the relocation table. Return
  68. // TRUE on success, FALSE on failure.
  69. static BOOLEAN EmitCompressedReloc (SECTION *Section, OFFSET Offset)
  70. {
  71. // Maximum number of nibbles in a nibble group.
  72. #define MAX_NIBBLES 9
  73. static I4 NibbleCount = 0;
  74. static I1 NibbleBuffer[MAX_NIBBLES] = {};
  75. #define AppendI1(i1) ({if (!AppendI1ToSection (Section, (i1))) return FALSE;})
  76. #define AppendI2(i2) ({if (!AppendI2ToSection (Section, (i2))) return FALSE;})
  77. #define EmitNibbles() ({if (!EmitCompressedRelocNibbles (Section, NibbleCount, NibbleBuffer)) return FALSE; NibbleCount = 0;})
  78. if (Offset == -1)
  79. {
  80. // End the relocation table.
  81. EmitNibbles();
  82. AppendI1(0);
  83. }
  84. else
  85. {
  86. Continue:
  87. if (Offset < 16)
  88. {
  89. // We have a nibble. Check if we have room left in the buffer.
  90. if (NibbleCount == MAX_NIBBLES)
  91. {
  92. // Room full. Emit the nibbles in the buffer.
  93. EmitNibbles();
  94. }
  95. // Put the nibble into the buffer.
  96. NibbleBuffer[NibbleCount++] = Offset;
  97. }
  98. else
  99. {
  100. // We have a byte or a word. Emit the nibbles in the buffer.
  101. EmitNibbles();
  102. if (Offset < 127)
  103. {
  104. // We have a byte.
  105. AppendI1 (Offset + 1);
  106. }
  107. else if (Offset < 16510)
  108. {
  109. // We have a word.
  110. AppendI2 (Offset + 49025);
  111. }
  112. else
  113. {
  114. // We have an 0xFFFF word and an additional offset.
  115. AppendI2 (65535);
  116. Offset -= 16510;
  117. goto Continue;
  118. }
  119. }
  120. }
  121. #undef AppendI1
  122. #undef AppendI2
  123. #undef EmitNibbles
  124. #undef MAX_NIBBLES
  125. return TRUE;
  126. }
  127. // Emit a compressed reloc given the true offset between the 2 relocs. Compute
  128. // the offset as used in the compressed reloc table or give an error message if
  129. // it isn't representable. Call EmitCompressedReloc with the computed offset.
  130. // Return TRUE on success, FALSE on failure.
  131. static BOOLEAN EmitCompressedRelocFromActualOffset (SECTION *Section, OFFSET Offset)
  132. {
  133. if ((Offset > 0) && (Offset & 1))
  134. {
  135. Error (Section->FileName, "Odd offset `%ld' between 2 absolute relocs. Even offset needed.", (long) Offset);
  136. return FALSE;
  137. }
  138. if (Offset < 4)
  139. {
  140. Error (Section->FileName, (Offset >= 0) ? "Cannot emit overlapping absolute relocs (offset `0x%lx', need offset >=4)."
  141. : "Invalid internal reloc sorting order (offset `-0x%lx', need positive offset).",
  142. (Offset >= 0) ? Offset : -Offset);
  143. return FALSE;
  144. }
  145. return EmitCompressedReloc (Section, (Offset - 4) >> 1);
  146. }
  147. // Emit a reloc table in compressed format for the items enumerated in the
  148. // list model specified by Model.
  149. static BOOLEAN EmitCompressedFormatRelocs (LIST_MODEL *Model, SECTION *SourceSection, const LOCATION *SourceBase, void *UserData, SECTION *Section)
  150. {
  151. if (!SourceSection)
  152. SourceSection = Section;
  153. SourceSection->Frozen = TRUE;
  154. {
  155. void *NextItem = NULL;
  156. OFFSET Offset;
  157. // Output the first item in the list...
  158. // Output the target offset, and get the reloc's location.
  159. Offset = Model (SourceSection, &NextItem, UserData, FALSE, TRUE);
  160. // A return value < 0 indicates that the list was empty.
  161. if (Offset >= 0)
  162. {
  163. OFFSET BaseAddress = GetLocationOffset (SourceSection, SourceBase);
  164. if (BaseAddress & 1)
  165. {
  166. Error (Section->FileName, "Invalid base address `0x%lx'. Even base address needed.", BaseAddress);
  167. return FALSE;
  168. }
  169. if (Offset & 1)
  170. {
  171. Error (Section->FileName, "Odd offset between base address `0x%lx' and first absolute reloc `0x%lx'. Even offset needed.", BaseAddress, Offset);
  172. return FALSE;
  173. }
  174. if (Offset < BaseAddress)
  175. {
  176. Error (Section->FileName, "Cannot emit absolute reloc located at `0x%lx' before base address.", Offset);
  177. return FALSE;
  178. }
  179. // Emit the reloc.
  180. if (!(EmitCompressedReloc (Section, (Offset - BaseAddress) >> 1)))
  181. return FALSE;
  182. // Output the remaining items in the list...
  183. while (NextItem)
  184. {
  185. // Save the previous offset.
  186. OFFSET LastOffset = Offset;
  187. // Output the target offset, and get the reloc's location.
  188. Offset = Model (SourceSection, &NextItem, UserData, FALSE, TRUE);
  189. // A negative offset means the list ends here.
  190. if (Offset >= 0)
  191. {
  192. // Emit the reloc.
  193. if (!(EmitCompressedRelocFromActualOffset (Section, Offset - LastOffset)))
  194. return FALSE;
  195. }
  196. }
  197. }
  198. return EmitCompressedReloc (Section, -1);
  199. }
  200. }
  201. // Append relocation entries in the format required by the TIGCCLIB relocation
  202. // code. If TargetSection is NULL, append all relocation entries that point to
  203. // unhandled sections. Otherwise, append all relocation entries pointing to this
  204. // section.
  205. // Warning: Inserting relocs is special: Since the relocs are changed
  206. // during the process, they can be inserted only once.
  207. BOOLEAN InsertCompressedRelocs (SECTION *Section, SECTION *TargetSection, SECTION *MergedSection, const LOCATION *Reference)
  208. {
  209. // Initialize user data for list model.
  210. RELOC_USER_DATA UserData = {TargetSection};
  211. // If a target section is specified, it is essential now, and it may
  212. // not be modified any more.
  213. if (TargetSection)
  214. TargetSection->Frozen = TargetSection->Essential = TRUE;
  215. else
  216. // Do code optimizations now, since this might reduce the number
  217. // of relocs. If a target section was specified, this is pointless,
  218. // as relocs into a separate section can never be optimized away.
  219. FixCode (Section->Parent);
  220. // Apply the format documented in _compressed_format_relocs.s.
  221. if (!(EmitCompressedFormatRelocs ((LIST_MODEL *) RelocListModel, MergedSection, Reference, &UserData, Section)))
  222. return FALSE;
  223. // If a target section was specified, and its Handled flag was not
  224. // set yet, now setting it is probably correct.
  225. if (TargetSection)
  226. TargetSection->Handled = TRUE;
  227. return TRUE;
  228. }
  229. // Append relocation entries in the format required by the TIGCCLIB relocation
  230. // code, using InsertCompressedRelocs. If TargetSection is NULL, output an empty
  231. // relocation table. Otherwise, append all relocation entries pointing to this
  232. // section.
  233. // Warning: Inserting relocs is special: Since the relocs are changed
  234. // during the process, they can be inserted only once.
  235. BOOLEAN InsertCompressedSectionRefs (SECTION *Section, SECTION *TargetSection, SECTION *MergedSection, const LOCATION *Reference)
  236. {
  237. if (TargetSection)
  238. return InsertCompressedRelocs (Section, TargetSection, MergedSection, Reference);
  239. else
  240. return (AllocateSpaceInSection (Section, 1) != NULL);
  241. }
  242. // Append ROM calls in the format required by the TIGCCLIB relocation code.
  243. BOOLEAN InsertCompressedROMCalls (SECTION *Section, SECTION *MergedSection, const LOCATION *Reference)
  244. {
  245. PROGRAM *Program = Section->Parent;
  246. // Initialize user data for list model.
  247. ROM_CALL_USER_DATA UserData = {NULL, 0, -1};
  248. // Allocate space for dynamic user data.
  249. if (!(UserData.ROMFunctions = calloc (Program->HighestROMCall + 1, sizeof (ROM_CALL_FUNCTION_DATA))))
  250. {
  251. Error (NULL, "Out of memory while inserting ROM calls with compressed relocs.");
  252. return FALSE;
  253. }
  254. {
  255. BOOLEAN Result = TRUE;
  256. // Go through all ROM calls and increment the appropriate counters.
  257. COUNT ROMRelocCount = GetSectionItemCount ((LIST_MODEL *) ROMCallListModel, MergedSection ? : Section, &UserData);
  258. // If no ROM calls are used, do not output anything but the final null-terminator.
  259. if (ROMRelocCount > 0)
  260. {
  261. // Apply the format documented in _compressed_format_rom_calls.s.
  262. OFFSET LastFunction = -1;
  263. for (UserData.CurFunction = 0; UserData.CurFunction <= Program->HighestROMCall; UserData.CurFunction++)
  264. {
  265. if (UserData.ROMFunctions[UserData.CurFunction].RelocCount)
  266. {
  267. // Emit the function number as a compressed offset.
  268. // Yes, the offset is intentionally integrated into the table that follows!
  269. OFFSET FunctionOffset = UserData.CurFunction - (LastFunction + 1);
  270. if (!(EmitCompressedReloc (Section, FunctionOffset)))
  271. {
  272. Result = FALSE;
  273. break;
  274. }
  275. LastFunction = UserData.CurFunction;
  276. // Emit all ROM calls using this function.
  277. if (!(EmitCompressedFormatRelocs ((LIST_MODEL *) ROMCallListModel, MergedSection, Reference, &UserData, Section)))
  278. {
  279. Result = FALSE;
  280. break;
  281. }
  282. }
  283. }
  284. }
  285. // Output the final null-terminator.
  286. if (!(AppendI1ToSection (Section, 0)))
  287. Result = FALSE;
  288. // Free the extra information.
  289. free (UserData.ROMFunctions);
  290. return Result;
  291. }
  292. }
  293. // Emit a compressed index in PreOs format. Return TRUE on success, FALSE on
  294. // failure. This is NOT the same format as the compressed relocs!
  295. static BOOLEAN EmitPreOsCompressedIndex (SECTION *Section, COUNT LastIndex, COUNT Index)
  296. {
  297. #define AppendI1(i1) ({if (!AppendI1ToSection (Section, (i1))) return FALSE;})
  298. #define AppendI2(i2) ({if (!AppendI2ToSection (Section, (i2))) return FALSE;})
  299. OFFSET Offset = Index - (LastIndex + 1);
  300. if (Offset < 0)
  301. {
  302. // The computed offset must be nonnegative (positive or zero).
  303. Error (NULL, "Invalid index sequence during PreOs compressed relocs.");
  304. return FALSE;
  305. }
  306. else
  307. {
  308. if (Offset <= 253)
  309. {
  310. // Offsets in the range 0 .. 253 are encoded as a single byte.
  311. AppendI1 (Offset);
  312. }
  313. else if (Offset <= (254 + 255))
  314. {
  315. // Offsets in the range 254+0 .. 254+255 are encoded as 2 bytes.
  316. AppendI1 (254);
  317. AppendI1 (Offset - 254);
  318. }
  319. else
  320. {
  321. // For offsets larger than 254+255, we don't encode the offset, but
  322. // the actual index, in a 3-byte encoding.
  323. AppendI1 (255);
  324. AppendI2 (Index);
  325. }
  326. }
  327. #undef AppendI1
  328. #undef AppendI2
  329. return TRUE;
  330. }
  331. // Append the section size and relocs to the specified section in the
  332. // format required by PreOS.
  333. // Warning: Inserting relocs is special: Since the relocs are changed
  334. // during the process, they can be inserted only once.
  335. BOOLEAN InsertPreOSSectionRefs (SECTION *Section, SECTION *TargetSection, SECTION *MergedSection, const LOCATION *Reference)
  336. {
  337. if (TargetSection)
  338. {
  339. // Initialize user data for list model.
  340. RELOC_USER_DATA UserData = {TargetSection};
  341. // Target size. Round up to the next multiple of 4, and output the size
  342. // divided by 4.
  343. if (!(AppendI2ToSection (Section, (TargetSection->Size + 3) >> 2)))
  344. return FALSE;
  345. // Apply the format documented in _preos_program_header.s.
  346. return EmitCompressedFormatRelocs ((LIST_MODEL *) RelocListModel, MergedSection, Reference, &UserData, Section);
  347. }
  348. else
  349. {
  350. // Target size:
  351. return (AllocateSpaceInSection (Section, 2) != NULL);
  352. // The empty relocation table can be omitted.
  353. }
  354. }
  355. // Append ROM calls in the format required by PreOs.
  356. BOOLEAN InsertPreOsROMCalls (SECTION *Section, SECTION *MergedSection, const LOCATION *Reference)
  357. {
  358. PROGRAM *Program = Section->Parent;
  359. // Initialize user data for list model.
  360. ROM_CALL_USER_DATA UserData = {NULL, 0, -1};
  361. // Allocate space for dynamic user data.
  362. if (!(UserData.ROMFunctions = calloc (Program->HighestROMCall + 1, sizeof (ROM_CALL_FUNCTION_DATA))))
  363. {
  364. Error (NULL, "Out of memory while inserting ROM calls with compressed relocs.");
  365. return FALSE;
  366. }
  367. {
  368. BOOLEAN Result = TRUE;
  369. #define EmitIndex(oldidx,idx) ({if (!EmitPreOsCompressedIndex (Section, (oldidx), (idx))) { Result = FALSE; goto ROMCallsOutOfMem; } })
  370. // Go through all ROM calls and increment the appropriate counters.
  371. COUNT ROMRelocCount = GetItemCount ((LIST_MODEL *) ROMCallListModel, Program, NULL, &UserData);
  372. // If no ROM calls are used, output an empty table.
  373. if (!ROMRelocCount)
  374. {
  375. EmitIndex (-1, 0);
  376. }
  377. else
  378. {
  379. // Apply the format documented in _preos_program_header.s.
  380. OFFSET LastFunction = -1;
  381. // Output the number of functions used.
  382. EmitIndex (-1, UserData.ROMFunctionCount);
  383. for (UserData.CurFunction = 0; UserData.CurFunction <= Program->HighestROMCall; UserData.CurFunction++)
  384. {
  385. if (UserData.ROMFunctions[UserData.CurFunction].RelocCount)
  386. {
  387. // Output the current function number.
  388. EmitIndex (LastFunction, UserData.CurFunction);
  389. LastFunction = UserData.CurFunction;
  390. // Emit all ROM calls using this function.
  391. if (!(EmitCompressedFormatRelocs ((LIST_MODEL *) ROMCallListModel, MergedSection, Reference, &UserData, Section)))
  392. {
  393. Result = FALSE;
  394. goto ROMCallsOutOfMem;
  395. }
  396. }
  397. }
  398. }
  399. #undef EmitIndex
  400. ROMCallsOutOfMem:
  401. // Free the extra information.
  402. free (UserData.ROMFunctions);
  403. return FALSE;
  404. }
  405. }
  406. // Append RAM calls in the format required by PreOs.
  407. BOOLEAN InsertPreOsRAMCalls (SECTION *Section, SECTION *MergedSection, const LOCATION *Reference)
  408. {
  409. PROGRAM *Program = Section->Parent;
  410. BOOLEAN Result = TRUE;
  411. // Initialize user data for list model.
  412. RAM_CALL_USER_DATA UserData = {{{NULL, 0}, {NULL, 0}, {NULL, 0}, {NULL, 0}}, 0, RT_ALL_TYPES, -1};
  413. // Allocate space for dynamic user data.
  414. RAM_CALL_TYPE_DATA *CurType = UserData.RAMTypes;
  415. RAM_CALL_TYPE LoopType;
  416. for (LoopType = 0; LoopType < RAM_CALL_TYPE_COUNT; LoopType++, CurType++)
  417. {
  418. if (!(CurType->Functions = calloc (Program->HighestRAMCall + 1, sizeof (RAM_CALL_FUNCTION_DATA))))
  419. {
  420. Error (NULL, "Out of memory while inserting RAM calls with compressed relocs.");
  421. Result = FALSE;
  422. goto RAMCallsOutOfMem;
  423. }
  424. }
  425. {
  426. #define EmitIndex(oldidx,idx) ({if (!EmitPreOsCompressedIndex (Section, (oldidx), (idx))) { Result = FALSE; goto RAMCallsOutOfMem; } })
  427. // Go through all RAM calls and increment the appropriate counters.
  428. COUNT RAMRelocCount = GetItemCount ((LIST_MODEL *) RAMCallListModel, Program, NULL, &UserData);
  429. // If no RAM calls are used, output an empty table.
  430. if (!RAMRelocCount)
  431. {
  432. EmitIndex (-1, 0);
  433. }
  434. else
  435. {
  436. // Apply the format documented in _preos_program_header.s.
  437. OFFSET LastFunction = -1;
  438. // Output the number of functions used.
  439. EmitIndex (-1, UserData.RAMFunctionCount);
  440. // For each possible RAM call type...
  441. for (UserData.CurType = 0; UserData.CurType < RAM_CALL_TYPE_COUNT; UserData.CurType++)
  442. {
  443. // Check if the type has been used.
  444. if (UserData.RAMTypes[UserData.CurType].FunctionCount)
  445. {
  446. // Gather information about the type.
  447. SIZE TypeSize = ((UserData.CurType == RT_RAM_CALL_2) || (UserData.CurType == RT_EXTRA_RAM_2) ? 2 : 4);
  448. BOOLEAN TypeExtraRAM = (UserData.CurType == RT_EXTRA_RAM_4) || (UserData.CurType == RT_EXTRA_RAM_2);
  449. I2 TypeFlags = 0;
  450. if (TypeSize < 4)
  451. TypeFlags |= (1 << 15);
  452. if (TypeExtraRAM)
  453. TypeFlags |= (1 << 14);
  454. // For each possible RAM function number...
  455. for (UserData.CurFunction = 0; UserData.CurFunction <= Program->HighestRAMCall; UserData.CurFunction++)
  456. {
  457. // Check if a RAM function of this type and number has been used.
  458. if (UserData.RAMTypes[UserData.CurType].Functions[UserData.CurFunction].RelocCount)
  459. {
  460. // Output the type and number.
  461. COUNT RAMCallNumber = UserData.CurFunction | TypeFlags;
  462. EmitIndex (LastFunction, RAMCallNumber);
  463. LastFunction = RAMCallNumber;
  464. // Emit all RAM calls using this function.
  465. if (!(EmitCompressedFormatRelocs ((LIST_MODEL *) RAMCallListModel, MergedSection, Reference, &UserData, Section)))
  466. {
  467. Result = FALSE;
  468. goto RAMCallsOutOfMem;
  469. }
  470. }
  471. }
  472. }
  473. }
  474. }
  475. #undef EmitIndex
  476. RAMCallsOutOfMem:
  477. // Free the extra information.
  478. for (UserData.CurType = 0; UserData.CurType < RAM_CALL_TYPE_COUNT; UserData.CurType++)
  479. {
  480. RAM_CALL_FUNCTION_DATA *Functions = UserData.RAMTypes[UserData.CurType].Functions;
  481. if (Functions)
  482. free (Functions);
  483. }
  484. }
  485. return Result;
  486. }
  487. // Append libraries and library calls in the format required by PreOs.
  488. BOOLEAN InsertPreOsLibraries (SECTION *Section, SECTION *MergedSection, const LOCATION *Reference)
  489. {
  490. PROGRAM *Program = Section->Parent;
  491. // Output an empty table if no libraries are referenced.
  492. if (IsEmpty (Program->Libraries))
  493. return (AppendI1ToSection (Section, 0)); // library count
  494. else
  495. {
  496. BOOLEAN Result = TRUE;
  497. // Initialize user data for list model.
  498. LIB_CALL_USER_DATA UserData = {0, NULL, 0, 0, NULL, -1, -1};
  499. if (InitializeLibCallUserData (&UserData, Program))
  500. {
  501. #define AppendI1(i1) ({if (!AppendI1ToSection (Section, (i1))) { Result = FALSE; goto PreOsLibsOutOfMem; } })
  502. #define EmitIndex(oldidx,idx) ({if (!EmitPreOsCompressedIndex (Section, (oldidx), (idx))) { Result = FALSE; goto PreOsLibsOutOfMem; } })
  503. // Go through all library calls and increment the appropriate counters.
  504. COUNT LibRelocCount = GetItemCount ((LIST_MODEL *) LibCallListModel, Program, MergedSection, &UserData);
  505. // Output an empty table if no libraries are referenced.
  506. if (!LibRelocCount)
  507. {
  508. AppendI1 (0); // library count
  509. }
  510. else
  511. {
  512. // Pointer to the inserted data.
  513. I1 *NewData;
  514. // The number of requested libraries.
  515. COUNT LibCount = UserData.UsedLibCount;
  516. AppendI1 (LibCount);
  517. // Apply the format documented in _preos_program_header.s.
  518. // Allocate space for the library names.
  519. NewData = AllocateSpaceInSection (Section, 10 * UserData.UsedLibCount);
  520. // Now handle the library names.
  521. if (NewData)
  522. {
  523. // For each referenced library...
  524. LIB_DATA *CurLib = UserData.Libs;
  525. for (UserData.CurLib = 0; UserData.CurLib < UserData.LibCount; UserData.CurLib++, CurLib++)
  526. {
  527. if (CurLib->FunctionCount)
  528. {
  529. // Output its name.
  530. if (strlen (CurLib->Lib->Name) > 8)
  531. Warning (Section->FileName, "Library name `%s' too long; cutting off at 8th character.", CurLib->Lib->Name);
  532. strncpy (NewData, CurLib->Lib->Name, 8);
  533. WriteTI1 (*((TI1 *) (NewData + 9)), CurLib->Lib->Version);
  534. NewData += 10;
  535. }
  536. }
  537. }
  538. else
  539. {
  540. Error (NULL, "Out of memory while inserting libraries with compressed relocs.");
  541. Result = FALSE;
  542. goto PreOsLibsOutOfMem;
  543. }
  544. {
  545. // For each referenced library...
  546. LIB_DATA *CurLib = UserData.Libs;
  547. for (UserData.CurLib = 0; UserData.CurLib < UserData.LibCount; UserData.CurLib++, CurLib++)
  548. {
  549. if (CurLib->FunctionCount)
  550. {
  551. OFFSET LastFunction = -1;
  552. // Output the number of exports used.
  553. EmitIndex (-1, CurLib->FunctionCount - 1);
  554. // For each referenced export...
  555. for (UserData.CurFunction = 0; UserData.CurFunction <= CurLib->Lib->Highest; UserData.CurFunction++)
  556. {
  557. if (CurLib->Functions[UserData.CurFunction].RelocCount)
  558. {
  559. // Output the export number.
  560. EmitIndex (LastFunction, UserData.CurFunction);
  561. LastFunction = UserData.CurFunction;
  562. // Emit all library calls using this export.
  563. if (!(EmitCompressedFormatRelocs ((LIST_MODEL *) LibCallListModel, MergedSection, Reference, &UserData, Section)))
  564. {
  565. Result = FALSE;
  566. goto PreOsLibsOutOfMem;
  567. }
  568. }
  569. }
  570. }
  571. }
  572. }
  573. }
  574. }
  575. else
  576. Result = FALSE;
  577. PreOsLibsOutOfMem:
  578. // Free the extra information.
  579. FinalizeLibCallUserData (&UserData);
  580. #undef AppendI1
  581. #undef EmitIndex
  582. return Result;
  583. }
  584. }
  585. // The reference address used for the compressed relocation tables in PreOs.
  586. #define PREOS_BASE_ADDR 36
  587. // Append import tables and relocation entries in the format required by PreOs.
  588. // In order: library imports, ROM calls, RAM calls, relocs, BSS references. All
  589. // in one stream, pointed to by a single pointer.
  590. // Warning: Inserting relocs is special: Since the relocs are changed
  591. // during the process, they can be inserted only once.
  592. BOOLEAN InsertPreOsCompressedTables (SECTION *Section)
  593. {
  594. PROGRAM *Program = Section->Parent;
  595. SECTION *MergedSection = Program->MainSection;
  596. LOCATION Reference = {Program->EntryPoint.Symbol, Program->EntryPoint.SymbolName, Program->EntryPoint.Offset + PREOS_BASE_ADDR, FALSE};
  597. // FIXME: Remove as soon as specification is not preliminary any more.
  598. Warning (NULL, "Encoding relocation tables according to a PRELIMINARY specification!");
  599. return (InsertPreOsLibraries (Section, MergedSection, &Reference)
  600. && InsertPreOsROMCalls (Section, MergedSection, &Reference)
  601. && InsertPreOsRAMCalls (Section, MergedSection, &Reference)
  602. && InsertCompressedRelocs (Section, NULL, MergedSection, &Reference)
  603. && InsertPreOSSectionRefs (Section, Program->BSSSection, MergedSection, &Reference));
  604. }
  605. #ifdef FARGO_SUPPORT
  606. // Append BSS relocation entries in the format required by Fargo 0.2.1. Append
  607. // all relocation entries pointing to the BSS section.
  608. // Warning: Inserting relocs is special: Since the relocs are changed
  609. // during the process, they can be inserted only once.
  610. BOOLEAN InsertFargo021SectionRefs (SECTION *Section, SECTION *TargetSection, SECTION *MergedSection, const LOCATION *Reference)
  611. {
  612. if (TargetSection)
  613. {
  614. // Initialize user data for list model.
  615. RELOC_USER_DATA UserData = {TargetSection};
  616. if (!(AppendI2ToSection (Section, TargetSection->Size)))
  617. return FALSE;
  618. // Apply the format documented in _fargo021_program_header.s.
  619. return EmitCompressedFormatRelocs ((LIST_MODEL *) RelocListModel, MergedSection, Reference, &UserData, Section);
  620. }
  621. else
  622. return (AllocateSpaceInSection (Section, 2) != NULL);
  623. }
  624. // Append library calls in the format required by Fargo 0.2.1.
  625. BOOLEAN InsertFargo021Libraries (SECTION *Section, SECTION *MergedSection, const LOCATION *Reference)
  626. {
  627. PROGRAM *Program = Section->Parent;
  628. // Output an empty table if no libraries are referenced.
  629. if (IsEmpty (Program->Libraries))
  630. return (AllocateSpaceInSection (Section, 2) != NULL);
  631. else
  632. {
  633. BOOLEAN Result = TRUE;
  634. // Initialize user data for list model.
  635. LIB_CALL_USER_DATA UserData = {0, NULL, 0, 0, NULL, -1, -1};
  636. if (InitializeLibCallUserData (&UserData, Program))
  637. {
  638. // Go through all library calls and increment the appropriate counters.
  639. COUNT LibRelocCount = GetItemCount ((LIST_MODEL *) LibCallListModel, Program, NULL, &UserData);
  640. // Output an empty table if no libraries are referenced.
  641. if (!LibRelocCount)
  642. {
  643. if (!(AllocateSpaceInSection (Section, 2)))
  644. Result = FALSE;
  645. }
  646. else
  647. {
  648. #define AppendI1(i1) ({if (!AppendI1ToSection (Section, (i1))) { Result = FALSE; goto Fargo021LibsOutOfMem; } })
  649. #define AppendI2(i2) ({if (!AppendI2ToSection (Section, (i2))) { Result = FALSE; goto Fargo021LibsOutOfMem; } })
  650. // Pointer to the inserted data.
  651. I1 *NewData;
  652. SIZE SizeToAllocate;
  653. I1 *LibName;
  654. // The number of requested libraries.
  655. COUNT LibCount = UserData.UsedLibCount;
  656. // The placeholder for the library names.
  657. OFFSET LibNamesLocation;
  658. AppendI2 (LibCount);
  659. LibNamesLocation = Section->Size;
  660. AppendI2 (0);
  661. // Apply the format documented in _fargo021_program_header.s.
  662. {
  663. // For each referenced library...
  664. LIB_DATA *CurLib = UserData.Libs;
  665. for (UserData.CurLib = 0; UserData.CurLib < UserData.LibCount; UserData.CurLib++, CurLib++)
  666. {
  667. if (CurLib->FunctionCount)
  668. {
  669. OFFSET LastFunction = -1;
  670. // For each referenced export...
  671. for (UserData.CurFunction = 0; UserData.CurFunction <= CurLib->Lib->Highest; UserData.CurFunction++)
  672. {
  673. if (CurLib->Functions[UserData.CurFunction].RelocCount)
  674. {
  675. // Output the export number.
  676. OFFSET FunctionOffset = UserData.CurFunction - LastFunction;
  677. // Emit the compressed offset. This is NOT the same
  678. // format as the compressed relocs!
  679. if (FunctionOffset < 128)
  680. AppendI1 (FunctionOffset);
  681. else
  682. AppendI2 (0x8000 + FunctionOffset);
  683. LastFunction = UserData.CurFunction;
  684. // Emit all library calls using this export.
  685. if (!(EmitCompressedFormatRelocs ((LIST_MODEL *) LibCallListModel, MergedSection, Reference, &UserData, Section)))
  686. {
  687. Result = FALSE;
  688. goto Fargo021LibsOutOfMem;
  689. }
  690. }
  691. }
  692. AppendI1 (0);
  693. }
  694. }
  695. // Add the redundant null-terminator.
  696. AppendI1 (0);
  697. // Allocate space for the library names.
  698. SizeToAllocate = 0;
  699. // For each referenced library...
  700. CurLib = UserData.Libs;
  701. for (UserData.CurLib = 0; UserData.CurLib < UserData.LibCount; UserData.CurLib++, CurLib++)
  702. {
  703. if (CurLib->FunctionCount)
  704. SizeToAllocate += strlen (CurLib->Lib->Name) + 1;
  705. }
  706. NewData = AllocateSpaceInSection (Section, SizeToAllocate);
  707. LibName = NewData;
  708. // Now handle the library names.
  709. if (NewData)
  710. {
  711. // Create a new reloc at the given location, pointing to
  712. // the location of the library names.
  713. {
  714. I1 *LibNamePlaceholder = Section->Data + LibNamesLocation;
  715. RELOC *Reloc = CreateProgramRelativeReloc (Section, &LibNamePlaceholder, Section, LibName - Section->Data, 2);
  716. if (!Reloc)
  717. {
  718. Error (NULL, "Out of memory while inserting libraries with compressed relocs.");
  719. Result = FALSE;
  720. goto Fargo021LibsOutOfMem;
  721. }
  722. }
  723. // For each referenced library...
  724. CurLib = UserData.Libs;
  725. for (UserData.CurLib = 0; UserData.CurLib < UserData.LibCount; UserData.CurLib++, CurLib++)
  726. {
  727. if (CurLib->FunctionCount)
  728. {
  729. // Output its name.
  730. strcpy (LibName, CurLib->Lib->Name);
  731. LibName += strlen (CurLib->Lib->Name) + 1;
  732. }
  733. }
  734. }
  735. else
  736. {
  737. Error (NULL, "Out of memory while inserting libraries with compressed relocs.");
  738. Result = FALSE;
  739. }
  740. }
  741. }
  742. }
  743. else
  744. Result = FALSE;
  745. Fargo021LibsOutOfMem:
  746. // Free the extra information.
  747. FinalizeLibCallUserData (&UserData);
  748. return Result;
  749. }
  750. #undef AppendI1
  751. #undef AppendI2
  752. }
  753. #endif /* FARGO_SUPPORT */
  754. // Emit an mlink-format compressed reloc. If Offset is -1, end the relocation
  755. // table. Return TRUE on success, FALSE on failure.
  756. static BOOLEAN EmitMlinkReloc (SECTION *Section, OFFSET Offset)
  757. {
  758. #define AppendI1(i1) ({if (!AppendI1ToSection (Section, (i1))) return FALSE;})
  759. #define AppendI2(i2) ({if (!AppendI2ToSection (Section, (i2))) return FALSE;})
  760. if (Offset == -1)
  761. {
  762. // End the relocation table.
  763. AppendI1(0);
  764. }
  765. else
  766. {
  767. if (Offset < 128)
  768. {
  769. // We have 1 byte.
  770. AppendI1 (Offset + 0x80);
  771. }
  772. else if (Offset < 16384)
  773. {
  774. // We have 2 bytes.
  775. AppendI1 (Offset >> 7);
  776. AppendI1 ((Offset & 0x7F) + 0x80);
  777. }
  778. else if (Offset < 2097152)
  779. {
  780. // We have 3 bytes.
  781. AppendI1 (Offset >> 14);
  782. AppendI1 ((Offset >> 7) & 0x7F);
  783. AppendI1 ((Offset & 0x7F) + 0x80);
  784. }
  785. else
  786. Error (Section->FileName, "Offset `%ld' for mlink-format reloc doesn't fit into 3 bytes.", (long) Offset);
  787. }
  788. #undef AppendI1
  789. #undef AppendI2
  790. return TRUE;
  791. }
  792. // Emit an mlink-format compressed reloc given the true offset between the 2
  793. // relocs. Compute the offset as used in the compressed reloc table or give
  794. // an error message if
  795. // it isn't representable. Call EmitCompressedReloc with the computed offset.
  796. // Return TRUE on success, FALSE on failure.
  797. static BOOLEAN EmitMlinkRelocFromActualOffset (SECTION *Section, OFFSET Offset)
  798. {
  799. if ((Offset > 0) && (Offset & 1))
  800. {
  801. Error (Section->FileName, "Odd offset `%ld' between 2 absolute relocs. Even offset needed.", (long) Offset);
  802. return FALSE;
  803. }
  804. if (Offset < 0)
  805. {
  806. Error (Section->FileName, "Invalid internal reloc sorting order (offset `-0x%lx', need positive offset).",
  807. -Offset);
  808. return FALSE;
  809. }
  810. return EmitMlinkReloc (Section, Offset >> 1);
  811. }
  812. // Emit a reloc table in mlink compressed format for the items enumerated in the
  813. // list model specified by Model.
  814. static BOOLEAN EmitMlinkFormatRelocs (LIST_MODEL *Model, SECTION *SourceSection, const LOCATION *SourceBase, void *UserData, SECTION *Section)
  815. {
  816. if (!SourceSection)
  817. SourceSection = Section;
  818. SourceSection->Frozen = TRUE;
  819. {
  820. void *NextItem = NULL;
  821. OFFSET Offset;
  822. // Output the first item in the list...
  823. // Output the target offset, and get the reloc's location.
  824. Offset = Model (SourceSection, &NextItem, UserData, FALSE, TRUE);
  825. // A return value < 0 indicates that the list was empty.
  826. if (Offset >= 0)
  827. {
  828. OFFSET BaseAddress = GetLocationOffset (SourceSection, SourceBase);
  829. if (BaseAddress & 1)
  830. {
  831. Error (Section->FileName, "Invalid base address `0x%lx'. Even base address needed.", BaseAddress);
  832. return FALSE;
  833. }
  834. if (Offset & 1)
  835. {
  836. Error (Section->FileName, "Odd offset between base address `0x%lx' and first absolute reloc `0x%lx'. Even offset needed.", BaseAddress, Offset);
  837. return FALSE;
  838. }
  839. if (Offset < BaseAddress)
  840. {
  841. Error (Section->FileName, "Cannot emit absolute reloc located at `0x%lx' before base address.", Offset);
  842. return FALSE;
  843. }
  844. // Emit the reloc.
  845. if (!(EmitCompressedReloc (Section, (Offset - BaseAddress) >> 1)))
  846. return FALSE;
  847. // Output the remaining items in the list...
  848. while (NextItem)
  849. {
  850. // Save the previous offset.
  851. OFFSET LastOffset = Offset;
  852. // Output the target offset, and get the reloc's location.
  853. Offset = Model (SourceSection, &NextItem, UserData, FALSE, TRUE);
  854. // A negative offset means the list ends here.
  855. if (Offset >= 0)
  856. {
  857. // Emit the reloc.
  858. if (!(EmitMlinkRelocFromActualOffset (Section, Offset - LastOffset)))
  859. return FALSE;
  860. }
  861. }
  862. }
  863. return EmitMlinkReloc (Section, -1);
  864. }
  865. }
  866. // Append mlink-style relocation entries in the format required by the TIGCCLIB
  867. // relocation code. If TargetSection is NULL, append all relocation entries that
  868. // point to unhandled sections. Otherwise, append all relocation entries
  869. // pointing to this section.
  870. // Warning: Inserting relocs is special: Since the relocs are changed
  871. // during the process, they can be inserted only once.
  872. BOOLEAN InsertMlinkRelocs (SECTION *Section, SECTION *TargetSection, SECTION *MergedSection, const LOCATION *Reference)
  873. {
  874. // Initialize user data for list model.
  875. RELOC_USER_DATA UserData = {TargetSection};
  876. // If a target section is specified, it is essential now, and it may
  877. // not be modified any more.
  878. if (TargetSection)
  879. TargetSection->Frozen = TargetSection->Essential = TRUE;
  880. else
  881. // Do code optimizations now, since this might reduce the number
  882. // of relocs. If a target section was specified, this is pointless,
  883. // as relocs into a separate section can never be optimized away.
  884. FixCode (Section->Parent);
  885. // Apply the format documented in _mlink_format_relocs.s.
  886. if (!(EmitMlinkFormatRelocs ((LIST_MODEL *) RelocListModel, MergedSection, Reference, &UserData, Section)))
  887. return FALSE;
  888. // If a target section was specified, and its Handled flag was not
  889. // set yet, now setting it is probably correct.
  890. if (TargetSection)
  891. TargetSection->Handled = TRUE;
  892. return TRUE;
  893. }
  894. // Append mlink-style relocation entries in the format required by the TIGCCLIB
  895. // relocation code, using InsertCompressedRelocs. If TargetSection is NULL,
  896. // output an empty relocation table. Otherwise, append all relocation entries
  897. // pointing to this section.
  898. // Warning: Inserting relocs is special: Since the relocs are changed
  899. // during the process, they can be inserted only once.
  900. BOOLEAN InsertMlinkSectionRefs (SECTION *Section, SECTION *TargetSection, SECTION *MergedSection, const LOCATION *Reference)
  901. {
  902. if (TargetSection)
  903. return InsertMlinkRelocs (Section, TargetSection, MergedSection, Reference);
  904. else
  905. return (AllocateSpaceInSection (Section, 1) != NULL);
  906. }
  907. // Append ROM calls in the mlink-style format required by the TIGCCLIB
  908. // relocation code.
  909. BOOLEAN InsertMlinkROMCalls (SECTION *Section, SECTION *MergedSection, const LOCATION *Reference)
  910. {
  911. PROGRAM *Program = Section->Parent;
  912. // Initialize user data for list model.
  913. ROM_CALL_USER_DATA UserData = {NULL, 0, -1};
  914. // Allocate space for dynamic user data.
  915. if (!(UserData.ROMFunctions = calloc (Program->HighestROMCall + 1, sizeof (ROM_CALL_FUNCTION_DATA))))
  916. {
  917. Error (NULL, "Out of memory while inserting ROM calls with mlink-format relocs.");
  918. return FALSE;
  919. }
  920. {
  921. BOOLEAN Result = TRUE;
  922. // Go through all ROM calls and increment the appropriate counters.
  923. COUNT ROMRelocCount = GetSectionItemCount ((LIST_MODEL *) ROMCallListModel, MergedSection ? : Section, &UserData);
  924. // If no ROM calls are used, do not output anything but the final null-terminator.
  925. if (ROMRelocCount > 0)
  926. {
  927. // Apply the format documented in _compressed_format_rom_calls.s.
  928. OFFSET LastFunction = -1;
  929. for (UserData.CurFunction = 0; UserData.CurFunction <= Program->HighestROMCall; UserData.CurFunction++)
  930. {
  931. if (UserData.ROMFunctions[UserData.CurFunction].RelocCount)
  932. {
  933. // Emit the function number as a compressed offset.
  934. OFFSET FunctionOffset = UserData.CurFunction - LastFunction;
  935. if (!(EmitMlinkReloc (Section, FunctionOffset)))
  936. {
  937. Result = FALSE;
  938. break;
  939. }
  940. LastFunction = UserData.CurFunction;
  941. // Emit all ROM calls using this function.
  942. if (!(EmitMlinkFormatRelocs ((LIST_MODEL *) ROMCallListModel, MergedSection, Reference, &UserData, Section)))
  943. {
  944. Result = FALSE;
  945. break;
  946. }
  947. }
  948. }
  949. }
  950. // Output the final null-terminator.
  951. if (!(AppendI1ToSection (Section, 0)))
  952. Result = FALSE;
  953. // Free the extra information.
  954. free (UserData.ROMFunctions);
  955. return Result;
  956. }
  957. }