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