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