]> git.sur5r.net Git - cc65/blob - src/ar65/library.c
Added a method to write variable sized unsigned values. Use this method for
[cc65] / src / ar65 / library.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 library.c                                 */
4 /*                                                                           */
5 /*         Library data structures and helpers for the ar65 archiver         */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2000 Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
12 /* EMail:        uz@musoftware.de                                            */
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 "bitops.h"
42 #include "exprdefs.h"
43 #include "filepos.h"
44 #include "libdefs.h"
45 #include "symdefs.h"
46 #include "xmalloc.h"
47
48 /* ar65 */
49 #include "error.h"
50 #include "global.h"
51 #include "fileio.h"
52 #include "objdata.h"
53 #include "exports.h"
54 #include "library.h"
55
56
57
58 /*****************************************************************************/
59 /*                                   Data                                    */
60 /*****************************************************************************/
61
62
63
64 /* File descriptor for the library file */
65 FILE*                   NewLib = 0;
66 static FILE*            Lib = 0;
67 static const char*      LibName = 0;
68
69 /* The library header */
70 static LibHeader        Header = {
71     LIB_MAGIC,
72     LIB_VERSION
73 };
74
75
76
77 /*****************************************************************************/
78 /*                       Writing file data structures                        */
79 /*****************************************************************************/
80
81
82
83 static void ReadHeader (void)
84 /* Read the header of a library file */
85 {
86     /* Seek to position zero */
87     fseek (Lib, 0, SEEK_SET);
88
89     /* Read the header fields, checking magic and version */
90     Header.Magic   = Read32 (Lib);
91     if (Header.Magic != LIB_MAGIC) {
92         Error ("`%s' is not a valid library file", LibName);
93     }
94     Header.Version = Read16 (Lib);
95     if (Header.Version != LIB_VERSION) {
96         Error ("Wrong data version in `%s'", LibName);
97     }
98     Header.Flags   = Read16 (Lib);
99     Header.IndexOffs = Read32 (Lib);
100 }
101
102
103
104 static void ReadIndexEntry (void)
105 /* Read one entry in the index */
106 {
107     /* Create a new entry and insert it into the list */
108     ObjData* O  = NewObjData ();
109
110     /* Module name/flags/MTime/Start/Size */
111     O->Name     = ReadStr (Lib);
112     O->Flags    = Read16 (Lib);
113     O->MTime    = Read32 (Lib);
114     O->Start    = Read32 (Lib);
115     O->Size     = Read32 (Lib);
116
117     /* Exports */
118     O->ExportSize = Read16 (Lib);
119     O->Exports    = xmalloc (O->ExportSize);
120     ReadData (Lib, O->Exports, O->ExportSize);
121
122     /* Imports */
123     O->ImportSize = Read16 (Lib);
124     O->Imports    = xmalloc (O->ImportSize);
125     ReadData (Lib, O->Imports, O->ImportSize);
126 }
127
128
129
130 static void ReadIndex (void)
131 /* Read the index of a library file */
132 {
133     unsigned Count;
134
135     /* Seek to the start of the index */
136     fseek (Lib, Header.IndexOffs, SEEK_SET);
137
138     /* Read the object file count and calculate the cross ref size */
139     Count = Read16 (Lib);
140
141     /* Read all entries in the index */
142     while (Count--) {
143         ReadIndexEntry ();
144     }
145 }
146
147
148
149 /*****************************************************************************/
150 /*                       Writing file data structures                        */
151 /*****************************************************************************/
152
153
154
155 static void WriteHeader (void)
156 /* Write the header to the library file */
157 {
158     /* Seek to position zero */
159     fseek (NewLib, 0, SEEK_SET);
160
161     /* Write the header fields */
162     Write32 (NewLib, Header.Magic);
163     Write16 (NewLib, Header.Version);
164     Write16 (NewLib, Header.Flags);
165     Write32 (NewLib, Header.IndexOffs);
166 }
167
168
169
170 static void WriteIndexEntry (ObjData* O)
171 /* Write one index entry */
172 {
173     /* Module name/flags/MTime/start/size */
174     WriteStr (NewLib, O->Name);
175     Write16  (NewLib, O->Flags & ~OBJ_HAVEDATA);
176     Write32  (NewLib, O->MTime);
177     Write32  (NewLib, O->Start);
178     Write32  (NewLib, O->Size);
179
180     /* Exports */
181     Write16 (NewLib, O->ExportSize);
182     WriteData (NewLib, O->Exports, O->ExportSize);
183
184     /* Imports */
185     Write16 (NewLib, O->ImportSize);
186     WriteData (NewLib, O->Imports, O->ImportSize);
187 }
188
189
190
191 static void WriteIndex (void)
192 /* Write the index of a library file */
193 {
194     ObjData* O;
195
196     /* Sync I/O in case the last operation was a read */
197     fseek (NewLib, 0, SEEK_CUR);
198
199     /* Remember the current offset in the header */
200     Header.IndexOffs = ftell (NewLib);
201
202     /* Write the object file count */
203     Write16 (NewLib, ObjCount);
204
205     /* Write the object files */
206     O = ObjRoot;
207     while (O) {
208         WriteIndexEntry (O);
209         O = O->Next;
210     }
211 }
212
213
214
215 /*****************************************************************************/
216 /*                             High level stuff                              */
217 /*****************************************************************************/
218
219
220
221 void LibOpen (const char* Name, int MustExist, int NeedTemp)
222 /* Open an existing library and a temporary copy. If MustExist is true, the
223  * old library is expected to exist. If NeedTemp is true, a temporary library
224  * is created.
225  */
226 {
227     /* Remember the name */
228     LibName = xstrdup (Name);
229
230     /* Open the existing library for reading */
231     Lib = fopen (Name, "rb");
232     if (Lib == 0) {
233
234         /* File does not exist */
235         if (MustExist) {
236             Error ("Library `%s' does not exist", Name);
237         } else {
238             Warning ("Library `%s' not found - will be created", Name);
239         }
240
241     } else {
242
243         /* We have an existing file: Read the header */
244         ReadHeader ();
245
246         /* Now read the existing index */
247         ReadIndex ();
248
249     }
250
251     if (NeedTemp) {
252         /* Create the temporary library */
253         NewLib = tmpfile ();
254         if (NewLib == 0) {
255             Error ("Cannot create temporary file: %s", strerror (errno));
256         }
257
258         /* Write a dummy header to the temp file */
259         WriteHeader ();
260     }
261 }
262
263
264
265 unsigned long LibCopyTo (FILE* F, unsigned long Bytes)
266 /* Copy data from F to the temp library file, return the start position in
267  * the temporary library file.
268  */
269 {
270     unsigned char Buf [4096];
271
272     /* Remember the position */
273     unsigned long Pos = ftell (NewLib);
274
275     /* Copy loop */
276     while (Bytes) {
277         unsigned Count = (Bytes > sizeof (Buf))? sizeof (Buf) : Bytes;
278         ReadData (F, Buf, Count);
279         WriteData (NewLib, Buf, Count);
280         Bytes -= Count;
281     }
282
283     /* Return the start position */
284     return Pos;
285 }
286
287
288
289 void LibCopyFrom (unsigned long Pos, unsigned long Bytes, FILE* F)
290 /* Copy data from the library file into another file */
291 {
292     unsigned char Buf [4096];
293
294     /* Seek to the correct position */
295     fseek (Lib, Pos, SEEK_SET);
296
297     /* Copy loop */
298     while (Bytes) {
299         unsigned Count = (Bytes > sizeof (Buf))? sizeof (Buf) : Bytes;
300         ReadData (Lib, Buf, Count);
301         WriteData (F, Buf, Count);
302         Bytes -= Count;
303     }
304 }
305
306
307
308 static unsigned long GetVar (unsigned char** Buf)
309 /* Get a variable sized value from Buf */
310 {
311     unsigned char C;
312     unsigned long V = 0;
313     unsigned Shift = 0;
314     do {
315         /* Read one byte */
316         C = **Buf;
317         ++(*Buf);
318         /* Add this char to the value */
319         V |= ((unsigned long)(C & 0x7F)) << Shift;
320         /* Next value */
321         Shift += 7;
322     } while (C & 0x80);
323
324     /* Return the result */
325     return V;
326 }
327
328
329
330 static void SkipExpr (unsigned char** Buf)
331 /* Skip an expression in Buf */
332 {
333     /* Get the operation and skip it */
334     unsigned char Op = **Buf;
335     ++(*Buf);
336
337     /* Filter leaf nodes */
338     switch (Op) {
339
340         case EXPR_NULL:
341             return;
342
343         case EXPR_LITERAL:
344             /* 32 bit literal value */
345             *Buf += 4;
346             return;
347
348         case EXPR_SYMBOL:
349             /* 16 bit symbol index */
350             *Buf += 2;
351             return;
352
353         case EXPR_SEGMENT:
354             /* 8 bit segment number */
355             *Buf += 1;
356             return;
357     }
358
359     /* What's left are unary and binary nodes */
360     SkipExpr (Buf);             /* Skip left */
361     SkipExpr (Buf);             /* Skip right */
362 }
363
364
365
366 static void SkipFilePos (unsigned char** Buf)
367 /* Skip a file position in Buf */
368 {
369     (void) GetVar (Buf);        /* Line */
370     (void) GetVar (Buf);        /* Col */
371     (void) GetVar (Buf);        /* Name */
372 }
373
374
375
376 static void LibCheckExports (ObjData* O)
377 /* Insert all exports from the given object file into the global list
378  * checking for duplicates.
379  */
380 {
381     /* Get a pointer to the buffer */
382     unsigned char* Exports = O->Exports;
383
384     /* Get the export count */
385     unsigned Count = GetVar (&Exports);
386
387     /* Read the exports */
388     if (Verbose > 1) {
389         printf ("Module `%s' (%u exports):\n", O->Name, Count);
390     }
391     while (Count--) {
392
393         /* Get the export tag */
394         unsigned char Tag = *Exports++;
395
396         /* Next thing is name of symbol */
397         unsigned Len = GetVar (&Exports);
398         char* Name = xmalloc (Len + 1);
399         memcpy (Name, Exports, Len);
400         Name [Len] = '\0';
401         Exports += Len;
402
403         /* Skip value of symbol */
404         if (Tag & EXP_EXPR) {
405             /* Expression tree */
406             SkipExpr (&Exports);
407         } else {
408             /* Constant 32 bit value */
409             Exports += 4;
410         }
411
412         /* Skip the position */
413         SkipFilePos (&Exports);
414
415         /* Insert the name into the hash table */
416         if (Verbose > 1) {
417                 printf ("  %s\n", Name);
418         }
419         ExpInsert (Name, O->Index);
420
421         /* Free the name */
422         xfree (Name);
423     }
424 }
425
426
427
428 void LibClose (void)
429 /* Write remaining data, close both files and copy the temp file to the old
430  * filename
431  */
432 {
433     /* Do we have a temporary library? */
434     if (NewLib) {
435
436         unsigned I;
437         unsigned char Buf [4096];
438         size_t Count;
439
440         /* Index the object files and make an array containing the objects */
441         MakeObjPool ();
442
443         /* Walk through the object file list, inserting exports into the
444          * export list checking for duplicates. Copy any data that is still
445          * in the old library into the new one.
446          */
447         for (I = 0; I < ObjCount; ++I) {
448
449             /* Get a pointer to the object */
450             ObjData* O = ObjPool [I];
451
452             /* Check exports, make global export table */
453             LibCheckExports (O);
454
455             /* Copy data if needed */
456             if ((O->Flags & OBJ_HAVEDATA) == 0) {
457                 /* Data is still in the old library */
458                 fseek (Lib, O->Start, SEEK_SET);
459                 O->Start = ftell (NewLib);
460                 LibCopyTo (Lib, O->Size);
461                 O->Flags |= OBJ_HAVEDATA;
462             }
463         }
464
465         /* Write the index */
466         WriteIndex ();
467
468         /* Write the updated header */
469         WriteHeader ();
470
471         /* Close the file */
472         if (Lib && fclose (Lib) != 0) {
473             Error ("Error closing library: %s", strerror (errno));
474         }
475
476         /* Reopen the library and truncate it */
477         Lib = fopen (LibName, "wb");
478         if (Lib == 0) {
479             Error ("Cannot open library `%s' for writing: %s",
480                    LibName, strerror (errno));
481         }
482
483         /* Copy the new library to the new one */
484         fseek (NewLib, 0, SEEK_SET);
485         while ((Count = fread (Buf, 1, sizeof (Buf), NewLib)) != 0) {
486             if (fwrite (Buf, 1, Count, Lib) != Count) {
487                 Error ("Cannot write to `%s': %s", LibName, strerror (errno));
488             }
489         }
490     }
491
492     /* Close both files */
493     if (Lib && fclose (Lib) != 0) {
494         Error ("Problem closing `%s': %s", LibName, strerror (errno));
495     }
496     if (NewLib && fclose (NewLib) != 0) {
497         Error ("Problem closing temporary library file: %s", strerror (errno));
498     }
499 }
500
501
502