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