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