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