]> git.sur5r.net Git - cc65/blob - src/ld65/bin.c
Corrected indentation - no code change.
[cc65] / src / ld65 / bin.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                   bin.c                                   */
4 /*                                                                           */
5 /*                  Module to handle the raw binary format                   */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1999-2008 Ullrich von Bassewitz                                       */
10 /*               Roemerstrasse 52                                            */
11 /*               D-70794 Filderstadt                                         */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdio.h>
37 #include <string.h>
38 #include <errno.h>
39
40 /* common */
41 #include "print.h"
42 #include "xmalloc.h"
43
44 /* ld65 */
45 #include "bin.h"
46 #include "config.h"
47 #include "exports.h"
48 #include "expr.h"
49 #include "error.h"
50 #include "global.h"
51 #include "fileio.h"
52 #include "lineinfo.h"
53 #include "segments.h"
54 #include "spool.h"
55
56
57
58 /*****************************************************************************/
59 /*                                   Data                                    */
60 /*****************************************************************************/
61
62
63
64 struct BinDesc {
65     unsigned    Undef;          /* Count of undefined externals */
66     FILE*       F;              /* Output file */
67     const char* Filename;       /* Name of output file */
68 };
69
70
71
72 /*****************************************************************************/
73 /*                                   Code                                    */
74 /*****************************************************************************/
75
76
77
78 BinDesc* NewBinDesc (void)
79 /* Create a new binary format descriptor */
80 {
81     /* Allocate memory for a new BinDesc struct */
82     BinDesc* D = xmalloc (sizeof (BinDesc));
83
84     /* Initialize the fields */
85     D->Undef    = 0;
86     D->F        = 0;
87     D->Filename = 0;
88
89     /* Return the created struct */
90     return D;
91 }
92
93
94
95 void FreeBinDesc (BinDesc* D)
96 /* Free a binary format descriptor */
97 {
98     xfree (D);
99 }
100
101
102
103 static unsigned BinWriteExpr (ExprNode* E, int Signed, unsigned Size,
104                               unsigned long Offs attribute ((unused)),
105                               void* Data)
106 /* Called from SegWrite for an expression. Evaluate the expression, check the
107  * range and write the expression value to the file.
108  */
109 {
110     /* There's a predefined function to handle constant expressions */
111     return SegWriteConstExpr (((BinDesc*)Data)->F, E, Signed, Size);
112 }
113
114
115
116 static void PrintBoolVal (const char* Name, int B)
117 /* Print a boolean value for debugging */
118 {
119     Print (stdout, 2, "      %s = %s\n", Name, B? "true" : "false");
120 }
121
122
123
124 static void PrintNumVal (const char* Name, unsigned long V)
125 /* Print a numerical value for debugging */
126 {
127     Print (stdout, 2, "      %s = 0x%lx\n", Name, V);
128 }
129
130
131
132 static void BinWriteMem (BinDesc* D, Memory* M)
133 /* Write the segments of one memory area to a file */
134 {
135     /* Get the start address of this memory area */
136     unsigned long Addr = M->Start;
137
138     /* Get a pointer to the first segment node */
139     MemListNode* N = M->SegList;
140     while (N) {
141
142         int DoWrite;
143
144         /* Get the segment from the list node */
145         SegDesc* S = N->Seg;
146
147         /* Keep the user happy */
148         Print (stdout, 1, "    Writing `%s'\n", GetString (S->Name));
149
150         /* Writes do only occur in the load area and not for BSS segments */
151         DoWrite = (S->Flags & SF_BSS) == 0      &&      /* No BSS segment */
152                    S->Load == M                 &&      /* LOAD segment */
153                    S->Seg->Dumped == 0;                 /* Not already written */
154
155         /* Output debugging stuff */
156         PrintBoolVal ("bss", S->Flags & SF_BSS);
157         PrintBoolVal ("LoadArea", S->Load == M);
158         PrintBoolVal ("Dumped", S->Seg->Dumped);
159         PrintBoolVal ("DoWrite", DoWrite);
160         PrintNumVal  ("Address", Addr);
161         PrintNumVal  ("FileOffs", (unsigned long) ftell (D->F));
162
163         /* Check if we would need an alignment */
164         if (S->Seg->Align > S->Align) {
165             /* Segment itself requires larger alignment than configured
166              * in the linker.
167              */
168             Warning ("Segment `%s' in module `%s' requires larger alignment",
169                      GetString (S->Name), GetObjFileName (S->Seg->AlignObj));
170         }
171
172         /* If this is the run memory area, we must apply run alignment. If
173          * this is not the run memory area but the load memory area (which
174          * means that both are different), we must apply load alignment.
175          * Beware: DoWrite may be true even if this is the run memory area,
176          * because it may be also the load memory area.
177          */
178         if (S->Run == M) {
179
180             /* Handle ALIGN and OFFSET/START */
181             if (S->Flags & SF_ALIGN) {
182                 /* Align the address */
183                 unsigned long Val = (0x01UL << S->Align) - 1;
184                 unsigned long NewAddr = (Addr + Val) & ~Val;
185                 if (DoWrite || (M->Flags & MF_FILL) != 0) {
186                     WriteMult (D->F, M->FillVal, NewAddr - Addr);
187                     PrintNumVal ("SF_ALIGN", NewAddr - Addr);
188                 }
189                 Addr = NewAddr;
190             } else if (S->Flags & (SF_OFFSET | SF_START)) {
191                 unsigned long NewAddr = S->Addr;
192                 if (S->Flags & SF_OFFSET) {
193                     /* It's an offset, not a fixed address, make an address */
194                     NewAddr += M->Start;
195                 }
196                 if (DoWrite || (M->Flags & MF_FILL) != 0) {
197                     WriteMult (D->F, M->FillVal, NewAddr-Addr);
198                     PrintNumVal ("SF_OFFSET", NewAddr - Addr);
199                 }
200                 Addr = NewAddr;
201             }
202
203             /* Relocate line information for this segment */
204             RelocLineInfo (S->Seg);
205
206         } else if (S->Load == M) {
207
208             /* Handle ALIGN_LOAD */
209             if (S->Flags & SF_ALIGN_LOAD) {
210                 /* Align the address */
211                 unsigned long Val = (0x01UL << S->AlignLoad) - 1;
212                 unsigned long NewAddr = (Addr + Val) & ~Val;
213                 if (DoWrite || (M->Flags & MF_FILL) != 0) {
214                     WriteMult (D->F, M->FillVal, NewAddr-Addr);
215                     PrintNumVal ("SF_ALIGN_LOAD", NewAddr - Addr);
216                 }
217                 Addr = NewAddr;
218             }
219
220         }
221
222         /* Now write the segment to disk if it is not a BSS type segment and
223          * if the memory area is the load area.
224          */
225         if (DoWrite) {
226             unsigned long P = ftell (D->F);
227             S->Seg->FillVal = M->FillVal;
228             SegWrite (D->F, S->Seg, BinWriteExpr, D);
229             PrintNumVal ("Wrote", (unsigned long) (ftell (D->F) - P));
230         } else if (M->Flags & MF_FILL) {
231             WriteMult (D->F, M->FillVal, S->Seg->Size);
232             PrintNumVal ("Filled", (unsigned long) S->Seg->Size);
233         }
234
235         /* If this was the load memory area, mark the segment as dumped */
236         if (S->Load == M) {
237             S->Seg->Dumped = 1;
238         }
239
240         /* Calculate the new address */
241         Addr += S->Seg->Size;
242
243         /* Next segment node */
244         N = N->Next;
245     }
246
247     /* If a fill was requested, fill the remaining space */
248     if ((M->Flags & MF_FILL) != 0 && M->FillLevel < M->Size) {
249         unsigned long ToFill = M->Size - M->FillLevel;
250         Print (stdout, 2, "    Filling 0x%lx bytes with 0x%02x\n",
251                ToFill, M->FillVal);
252         WriteMult (D->F, M->FillVal, ToFill);
253         M->FillLevel = M->Size;
254     }
255 }
256
257
258
259 static int BinUnresolved (unsigned Name attribute ((unused)), void* D)
260 /* Called if an unresolved symbol is encountered */
261 {
262     /* Unresolved symbols are an error in binary format. Bump the counter
263      * and return zero telling the caller that the symbol is indeed
264      * unresolved.
265      */
266     ((BinDesc*) D)->Undef++;
267     return 0;
268 }
269
270
271
272 void BinWriteTarget (BinDesc* D, struct File* F)
273 /* Write a binary output file */
274 {
275     Memory* M;
276
277     /* Place the filename in the control structure */
278     D->Filename = GetString (F->Name);
279
280     /* Check for unresolved symbols. The function BinUnresolved is called
281      * if we get an unresolved symbol.
282      */
283     D->Undef = 0;               /* Reset the counter */
284     CheckUnresolvedImports (BinUnresolved, D);
285     if (D->Undef > 0) {
286         /* We had unresolved symbols, cannot create output file */
287         Error ("%u unresolved external(s) found - cannot create output file", D->Undef);
288     }
289
290     /* Open the file */
291     D->F = fopen (D->Filename, "wb");
292     if (D->F == 0) {
293         Error ("Cannot open `%s': %s", D->Filename, strerror (errno));
294     }
295
296     /* Keep the user happy */
297     Print (stdout, 1, "Opened `%s'...\n", D->Filename);
298
299     /* Dump all memory areas */
300     M = F->MemList;
301     while (M) {
302         Print (stdout, 1, "  Dumping `%s'\n", GetString (M->Name));
303         BinWriteMem (D, M);
304         M = M->FNext;
305     }
306
307     /* Close the file */
308     if (fclose (D->F) != 0) {
309         Error ("Cannot write to `%s': %s", D->Filename, strerror (errno));
310     }
311
312     /* Reset the file and filename */
313     D->F        = 0;
314     D->Filename = 0;
315 }
316
317
318
319
320