- Move deallocation of Buffer object to end of routine.
[dragonfly.git] / usr.bin / make / arch.c
1 /*
2  * Copyright (c) 1988, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1989 by Berkeley Softworks
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * @(#)arch.c   8.2 (Berkeley) 1/2/94
39  * $FreeBSD: src/usr.bin/make/arch.c,v 1.15.2.1 2001/02/13 03:13:57 will Exp $
40  * $DragonFly: src/usr.bin/make/arch.c,v 1.28 2005/01/31 21:13:07 okumoto Exp $
41  */
42
43 /*-
44  * arch.c --
45  *      Functions to manipulate libraries, archives and their members.
46  *
47  *      Once again, cacheing/hashing comes into play in the manipulation
48  * of archives. The first time an archive is referenced, all of its members'
49  * headers are read and hashed and the archive closed again. All hashed
50  * archives are kept on a list which is searched each time an archive member
51  * is referenced.
52  *
53  * The interface to this module is:
54  *      Arch_ParseArchive       Given an archive specification, return a list
55  *                              of GNode's, one for each member in the spec.
56  *                              FAILURE is returned if the specification is
57  *                              invalid for some reason.
58  *
59  *      Arch_Touch              Alter the modification time of the archive
60  *                              member described by the given node to be
61  *                              the current time.
62  *
63  *      Arch_TouchLib           Update the modification time of the library
64  *                              described by the given node. This is special
65  *                              because it also updates the modification time
66  *                              of the library's table of contents.
67  *
68  *      Arch_MTime              Find the modification time of a member of
69  *                              an archive *in the archive*. The time is also
70  *                              placed in the member's GNode. Returns the
71  *                              modification time.
72  *
73  *      Arch_MemTime            Find the modification time of a member of
74  *                              an archive. Called when the member doesn't
75  *                              already exist. Looks in the archive for the
76  *                              modification time. Returns the modification
77  *                              time.
78  *
79  *      Arch_FindLib            Search for a library along a path. The
80  *                              library name in the GNode should be in
81  *                              -l<name> format.
82  *
83  *      Arch_LibOODate          Special function to decide if a library node
84  *                              is out-of-date.
85  *
86  *      Arch_Init               Initialize this module.
87  */
88
89 #include <sys/param.h>
90 #include <sys/types.h>
91 #include <ar.h>
92 #include <ctype.h>
93 #include <regex.h>
94 #include <stdlib.h>
95 #include <string.h>
96 #include <utime.h>
97
98 #include "arch.h"
99 #include "buf.h"
100 #include "config.h"
101 #include "dir.h"
102 #include "globals.h"
103 #include "GNode.h"
104 #include "hash.h"
105 #include "make.h"
106 #include "targ.h"
107 #include "util.h"
108 #include "var.h"
109
110 /* Lst of archives we've already examined */
111 static Lst archives = Lst_Initializer(archives);
112
113 typedef struct Arch {
114     char        *name;          /* Name of archive */
115     Hash_Table  members;        /* All the members of the archive described
116                                  * by <name, struct ar_hdr *> key/value pairs */
117     char        *fnametab;      /* Extended name table strings */
118     size_t      fnamesize;      /* Size of the string table */
119 } Arch;
120
121 static struct ar_hdr *ArchStatMember(const char *, const char *, Boolean);
122 static FILE *ArchFindMember(const char *, const char *, struct ar_hdr *, const char *);
123 #if defined(__svr4__) || defined(__SVR4) || defined(__ELF__)
124 #define SVR4ARCHIVES
125 static int ArchSVR4Entry(Arch *, char *, size_t, FILE *);
126 #endif
127
128 /*-
129  *-----------------------------------------------------------------------
130  * Arch_ParseArchive --
131  *      Parse the archive specification in the given line and find/create
132  *      the nodes for the specified archive members, placing their nodes
133  *      on the given list, given the pointer to the start of the
134  *      specification, a Lst on which to place the nodes, and a context
135  *      in which to expand variables.
136  *
137  * Results:
138  *      SUCCESS if it was a valid specification. The linePtr is updated
139  *      to point to the first non-space after the archive spec. The
140  *      nodes for the members are placed on the given list.
141  *
142  * Side Effects:
143  *      Some nodes may be created. The given list is extended.
144  *
145  *-----------------------------------------------------------------------
146  */
147 ReturnStatus
148 Arch_ParseArchive(char **linePtr, Lst *nodeLst, GNode *ctxt)
149 {
150     char        *cp;            /* Pointer into line */
151     GNode       *gn;            /* New node */
152     char        *libName;       /* Library-part of specification */
153     char        *memName;       /* Member-part of specification */
154     char        *nameBuf;       /* temporary place for node name */
155     char        saveChar;       /* Ending delimiter of member-name */
156     Boolean     subLibName;     /* TRUE if libName should have/had
157                                  * variable substitution performed on it */
158
159     libName = *linePtr;
160
161     subLibName = FALSE;
162
163     for (cp = libName; *cp != '(' && *cp != '\0'; cp++) {
164         if (*cp == '$') {
165             /*
166              * Variable spec, so call the Var module to parse the puppy
167              * so we can safely advance beyond it...
168              */
169             size_t length;
170             Boolean     freeIt;
171             char        *result;
172
173             result = Var_Parse(cp, ctxt, TRUE, &length, &freeIt);
174             if (result == var_Error) {
175                 return (FAILURE);
176             } else {
177                 subLibName = TRUE;
178             }
179
180             if (freeIt) {
181                 free(result);
182             }
183             cp += length - 1;
184         }
185     }
186
187     *cp++ = '\0';
188     if (subLibName) {
189         Buffer  *buf;
190
191         buf = Var_Subst(NULL, libName, ctxt, TRUE);
192         libName = Buf_GetAll(buf, NULL);
193         Buf_Destroy(buf, FALSE);
194     }
195
196
197     for (;;) {
198         /*
199          * First skip to the start of the member's name, mark that
200          * place and skip to the end of it (either white-space or
201          * a close paren).
202          */
203         Boolean doSubst = FALSE; /* TRUE if need to substitute in memName */
204
205         while (*cp != '\0' && *cp != ')' && isspace((unsigned char)*cp)) {
206             cp++;
207         }
208         memName = cp;
209         while (*cp != '\0' && *cp != ')' && !isspace((unsigned char)*cp)) {
210             if (*cp == '$') {
211                 /*
212                  * Variable spec, so call the Var module to parse the puppy
213                  * so we can safely advance beyond it...
214                  */
215                 size_t length;
216                 Boolean freeIt;
217                 char    *result;
218
219                 result = Var_Parse(cp, ctxt, TRUE, &length, &freeIt);
220                 if (result == var_Error) {
221                     return (FAILURE);
222                 } else {
223                     doSubst = TRUE;
224                 }
225
226                 if (freeIt) {
227                     free(result);
228                 }
229                 cp += length;
230             } else {
231                 cp++;
232             }
233         }
234
235         /*
236          * If the specification ends without a closing parenthesis,
237          * chances are there's something wrong (like a missing backslash),
238          * so it's better to return failure than allow such things to happen
239          */
240         if (*cp == '\0') {
241             printf("No closing parenthesis in archive specification\n");
242             return (FAILURE);
243         }
244
245         /*
246          * If we didn't move anywhere, we must be done
247          */
248         if (cp == memName) {
249             break;
250         }
251
252         saveChar = *cp;
253         *cp = '\0';
254
255         /*
256          * XXX: This should be taken care of intelligently by
257          * SuffExpandChildren, both for the archive and the member portions.
258          */
259         /*
260          * If member contains variables, try and substitute for them.
261          * This will slow down archive specs with dynamic sources, of course,
262          * since we'll be (non-)substituting them three times, but them's
263          * the breaks -- we need to do this since SuffExpandChildren calls
264          * us, otherwise we could assume the thing would be taken care of
265          * later.
266          */
267         if (doSubst) {
268             char        *buf;
269             char        *sacrifice;
270             char        *oldMemName = memName;
271             size_t      sz;
272             Buffer      *buf1;
273
274             /*
275              * Now form an archive spec and recurse to deal with nested
276              * variables and multi-word variable values.... The results
277              * are just placed at the end of the nodeLst we're returning.
278              */
279             buf1 = Var_Subst(NULL, memName, ctxt, TRUE);
280             memName = Buf_GetAll(buf1, NULL);
281
282             sz = strlen(memName) + strlen(libName) + 3;
283             buf = emalloc(sz);
284             snprintf(buf, sz, "%s(%s)", libName, memName);
285
286             sacrifice = buf;
287
288             if (strchr(memName, '$') && strcmp(memName, oldMemName) == 0) {
289                 /*
290                  * Must contain dynamic sources, so we can't deal with it now.
291                  * Just create an ARCHV node for the thing and let
292                  * SuffExpandChildren handle it...
293                  */
294                 gn = Targ_FindNode(buf, TARG_CREATE);
295
296                 if (gn == NULL) {
297                     free(buf);
298                     Buf_Destroy(buf1, FALSE);
299                     return (FAILURE);
300                 } else {
301                     gn->type |= OP_ARCHV;
302                     Lst_AtEnd(nodeLst, (void *)gn);
303                 }
304             } else if (Arch_ParseArchive(&sacrifice, nodeLst, ctxt) != SUCCESS) {
305                 /*
306                  * Error in nested call -- free buffer and return FAILURE
307                  * ourselves.
308                  */
309                 free(buf);
310                 Buf_Destroy(buf1, FALSE);
311                 return (FAILURE);
312             }
313
314             /* Free buffer and continue with our work. */
315             free(buf);
316             Buf_Destroy(buf1, FALSE);
317
318         } else if (Dir_HasWildcards(memName)) {
319             Lst members = Lst_Initializer(members);
320             char  *member;
321             size_t sz = MAXPATHLEN;
322             size_t nsz;
323
324             nameBuf = emalloc(sz);
325
326             Dir_Expand(memName, &dirSearchPath, &members);
327             while (!Lst_IsEmpty(&members)) {
328                 member = Lst_DeQueue(&members);
329                 nsz = strlen(libName) + strlen(member) + 3; /* 3 = ()+\0 */
330                 if (sz < nsz) {
331                         sz = nsz * 2;
332                         nameBuf = erealloc(nameBuf, sz);
333                 }
334                 snprintf(nameBuf, sz, "%s(%s)", libName, member);
335                 free(member);
336                 gn = Targ_FindNode(nameBuf, TARG_CREATE);
337                 if (gn == NULL) {
338                     free(nameBuf);
339                     /* XXXHB Lst_Destroy(&members) */
340                     return (FAILURE);
341                 } else {
342                     /*
343                      * We've found the node, but have to make sure the rest of
344                      * the world knows it's an archive member, without having
345                      * to constantly check for parentheses, so we type the
346                      * thing with the OP_ARCHV bit before we place it on the
347                      * end of the provided list.
348                      */
349                     gn->type |= OP_ARCHV;
350                     Lst_AtEnd(nodeLst, (void *)gn);
351                 }
352             }
353             free(nameBuf);
354         } else {
355             size_t sz = strlen(libName) + strlen(memName) + 3;
356             nameBuf = emalloc(sz);
357             snprintf(nameBuf, sz, "%s(%s)", libName, memName);
358             gn = Targ_FindNode(nameBuf, TARG_CREATE);
359             free(nameBuf);
360             if (gn == NULL) {
361                 return (FAILURE);
362             } else {
363                 /*
364                  * We've found the node, but have to make sure the rest of the
365                  * world knows it's an archive member, without having to
366                  * constantly check for parentheses, so we type the thing with
367                  * the OP_ARCHV bit before we place it on the end of the
368                  * provided list.
369                  */
370                 gn->type |= OP_ARCHV;
371                 Lst_AtEnd(nodeLst, gn);
372             }
373         }
374         if (doSubst) {
375             free(memName);
376         }
377
378         *cp = saveChar;
379     }
380
381     /*
382      * If substituted libName, free it now, since we need it no longer.
383      */
384     if (subLibName) {
385         free(libName);
386     }
387
388     /*
389      * We promised the pointer would be set up at the next non-space, so
390      * we must advance cp there before setting *linePtr... (note that on
391      * entrance to the loop, cp is guaranteed to point at a ')')
392      */
393     do {
394         cp++;
395     } while (*cp != '\0' && isspace((unsigned char)*cp));
396
397     *linePtr = cp;
398     return (SUCCESS);
399 }
400
401 /*-
402  *-----------------------------------------------------------------------
403  * ArchFindArchive --
404  *      See if the given archive is the one we are looking for. Called
405  *      From ArchStatMember and ArchFindMember via Lst_Find with the
406  *      current list element and the name we want.
407  *
408  * Results:
409  *      0 if it is, non-zero if it isn't.
410  *
411  * Side Effects:
412  *      None.
413  *
414  *-----------------------------------------------------------------------
415  */
416 static int
417 ArchFindArchive(const void *ar, const void *archName)
418 {
419         return (strcmp(archName, ((const Arch *)ar)->name));
420 }
421
422 /*-
423  *-----------------------------------------------------------------------
424  * ArchStatMember --
425  *      Locate a member of an archive, given the path of the archive and
426  *      the path of the desired member, and a boolean representing whether
427  *      or not the archive should be hashed (if not already hashed).
428  *
429  * Results:
430  *      A pointer to the current struct ar_hdr structure for the member. Note
431  *      That no position is returned, so this is not useful for touching
432  *      archive members. This is mostly because we have no assurances that
433  *      The archive will remain constant after we read all the headers, so
434  *      there's not much point in remembering the position...
435  *
436  * Side Effects:
437  *
438  *-----------------------------------------------------------------------
439  */
440 static struct ar_hdr *
441 ArchStatMember(const char *archive, const char *member, Boolean hash)
442 {
443 #define AR_MAX_NAME_LEN     (sizeof(arh.ar_name) - 1)
444     FILE        *arch;  /* Stream to archive */
445     int         size;   /* Size of archive member */
446     char        *cp;    /* Useful character pointer */
447     char        magic[SARMAG];
448     LstNode     *ln;    /* Lst member containing archive descriptor */
449     Arch        *ar;    /* Archive descriptor */
450     Hash_Entry  *he;    /* Entry containing member's description */
451     struct ar_hdr arh;  /* archive-member header for reading archive */
452     char        memName[MAXPATHLEN]; /* Current member name while hashing. */
453
454     /*
455      * Because of space constraints and similar things, files are archived
456      * using their final path components, not the entire thing, so we need
457      * to point 'member' to the final component, if there is one, to make
458      * the comparisons easier...
459      */
460     cp = strrchr(member, '/');
461     if ((cp != NULL) && (strcmp(member, RANLIBMAG) != 0))
462         member = cp + 1;
463
464     ln = Lst_Find(&archives, archive, ArchFindArchive);
465     if (ln != NULL) {
466         ar = Lst_Datum(ln);
467
468         he = Hash_FindEntry(&ar->members, member);
469
470         if (he != NULL) {
471             return ((struct ar_hdr *)Hash_GetValue (he));
472         } else {
473             /* Try truncated name */
474             char copy[AR_MAX_NAME_LEN + 1];
475             size_t len = strlen(member);
476
477             if (len > AR_MAX_NAME_LEN) {
478                 len = AR_MAX_NAME_LEN;
479                 strncpy(copy, member, AR_MAX_NAME_LEN);
480                 copy[AR_MAX_NAME_LEN] = '\0';
481             }
482             if ((he = Hash_FindEntry(&ar->members, copy)) != NULL)
483                 return (Hash_GetValue(he));
484             return (NULL);
485         }
486     }
487
488     if (!hash) {
489         /*
490          * Caller doesn't want the thing hashed, just use ArchFindMember
491          * to read the header for the member out and close down the stream
492          * again. Since the archive is not to be hashed, we assume there's
493          * no need to allocate extra room for the header we're returning,
494          * so just declare it static.
495          */
496          static struct ar_hdr   sarh;
497
498          arch = ArchFindMember(archive, member, &sarh, "r");
499
500         if (arch == NULL) {
501             return (NULL);
502         } else {
503             fclose(arch);
504             return (&sarh);
505         }
506     }
507
508     /*
509      * We don't have this archive on the list yet, so we want to find out
510      * everything that's in it and cache it so we can get at it quickly.
511      */
512     arch = fopen(archive, "r");
513     if (arch == NULL) {
514         return (NULL);
515     }
516
517     /*
518      * We use the ARMAG string to make sure this is an archive we
519      * can handle...
520      */
521     if ((fread(magic, SARMAG, 1, arch) != 1) ||
522         (strncmp(magic, ARMAG, SARMAG) != 0)) {
523             fclose(arch);
524             return (NULL);
525     }
526
527     ar = emalloc(sizeof(Arch));
528     ar->name = estrdup(archive);
529     ar->fnametab = NULL;
530     ar->fnamesize = 0;
531     Hash_InitTable(&ar->members, -1);
532     memName[AR_MAX_NAME_LEN] = '\0';
533
534     while (fread(&arh, sizeof(struct ar_hdr), 1, arch) == 1) {
535         if (strncmp(arh.ar_fmag, ARFMAG, sizeof(arh.ar_fmag)) != 0) {
536             /*
537              * The header is bogus, so the archive is bad
538              * and there's no way we can recover...
539              */
540             goto badarch;
541         } else {
542             /*
543              * We need to advance the stream's pointer to the start of the
544              * next header. Files are padded with newlines to an even-byte
545              * boundary, so we need to extract the size of the file from the
546              * 'size' field of the header and round it up during the seek.
547              */
548             arh.ar_size[sizeof(arh.ar_size) - 1] = '\0';
549             size = (int)strtol(arh.ar_size, NULL, 10);
550
551             strncpy(memName, arh.ar_name, sizeof(arh.ar_name));
552             for (cp = &memName[AR_MAX_NAME_LEN]; *cp == ' '; cp--) {
553                 continue;
554             }
555             cp[1] = '\0';
556
557 #ifdef SVR4ARCHIVES
558             /*
559              * svr4 names are slash terminated. Also svr4 extended AR format.
560              */
561             if (memName[0] == '/') {
562                 /*
563                  * svr4 magic mode; handle it
564                  */
565                 switch (ArchSVR4Entry(ar, memName, size, arch)) {
566                 case -1:  /* Invalid data */
567                     goto badarch;
568                 case 0:   /* List of files entry */
569                     continue;
570                 default:  /* Got the entry */
571                     break;
572                 }
573             }
574             else {
575                 if (cp[0] == '/')
576                     cp[0] = '\0';
577             }
578 #endif
579
580 #ifdef AR_EFMT1
581             /*
582              * BSD 4.4 extended AR format: #1/<namelen>, with name as the
583              * first <namelen> bytes of the file
584              */
585             if (strncmp(memName, AR_EFMT1, sizeof(AR_EFMT1) - 1) == 0 &&
586                 isdigit(memName[sizeof(AR_EFMT1) - 1])) {
587
588                 unsigned int elen = atoi(&memName[sizeof(AR_EFMT1)-1]);
589
590                 if (elen > MAXPATHLEN)
591                         goto badarch;
592                 if (fread(memName, elen, 1, arch) != 1)
593                         goto badarch;
594                 memName[elen] = '\0';
595                 fseek(arch, -elen, SEEK_CUR);
596                 /* XXX Multiple levels may be asked for, make this conditional
597                  * on one, and use DEBUGF.
598                  */
599                 if (DEBUG(ARCH) || DEBUG(MAKE)) {
600                     fprintf(stderr, "ArchStat: Extended format entry for %s\n", memName);
601                 }
602             }
603 #endif
604
605             he = Hash_CreateEntry(&ar->members, memName, NULL);
606             Hash_SetValue(he, emalloc(sizeof(struct ar_hdr)));
607             memcpy(Hash_GetValue(he), &arh, sizeof(struct ar_hdr));
608         }
609         fseek(arch, (size + 1) & ~1, SEEK_CUR);
610     }
611
612     fclose(arch);
613
614     Lst_AtEnd(&archives, ar);
615
616     /*
617      * Now that the archive has been read and cached, we can look into
618      * the hash table to find the desired member's header.
619      */
620     he = Hash_FindEntry(&ar->members, member);
621
622     if (he != NULL) {
623         return (Hash_GetValue (he));
624     } else {
625         return (NULL);
626     }
627
628 badarch:
629     fclose(arch);
630     Hash_DeleteTable(&ar->members);
631     free(ar->fnametab);
632     free(ar);
633     return (NULL);
634 }
635
636 #ifdef SVR4ARCHIVES
637 /*-
638  *-----------------------------------------------------------------------
639  * ArchSVR4Entry --
640  *      Parse an SVR4 style entry that begins with a slash.
641  *      If it is "//", then load the table of filenames
642  *      If it is "/<offset>", then try to substitute the long file name
643  *      from offset of a table previously read.
644  *
645  * Results:
646  *      -1: Bad data in archive
647  *       0: A table was loaded from the file
648  *       1: Name was successfully substituted from table
649  *       2: Name was not successfully substituted from table
650  *
651  * Side Effects:
652  *      If a table is read, the file pointer is moved to the next archive
653  *      member
654  *
655  *-----------------------------------------------------------------------
656  */
657 static int
658 ArchSVR4Entry(Arch *ar, char *name, size_t size, FILE *arch)
659 {
660 #define ARLONGNAMES1 "//"
661 #define ARLONGNAMES2 "/ARFILENAMES"
662     size_t entry;
663     char *ptr, *eptr;
664
665     if (strncmp(name, ARLONGNAMES1, sizeof(ARLONGNAMES1) - 1) == 0 ||
666         strncmp(name, ARLONGNAMES2, sizeof(ARLONGNAMES2) - 1) == 0) {
667
668         if (ar->fnametab != NULL) {
669             DEBUGF(ARCH, ("Attempted to redefine an SVR4 name table\n"));
670             return (-1);
671         }
672
673         /*
674          * This is a table of archive names, so we build one for
675          * ourselves
676          */
677         ar->fnametab = emalloc(size);
678         ar->fnamesize = size;
679
680         if (fread(ar->fnametab, size, 1, arch) != 1) {
681             DEBUGF(ARCH, ("Reading an SVR4 name table failed\n"));
682             return (-1);
683         }
684         eptr = ar->fnametab + size;
685         for (entry = 0, ptr = ar->fnametab; ptr < eptr; ptr++)
686             switch (*ptr) {
687             case '/':
688                 entry++;
689                 *ptr = '\0';
690                 break;
691
692             case '\n':
693                 break;
694
695             default:
696                 break;
697             }
698         DEBUGF(ARCH, ("Found svr4 archive name table with %zu entries\n", entry));
699         return (0);
700     }
701
702     if (name[1] == ' ' || name[1] == '\0')
703         return (2);
704
705     entry = (size_t)strtol(&name[1], &eptr, 0);
706     if ((*eptr != ' ' && *eptr != '\0') || eptr == &name[1]) {
707         DEBUGF(ARCH, ("Could not parse SVR4 name %s\n", name));
708         return (2);
709     }
710     if (entry >= ar->fnamesize) {
711         DEBUGF(ARCH, ("SVR4 entry offset %s is greater than %zu\n",
712                name, ar->fnamesize));
713         return (2);
714     }
715
716     DEBUGF(ARCH, ("Replaced %s with %s\n", name, &ar->fnametab[entry]));
717
718     strncpy(name, &ar->fnametab[entry], MAXPATHLEN);
719     name[MAXPATHLEN - 1] = '\0';
720     return (1);
721 }
722 #endif
723
724
725 /*-
726  *-----------------------------------------------------------------------
727  * ArchFindMember --
728  *      Locate a member of an archive, given the path of the archive and
729  *      the path of the desired member. If the archive is to be modified,
730  *      the mode should be "r+", if not, it should be "r".  arhPtr is a
731  *      poitner to the header structure to fill in.
732  *
733  * Results:
734  *      An FILE *, opened for reading and writing, positioned at the
735  *      start of the member's struct ar_hdr, or NULL if the member was
736  *      nonexistent. The current struct ar_hdr for member.
737  *
738  * Side Effects:
739  *      The passed struct ar_hdr structure is filled in.
740  *
741  *-----------------------------------------------------------------------
742  */
743 static FILE *
744 ArchFindMember(const char *archive, const char *member, struct ar_hdr *arhPtr, const char *mode)
745 {
746     FILE        *arch;  /* Stream to archive */
747     int         size;   /* Size of archive member */
748     const char  *cp;    /* Useful character pointer */
749     char        magic[SARMAG];
750     size_t      len, tlen;
751
752     arch = fopen(archive, mode);
753     if (arch == NULL) {
754         return (NULL);
755     }
756
757     /*
758      * We use the ARMAG string to make sure this is an archive we
759      * can handle...
760      */
761     if ((fread(magic, SARMAG, 1, arch) != 1) ||
762         (strncmp(magic, ARMAG, SARMAG) != 0)) {
763             fclose(arch);
764             return (NULL);
765     }
766
767     /*
768      * Because of space constraints and similar things, files are archived
769      * using their final path components, not the entire thing, so we need
770      * to point 'member' to the final component, if there is one, to make
771      * the comparisons easier...
772      */
773     cp = strrchr(member, '/');
774     if ((cp != NULL) && (strcmp(member, RANLIBMAG) != 0)) {
775         member = cp + 1;
776     }
777     len = tlen = strlen(member);
778     if (len > sizeof(arhPtr->ar_name)) {
779         tlen = sizeof(arhPtr->ar_name);
780     }
781
782     while (fread(arhPtr, sizeof(struct ar_hdr), 1, arch) == 1) {
783         if (strncmp(arhPtr->ar_fmag, ARFMAG, sizeof(arhPtr->ar_fmag) ) != 0) {
784              /*
785               * The header is bogus, so the archive is bad
786               * and there's no way we can recover...
787               */
788              fclose(arch);
789              return (NULL);
790         } else if (strncmp(member, arhPtr->ar_name, tlen) == 0) {
791             /*
792              * If the member's name doesn't take up the entire 'name' field,
793              * we have to be careful of matching prefixes. Names are space-
794              * padded to the right, so if the character in 'name' at the end
795              * of the matched string is anything but a space, this isn't the
796              * member we sought.
797              */
798             if (tlen != sizeof(arhPtr->ar_name) && arhPtr->ar_name[tlen] != ' '){
799                 goto skip;
800             } else {
801                 /*
802                  * To make life easier, we reposition the file at the start
803                  * of the header we just read before we return the stream.
804                  * In a more general situation, it might be better to leave
805                  * the file at the actual member, rather than its header, but
806                  * not here...
807                  */
808                 fseek(arch, -sizeof(struct ar_hdr), SEEK_CUR);
809                 return (arch);
810             }
811         } else
812 #ifdef AR_EFMT1
813                 /*
814                  * BSD 4.4 extended AR format: #1/<namelen>, with name as the
815                  * first <namelen> bytes of the file
816                  */
817             if (strncmp(arhPtr->ar_name, AR_EFMT1,
818                                         sizeof(AR_EFMT1) - 1) == 0 &&
819                 isdigit(arhPtr->ar_name[sizeof(AR_EFMT1) - 1])) {
820
821                 unsigned int elen = atoi(&arhPtr->ar_name[sizeof(AR_EFMT1)-1]);
822                 char ename[MAXPATHLEN];
823
824                 if (elen > MAXPATHLEN) {
825                         fclose(arch);
826                         return NULL;
827                 }
828                 if (fread(ename, elen, 1, arch) != 1) {
829                         fclose(arch);
830                         return NULL;
831                 }
832                 ename[elen] = '\0';
833                 /*
834                  * XXX choose one.
835                  */
836                 if (DEBUG(ARCH) || DEBUG(MAKE)) {
837                     printf("ArchFind: Extended format entry for %s\n", ename);
838                 }
839                 if (strncmp(ename, member, len) == 0) {
840                         /* Found as extended name */
841                         fseek(arch, -sizeof(struct ar_hdr) - elen, SEEK_CUR);
842                         return (arch);
843                 }
844                 fseek(arch, -elen, SEEK_CUR);
845                 goto skip;
846         } else
847 #endif
848         {
849 skip:
850             /*
851              * This isn't the member we're after, so we need to advance the
852              * stream's pointer to the start of the next header. Files are
853              * padded with newlines to an even-byte boundary, so we need to
854              * extract the size of the file from the 'size' field of the
855              * header and round it up during the seek.
856              */
857             arhPtr->ar_size[sizeof(arhPtr->ar_size) - 1] = '\0';
858             size = (int)strtol(arhPtr->ar_size, NULL, 10);
859             fseek(arch, (size + 1) & ~1, SEEK_CUR);
860         }
861     }
862
863     /*
864      * We've looked everywhere, but the member is not to be found. Close the
865      * archive and return NULL -- an error.
866      */
867     fclose(arch);
868     return (NULL);
869 }
870
871 /*-
872  *-----------------------------------------------------------------------
873  * Arch_Touch --
874  *      Touch a member of an archive.
875  *
876  * Results:
877  *      The 'time' field of the member's header is updated.
878  *
879  * Side Effects:
880  *      The modification time of the entire archive is also changed.
881  *      For a library, this could necessitate the re-ranlib'ing of the
882  *      whole thing.
883  *
884  *-----------------------------------------------------------------------
885  */
886 void
887 Arch_Touch(GNode *gn)
888 {
889     FILE *        arch;   /* Stream open to archive, positioned properly */
890     struct ar_hdr arh;    /* Current header describing member */
891     char *p1, *p2;
892
893     arch = ArchFindMember(Var_Value(ARCHIVE, gn, &p1),
894                           Var_Value(TARGET, gn, &p2),
895                           &arh, "r+");
896     free(p1);
897     free(p2);
898     snprintf(arh.ar_date, sizeof(arh.ar_date), "%-12ld", (long)now);
899
900     if (arch != NULL) {
901         fwrite(&arh, sizeof(struct ar_hdr), 1, arch);
902         fclose(arch);
903     }
904 }
905
906 /*-
907  *-----------------------------------------------------------------------
908  * Arch_TouchLib --
909  *      Given a node which represents a library, touch the thing, making
910  *      sure that the table of contents also is touched.
911  *
912  * Results:
913  *      None.
914  *
915  * Side Effects:
916  *      Both the modification time of the library and of the RANLIBMAG
917  *      member are set to 'now'.
918  *
919  *-----------------------------------------------------------------------
920  */
921 void
922 Arch_TouchLib(GNode *gn)
923 {
924 #ifdef RANLIBMAG
925     FILE                *arch;  /* Stream open to archive */
926     struct ar_hdr       arh;    /* Header describing table of contents */
927     struct utimbuf      times;  /* Times for utime() call */
928
929     arch = ArchFindMember(gn->path, RANLIBMAG, &arh, "r+");
930     snprintf(arh.ar_date, sizeof(arh.ar_date), "%-12ld", (long) now);
931
932     if (arch != NULL) {
933         fwrite(&arh, sizeof(struct ar_hdr), 1, arch);
934         fclose(arch);
935
936         times.actime = times.modtime = now;
937         utime(gn->path, &times);
938     }
939 #endif
940 }
941
942 /*-
943  *-----------------------------------------------------------------------
944  * Arch_MTime --
945  *      Return the modification time of a member of an archive, given its
946  *      name.
947  *
948  * Results:
949  *      The modification time(seconds).
950  *
951  * Side Effects:
952  *      The mtime field of the given node is filled in with the value
953  *      returned by the function.
954  *
955  *-----------------------------------------------------------------------
956  */
957 int
958 Arch_MTime(GNode *gn)
959 {
960     struct ar_hdr *arhPtr;    /* Header of desired member */
961     int           modTime;    /* Modification time as an integer */
962     char *p1, *p2;
963
964     arhPtr = ArchStatMember(Var_Value(ARCHIVE, gn, &p1),
965                              Var_Value(TARGET, gn, &p2),
966                              TRUE);
967     free(p1);
968     free(p2);
969
970     if (arhPtr != NULL) {
971         modTime = (int)strtol(arhPtr->ar_date, NULL, 10);
972     } else {
973         modTime = 0;
974     }
975
976     gn->mtime = modTime;
977     return (modTime);
978 }
979
980 /*-
981  *-----------------------------------------------------------------------
982  * Arch_MemMTime --
983  *      Given a non-existent archive member's node, get its modification
984  *      time from its archived form, if it exists.
985  *
986  * Results:
987  *      The modification time.
988  *
989  * Side Effects:
990  *      The mtime field is filled in.
991  *
992  *-----------------------------------------------------------------------
993  */
994 int
995 Arch_MemMTime(GNode *gn)
996 {
997     LstNode     *ln;
998     GNode       *pgn;
999     char        *nameStart;
1000     char        *nameEnd;
1001
1002     for (ln = Lst_First(&gn->parents); ln != NULL; ln = Lst_Succ(ln)) {
1003         pgn = Lst_Datum(ln);
1004
1005         if (pgn->type & OP_ARCHV) {
1006             /*
1007              * If the parent is an archive specification and is being made
1008              * and its member's name matches the name of the node we were
1009              * given, record the modification time of the parent in the
1010              * child. We keep searching its parents in case some other
1011              * parent requires this child to exist...
1012              */
1013             nameStart = strchr(pgn->name, '(') + 1;
1014             nameEnd = strchr(nameStart, ')');
1015
1016             if (pgn->make &&
1017                 strncmp(nameStart, gn->name, nameEnd - nameStart) == 0) {
1018                                      gn->mtime = Arch_MTime(pgn);
1019             }
1020         } else if (pgn->make) {
1021             /*
1022              * Something which isn't a library depends on the existence of
1023              * this target, so it needs to exist.
1024              */
1025             gn->mtime = 0;
1026             break;
1027         }
1028     }
1029     return (gn->mtime);
1030 }
1031
1032 /*-
1033  *-----------------------------------------------------------------------
1034  * Arch_FindLib --
1035  *      Search for a named library along the given search path.
1036  *
1037  * Results:
1038  *      None.
1039  *
1040  * Side Effects:
1041  *      The node's 'path' field is set to the found path (including the
1042  *      actual file name, not -l...). If the system can handle the -L
1043  *      flag when linking (or we cannot find the library), we assume that
1044  *      the user has placed the .LIBRARIES variable in the final linking
1045  *      command (or the linker will know where to find it) and set the
1046  *      TARGET variable for this node to be the node's name. Otherwise,
1047  *      we set the TARGET variable to be the full path of the library,
1048  *      as returned by Dir_FindFile.
1049  *
1050  *-----------------------------------------------------------------------
1051  */
1052 void
1053 Arch_FindLib(GNode *gn, Lst *path)
1054 {
1055     char            *libName;   /* file name for archive */
1056     size_t          sz;
1057
1058     sz = strlen(gn->name) + 4;
1059     libName = emalloc(sz);
1060     snprintf(libName, sz, "lib%s.a", &gn->name[2]);
1061
1062     gn->path = Dir_FindFile(libName, path);
1063
1064     free(libName);
1065
1066 #ifdef LIBRARIES
1067     Var_Set(TARGET, gn->name, gn);
1068 #else
1069     Var_Set(TARGET, gn->path == NULL ? gn->name : gn->path, gn);
1070 #endif /* LIBRARIES */
1071 }
1072
1073 /*-
1074  *-----------------------------------------------------------------------
1075  * Arch_LibOODate --
1076  *      Decide if a node with the OP_LIB attribute is out-of-date. Called
1077  *      from Make_OODate to make its life easier, with the library's
1078  *      graph node.
1079  *
1080  *      There are several ways for a library to be out-of-date that are
1081  *      not available to ordinary files. In addition, there are ways
1082  *      that are open to regular files that are not available to
1083  *      libraries. A library that is only used as a source is never
1084  *      considered out-of-date by itself. This does not preclude the
1085  *      library's modification time from making its parent be out-of-date.
1086  *      A library will be considered out-of-date for any of these reasons,
1087  *      given that it is a target on a dependency line somewhere:
1088  *          Its modification time is less than that of one of its
1089  *                sources (gn->mtime < gn->cmtime).
1090  *          Its modification time is greater than the time at which the
1091  *                make began (i.e. it's been modified in the course
1092  *                of the make, probably by archiving).
1093  *          The modification time of one of its sources is greater than
1094  *                the one of its RANLIBMAG member (i.e. its table of contents
1095  *                is out-of-date). We don't compare of the archive time
1096  *                vs. TOC time because they can be too close. In my
1097  *                opinion we should not bother with the TOC at all since
1098  *                this is used by 'ar' rules that affect the data contents
1099  *                of the archive, not by ranlib rules, which affect the
1100  *                TOC.
1101  *
1102  * Results:
1103  *      TRUE if the library is out-of-date. FALSE otherwise.
1104  *
1105  * Side Effects:
1106  *      The library will be hashed if it hasn't been already.
1107  *
1108  *-----------------------------------------------------------------------
1109  */
1110 Boolean
1111 Arch_LibOODate(GNode *gn)
1112 {
1113     Boolean       oodate;
1114
1115     if (OP_NOP(gn->type) && Lst_IsEmpty(&gn->children)) {
1116         oodate = FALSE;
1117     } else if ((gn->mtime > now) || (gn->mtime < gn->cmtime)) {
1118         oodate = TRUE;
1119     } else {
1120 #ifdef RANLIBMAG
1121         struct ar_hdr   *arhPtr;        /* Header for __.SYMDEF */
1122         int             modTimeTOC;     /* The table-of-contents's mod time */
1123
1124         arhPtr = ArchStatMember(gn->path, RANLIBMAG, FALSE);
1125
1126         if (arhPtr != NULL) {
1127             modTimeTOC = (int)strtol(arhPtr->ar_date, NULL, 10);
1128
1129             /* XXX choose one. */
1130             if (DEBUG(ARCH) || DEBUG(MAKE)) {
1131                 printf("%s modified %s...", RANLIBMAG, Targ_FmtTime(modTimeTOC));
1132             }
1133             oodate = (gn->cmtime > modTimeTOC);
1134         } else {
1135             /*
1136              * A library w/o a table of contents is out-of-date
1137              */
1138             if (DEBUG(ARCH) || DEBUG(MAKE)) {
1139                 printf("No t.o.c....");
1140             }
1141             oodate = TRUE;
1142         }
1143 #else
1144         oodate = (gn->mtime == 0); /* out-of-date if not present */
1145 #endif
1146     }
1147     return (oodate);
1148 }
1149
1150 /*-
1151  *-----------------------------------------------------------------------
1152  * Arch_Init --
1153  *      Initialize things for this module.
1154  *
1155  * Results:
1156  *      None.
1157  *
1158  *-----------------------------------------------------------------------
1159  */
1160 void
1161 Arch_Init(void)
1162 {
1163 }