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