/* $NetBSD: arch.c,v 1.223 2025/06/28 22:39:27 rillig Exp $ */12/*3* Copyright (c) 1988, 1989, 1990, 19934* The Regents of the University of California. All rights reserved.5*6* This code is derived from software contributed to Berkeley by7* Adam de Boor.8*9* Redistribution and use in source and binary forms, with or without10* modification, are permitted provided that the following conditions11* are met:12* 1. Redistributions of source code must retain the above copyright13* notice, this list of conditions and the following disclaimer.14* 2. Redistributions in binary form must reproduce the above copyright15* notice, this list of conditions and the following disclaimer in the16* documentation and/or other materials provided with the distribution.17* 3. Neither the name of the University nor the names of its contributors18* may be used to endorse or promote products derived from this software19* without specific prior written permission.20*21* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND22* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE23* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE24* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE25* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL26* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS27* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)28* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT29* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY30* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF31* SUCH DAMAGE.32*/3334/*35* Copyright (c) 1989 by Berkeley Softworks36* All rights reserved.37*38* This code is derived from software contributed to Berkeley by39* Adam de Boor.40*41* Redistribution and use in source and binary forms, with or without42* modification, are permitted provided that the following conditions43* are met:44* 1. Redistributions of source code must retain the above copyright45* notice, this list of conditions and the following disclaimer.46* 2. Redistributions in binary form must reproduce the above copyright47* notice, this list of conditions and the following disclaimer in the48* documentation and/or other materials provided with the distribution.49* 3. All advertising materials mentioning features or use of this software50* must display the following acknowledgement:51* This product includes software developed by the University of52* California, Berkeley and its contributors.53* 4. Neither the name of the University nor the names of its contributors54* may be used to endorse or promote products derived from this software55* without specific prior written permission.56*57* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND58* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE59* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE60* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE61* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL62* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS63* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)64* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT65* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY66* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF67* SUCH DAMAGE.68*/6970/*71* Manipulate libraries, archives and their members.72*73* The first time an archive is referenced, all of its members' headers are74* read and cached and the archive closed again. All cached archives are kept75* on a list which is searched each time an archive member is referenced.76*77* The interface to this module is:78*79* Arch_Init Initialize this module.80*81* Arch_End Clean up this module.82*83* Arch_ParseArchive84* Parse an archive specification such as85* "archive.a(member1 member2)".86*87* Arch_Touch Alter the modification time of the archive88* member described by the given node to be89* the time when make was started.90*91* Arch_TouchLib Update the modification time of the library92* described by the given node. This is special93* because it also updates the modification time94* of the library's table of contents.95*96* Arch_UpdateMTime97* Find the modification time of a member of98* an archive *in the archive* and place it in the99* member's GNode.100*101* Arch_UpdateMemberMTime102* Find the modification time of a member of103* an archive. Called when the member doesn't104* already exist. Looks in the archive for the105* modification time. Returns the modification106* time.107*108* Arch_FindLib Search for a library along a path. The109* library name in the GNode should be in110* -l<name> format.111*112* Arch_LibOODate Decide if a library node is out-of-date.113*/114115#ifdef HAVE_CONFIG_H116# include "config.h"117#endif118#include <sys/types.h>119#include <sys/stat.h>120#include <sys/time.h>121#include <sys/param.h>122#ifdef HAVE_AR_H123#include <ar.h>124#else125struct ar_hdr {126char ar_name[16]; /* name */127char ar_date[12]; /* modification time */128char ar_uid[6]; /* user id */129char ar_gid[6]; /* group id */130char ar_mode[8]; /* octal file permissions */131char ar_size[10]; /* size in bytes */132#ifndef ARFMAG133#define ARFMAG "`\n"134#endif135char ar_fmag[2]; /* consistency check */136};137#endif138#if defined(HAVE_RANLIB_H) && !(defined(__ELF__) || defined(NO_RANLIB))139#include <ranlib.h>140#endif141#ifdef HAVE_UTIME_H142#include <utime.h>143#endif144145#include "make.h"146#include "dir.h"147148/* "@(#)arch.c 8.2 (Berkeley) 1/2/94" */149MAKE_RCSID("$NetBSD: arch.c,v 1.223 2025/06/28 22:39:27 rillig Exp $");150151typedef struct List ArchList;152typedef struct ListNode ArchListNode;153154static ArchList archives; /* The archives we've already examined */155156typedef struct Arch {157char *name;158HashTable members; /* All the members of the archive described159* by <name, struct ar_hdr *> key/value pairs */160char *fnametab; /* Extended name table strings */161size_t fnamesize; /* Size of the string table */162} Arch;163164static FILE *ArchFindMember(const char *, const char *,165struct ar_hdr *, const char *);166#if defined(__svr4__) || defined(__SVR4) || defined(__ELF__)167#define SVR4ARCHIVES168static int ArchSVR4Entry(Arch *, char *, size_t, FILE *);169#endif170171172#if defined(_AIX)173# define AR_NAME _ar_name.ar_name174# define AR_FMAG _ar_name.ar_fmag175# define SARMAG SAIAMAG176# define ARMAG AIAMAG177# define ARFMAG AIAFMAG178#endif179#ifndef AR_NAME180# define AR_NAME ar_name181#endif182#ifndef AR_DATE183# define AR_DATE ar_date184#endif185#ifndef AR_SIZE186# define AR_SIZE ar_size187#endif188#ifndef AR_FMAG189# define AR_FMAG ar_fmag190#endif191#ifndef ARMAG192# define ARMAG "!<arch>\n"193#endif194#ifndef SARMAG195# define SARMAG 8196#endif197198199#ifdef CLEANUP200static void201ArchFree(Arch *a)202{203HashIter hi;204205HashIter_Init(&hi, &a->members);206while (HashIter_Next(&hi))207free(hi.entry->value);208209free(a->name);210free(a->fnametab);211HashTable_Done(&a->members);212free(a);213}214#endif215216/* Return "archive(member)". */217MAKE_ATTR_NOINLINE static char *218FullName(const char *archive, const char *member)219{220Buffer buf;221Buf_Init(&buf);222Buf_AddStr(&buf, archive);223Buf_AddStr(&buf, "(");224Buf_AddStr(&buf, member);225Buf_AddStr(&buf, ")");226return Buf_DoneData(&buf);227}228229/*230* Parse an archive specification such as "archive.a(member1 member2.${EXT})",231* adding nodes for the expanded members to gns. If successful, advance pp232* beyond the archive specification and any trailing whitespace.233*/234bool235Arch_ParseArchive(char **pp, GNodeList *gns, GNode *scope)236{237char *spec; /* For modifying some bytes of *pp */238const char *cp; /* Pointer into line */239GNode *gn; /* New node */240FStr lib; /* Library-part of specification */241FStr mem; /* Member-part of specification */242char saveChar; /* Ending delimiter of member-name */243bool expandLib; /* Whether the parsed lib contains244* expressions that need to be expanded */245246spec = *pp;247lib = FStr_InitRefer(spec);248expandLib = false;249250for (cp = lib.str; *cp != '(' && *cp != '\0';) {251if (*cp == '$') {252/* Expand nested expressions. */253/* XXX: This code can probably be shortened. */254const char *nested_p = cp;255FStr result;256bool isError;257258/* XXX: is expanded twice: once here and once below */259result = Var_Parse(&nested_p, scope,260VARE_EVAL_DEFINED);261/* TODO: handle errors */262isError = result.str == var_Error;263FStr_Done(&result);264if (isError)265return false;266267expandLib = true;268cp += nested_p - cp;269} else270cp++;271}272273spec[cp++ - spec] = '\0';274if (expandLib)275Var_Expand(&lib, scope, VARE_EVAL_DEFINED);276277for (;;) {278/*279* First skip to the start of the member's name, mark that280* place and skip to the end of it (either white-space or281* a close paren).282*/283bool doSubst = false;284285cpp_skip_whitespace(&cp);286287mem = FStr_InitRefer(cp);288while (*cp != '\0' && *cp != ')' && !ch_isspace(*cp)) {289if (*cp == '$') {290/* Expand nested expressions. */291/*292* XXX: This code can probably be shortened.293*/294FStr result;295bool isError;296const char *nested_p = cp;297298result = Var_Parse(&nested_p, scope,299VARE_EVAL_DEFINED);300/* TODO: handle errors */301isError = result.str == var_Error;302FStr_Done(&result);303304if (isError)305return false;306307doSubst = true;308cp += nested_p - cp;309} else {310cp++;311}312}313314if (*cp == '\0') {315Parse_Error(PARSE_FATAL,316"Missing \")\" in archive specification");317return false;318}319320if (cp == mem.str)321break;322323saveChar = *cp;324spec[cp - spec] = '\0';325326/*327* XXX: This should be taken care of intelligently by328* SuffExpandChildren, both for the archive and the member329* portions.330*/331/*332* If member contains variables, try and substitute for them.333* This slows down archive specs with dynamic sources, since334* they are (non-)substituted three times, but we need to do335* this since SuffExpandChildren calls us, otherwise we could336* assume the substitutions would be taken care of later.337*/338if (doSubst) {339char *fullName;340char *p;341const char *unexpandedMem = mem.str;342343Var_Expand(&mem, scope, VARE_EVAL_DEFINED);344345/*346* Now form an archive spec and recurse to deal with347* nested variables and multi-word variable values.348*/349fullName = FullName(lib.str, mem.str);350p = fullName;351352if (strcmp(mem.str, unexpandedMem) == 0) {353/*354* Must contain dynamic sources, so we can't355* deal with it now. Just create an ARCHV node356* and let SuffExpandChildren handle it.357*/358gn = Targ_GetNode(fullName);359gn->type |= OP_ARCHV;360Lst_Append(gns, gn);361362} else if (!Arch_ParseArchive(&p, gns, scope)) {363/* Error in nested call. */364free(fullName);365/* XXX: does unexpandedMemName leak? */366return false;367}368free(fullName);369/* XXX: does unexpandedMemName leak? */370371} else if (Dir_HasWildcards(mem.str)) {372StringList members = LST_INIT;373SearchPath_Expand(&dirSearchPath, mem.str, &members);374375while (!Lst_IsEmpty(&members)) {376char *member = Lst_Dequeue(&members);377char *fullname = FullName(lib.str, member);378free(member);379380gn = Targ_GetNode(fullname);381free(fullname);382383gn->type |= OP_ARCHV;384Lst_Append(gns, gn);385}386Lst_Done(&members);387388} else {389char *fullname = FullName(lib.str, mem.str);390gn = Targ_GetNode(fullname);391free(fullname);392393gn->type |= OP_ARCHV;394Lst_Append(gns, gn);395}396FStr_Done(&mem);397398spec[cp - spec] = saveChar;399}400401FStr_Done(&lib);402403cp++; /* skip the ')' */404cpp_skip_whitespace(&cp);405*pp += cp - *pp;406return true;407}408409/*410* Locate a member in an archive.411*412* See ArchFindMember for an almost identical copy of this code.413*/414static struct ar_hdr *415ArchStatMember(const char *archive, const char *member, bool addToCache)416{417#define AR_MAX_NAME_LEN (sizeof arh.AR_NAME - 1)418FILE *arch;419size_t size; /* Size of archive member */420char magic[SARMAG];421ArchListNode *ln;422Arch *ar;423struct ar_hdr arh;424char memName[MAXPATHLEN + 1];425/* Current member name while hashing. */426427member = str_basename(member);428429for (ln = archives.first; ln != NULL; ln = ln->next) {430const Arch *a = ln->datum;431if (strcmp(a->name, archive) == 0)432break;433}434435if (ln != NULL) {436struct ar_hdr *hdr;437438ar = ln->datum;439hdr = HashTable_FindValue(&ar->members, member);440if (hdr != NULL)441return hdr;442443{444/* Try truncated name */445char copy[AR_MAX_NAME_LEN + 1];446size_t len = strlen(member);447448if (len > AR_MAX_NAME_LEN) {449snprintf(copy, sizeof copy, "%s", member);450hdr = HashTable_FindValue(&ar->members, copy);451}452return hdr;453}454}455456if (!addToCache) {457/*458* Since the archive is not to be cached, assume there's no459* need to allocate the header, so just declare it static.460*/461static struct ar_hdr sarh;462463arch = ArchFindMember(archive, member, &sarh, "r");464if (arch == NULL)465return NULL;466467fclose(arch);468return &sarh;469}470471arch = fopen(archive, "r");472if (arch == NULL)473return NULL;474475if (fread(magic, SARMAG, 1, arch) != 1 ||476strncmp(magic, ARMAG, SARMAG) != 0) {477(void)fclose(arch);478return NULL;479}480481ar = bmake_malloc(sizeof *ar);482ar->name = bmake_strdup(archive);483ar->fnametab = NULL;484ar->fnamesize = 0;485HashTable_Init(&ar->members);486memName[AR_MAX_NAME_LEN] = '\0';487488while (fread(&arh, sizeof arh, 1, arch) == 1) {489char *nameend;490491if (strncmp(arh.AR_FMAG, ARFMAG, sizeof arh.AR_FMAG) != 0)492goto bad_archive;493494arh.AR_SIZE[sizeof arh.AR_SIZE - 1] = '\0';495size = (size_t)strtol(arh.AR_SIZE, NULL, 10);496497memcpy(memName, arh.AR_NAME, sizeof arh.AR_NAME);498nameend = memName + AR_MAX_NAME_LEN;499while (nameend > memName && *nameend == ' ')500nameend--;501nameend[1] = '\0';502503#ifdef SVR4ARCHIVES504/*505* svr4 names are slash-terminated.506* Also svr4 extended the AR format.507*/508if (memName[0] == '/') {509/* svr4 magic mode; handle it */510switch (ArchSVR4Entry(ar, memName, size, arch)) {511case -1: /* Invalid data */512goto bad_archive;513case 0: /* List of files entry */514continue;515default: /* Got the entry */516break;517}518} else {519if (nameend[0] == '/')520nameend[0] = '\0';521}522#endif523524#ifdef AR_EFMT1525/*526* BSD 4.4 extended AR format: #1/<namelen>, with name as the527* first <namelen> bytes of the file528*/529if (strncmp(memName, AR_EFMT1, sizeof AR_EFMT1 - 1) == 0 &&530ch_isdigit(memName[sizeof AR_EFMT1 - 1])) {531532size_t elen = (size_t)atoi(533memName + sizeof AR_EFMT1 - 1);534535if (elen > MAXPATHLEN)536goto bad_archive;537if (fread(memName, elen, 1, arch) != 1)538goto bad_archive;539memName[elen] = '\0';540if (fseek(arch, -(long)elen, SEEK_CUR) != 0)541goto bad_archive;542if (DEBUG(ARCH) || DEBUG(MAKE))543debug_printf(544"ArchStatMember: "545"Extended format entry for %s\n",546memName);547}548#endif549550{551struct ar_hdr *cached_hdr = bmake_malloc(552sizeof *cached_hdr);553memcpy(cached_hdr, &arh, sizeof arh);554HashTable_Set(&ar->members, memName, cached_hdr);555}556557/* Files are padded with newlines to an even-byte boundary. */558if (fseek(arch, ((long)size + 1) & ~1, SEEK_CUR) != 0)559goto bad_archive;560}561562fclose(arch);563564Lst_Append(&archives, ar);565566return HashTable_FindValue(&ar->members, member);567568bad_archive:569fclose(arch);570HashTable_Done(&ar->members);571free(ar->fnametab);572free(ar);573return NULL;574}575576#ifdef SVR4ARCHIVES577/*578* Parse an SVR4 style entry that begins with a slash.579* If it is "//", then load the table of filenames.580* If it is "/<offset>", then try to substitute the long file name581* from offset of a table previously read.582* If a table is read, the file pointer is moved to the next archive member.583*584* Results:585* -1: Bad data in archive586* 0: A table was loaded from the file587* 1: Name was successfully substituted from table588* 2: Name was not successfully substituted from table589*/590static int591ArchSVR4Entry(Arch *ar, char *inout_name, size_t size, FILE *arch)592{593#define ARLONGNAMES1 "//"594#define ARLONGNAMES2 "/ARFILENAMES"595size_t entry;596char *ptr, *eptr;597598if (strncmp(inout_name, ARLONGNAMES1, sizeof ARLONGNAMES1 - 1) == 0 ||599strncmp(inout_name, ARLONGNAMES2, sizeof ARLONGNAMES2 - 1) == 0) {600601if (ar->fnametab != NULL) {602DEBUG0(ARCH,603"Attempted to redefine an SVR4 name table\n");604return -1;605}606607/*608* This is a table of archive names, so we build one for609* ourselves610*/611ar->fnametab = bmake_malloc(size);612ar->fnamesize = size;613614if (fread(ar->fnametab, size, 1, arch) != 1) {615DEBUG0(ARCH, "Reading an SVR4 name table failed\n");616return -1;617}618eptr = ar->fnametab + size;619for (entry = 0, ptr = ar->fnametab; ptr < eptr; ptr++)620if (*ptr == '/') {621entry++;622*ptr = '\0';623}624DEBUG1(ARCH,625"Found svr4 archive name table with %lu entries\n",626(unsigned long)entry);627return 0;628}629630if (inout_name[1] == ' ' || inout_name[1] == '\0')631return 2;632633entry = (size_t)strtol(&inout_name[1], &eptr, 0);634if ((*eptr != ' ' && *eptr != '\0') || eptr == &inout_name[1]) {635DEBUG1(ARCH, "Could not parse SVR4 name %s\n", inout_name);636return 2;637}638if (entry >= ar->fnamesize) {639DEBUG2(ARCH, "SVR4 entry offset %s is greater than %lu\n",640inout_name, (unsigned long)ar->fnamesize);641return 2;642}643644DEBUG2(ARCH, "Replaced %s with %s\n", inout_name, &ar->fnametab[entry]);645646snprintf(inout_name, MAXPATHLEN + 1, "%s", &ar->fnametab[entry]);647return 1;648}649#endif650651652static bool653ArchiveMember_HasName(const struct ar_hdr *hdr,654const char *name, size_t namelen)655{656const size_t ar_name_len = sizeof hdr->AR_NAME;657const char *ar_name = hdr->AR_NAME;658659if (strncmp(ar_name, name, namelen) != 0)660return false;661662if (namelen >= ar_name_len)663return namelen == ar_name_len;664665/* hdr->AR_NAME is space-padded to the right. */666if (ar_name[namelen] == ' ')667return true;668669/*670* In archives created by GNU binutils 2.27, the member names end671* with a slash.672*/673if (ar_name[namelen] == '/' && ar_name[namelen + 1] == ' ')674return true;675676return false;677}678679/*680* Load the header of an archive member. The mode is "r" for read-only681* access, "r+" for read-write access.682*683* Upon successful return, the archive file is positioned at the start of the684* member's struct ar_hdr. In case of a failure or if the member doesn't685* exist, return NULL.686*687* See ArchStatMember for an almost identical copy of this code.688*/689static FILE *690ArchFindMember(const char *archive, const char *member,691struct ar_hdr *out_arh, const char *mode)692{693FILE *arch;694int size; /* Size of archive member */695char magic[SARMAG];696size_t len;697698arch = fopen(archive, mode);699if (arch == NULL)700return NULL;701702if (fread(magic, SARMAG, 1, arch) != 1 ||703strncmp(magic, ARMAG, SARMAG) != 0) {704fclose(arch);705return NULL;706}707708/* Files are archived using their basename, not the entire path. */709member = str_basename(member);710len = strlen(member);711712while (fread(out_arh, sizeof *out_arh, 1, arch) == 1) {713714if (strncmp(out_arh->AR_FMAG, ARFMAG,715sizeof out_arh->AR_FMAG) != 0) {716fclose(arch);717return NULL;718}719720DEBUG5(ARCH, "Reading archive %s member %.*s mtime %.*s\n",721archive,722(int)sizeof out_arh->AR_NAME, out_arh->AR_NAME,723(int)sizeof out_arh->ar_date, out_arh->ar_date);724725if (ArchiveMember_HasName(out_arh, member, len)) {726if (fseek(arch, -(long)sizeof *out_arh, SEEK_CUR) !=7270) {728fclose(arch);729return NULL;730}731return arch;732}733734#ifdef AR_EFMT1735/*736* BSD 4.4 extended AR format: #1/<namelen>, with name as the737* first <namelen> bytes of the file738*/739if (strncmp(out_arh->AR_NAME, AR_EFMT1, sizeof AR_EFMT1 - 1) ==7400 &&741(ch_isdigit(out_arh->AR_NAME[sizeof AR_EFMT1 - 1]))) {742size_t elen = (size_t)atoi(743&out_arh->AR_NAME[sizeof AR_EFMT1 - 1]);744char ename[MAXPATHLEN + 1];745746if (elen > MAXPATHLEN) {747fclose(arch);748return NULL;749}750if (fread(ename, elen, 1, arch) != 1) {751fclose(arch);752return NULL;753}754ename[elen] = '\0';755if (DEBUG(ARCH) || DEBUG(MAKE))756debug_printf(757"ArchFindMember: "758"Extended format entry for %s\n",759ename);760if (strncmp(ename, member, len) == 0) {761/* Found as extended name */762if (fseek(arch,763-(long)(sizeof(struct ar_hdr) - elen),764SEEK_CUR) != 0) {765fclose(arch);766return NULL;767}768return arch;769}770if (fseek(arch, -(long)elen, SEEK_CUR) != 0) {771fclose(arch);772return NULL;773}774}775#endif776777/* Advance to the next member. */778out_arh->AR_SIZE[sizeof out_arh->AR_SIZE - 1] = '\0';779size = (int)strtol(out_arh->AR_SIZE, NULL, 10);780/* Files are padded with newlines to an even-byte boundary. */781if (fseek(arch, (size + 1) & ~1L, SEEK_CUR) != 0) {782fclose(arch);783return NULL;784}785}786787fclose(arch);788return NULL;789}790791/*792* Update the ar_date of the member of an archive, on disk but not in the793* GNode. Update the st_mtime of the entire archive as well. For a library,794* it may be required to run ranlib after this.795*/796void797Arch_Touch(GNode *gn)798{799FILE *f;800struct ar_hdr arh;801802f = ArchFindMember(GNode_VarArchive(gn), GNode_VarMember(gn), &arh,803"r+");804if (f == NULL)805return;806807snprintf(arh.ar_date, sizeof arh.ar_date, "%-ld", (unsigned long)now);808(void)fwrite(&arh, sizeof arh, 1, f);809fclose(f); /* TODO: handle errors */810}811812/*813* Given a node which represents a library, touch the thing, making sure that814* the table of contents is also touched.815*816* Both the modification time of the library and of the RANLIBMAG member are817* set to 'now'.818*/819void820Arch_TouchLib(GNode *gn MAKE_ATTR_UNUSED)821{822#ifdef RANLIBMAG823FILE *f;824struct ar_hdr arh; /* Header describing table of contents */825struct utimbuf times;826827f = ArchFindMember(gn->path, RANLIBMAG, &arh, "r+");828if (f == NULL)829return;830831snprintf(arh.ar_date, sizeof arh.ar_date, "%-ld", (unsigned long)now);832(void)fwrite(&arh, sizeof arh, 1, f);833fclose(f); /* TODO: handle errors */834835times.actime = times.modtime = now;836utime(gn->path, ×); /* TODO: handle errors */837#endif838}839840/*841* Update the mtime of the GNode with the mtime from the archive member on842* disk (or in the cache).843*/844void845Arch_UpdateMTime(GNode *gn)846{847struct ar_hdr *arh;848849arh = ArchStatMember(GNode_VarArchive(gn), GNode_VarMember(gn), true);850if (arh != NULL)851gn->mtime = (time_t)strtol(arh->ar_date, NULL, 10);852else853gn->mtime = 0;854}855856/*857* Given a nonexistent archive member's node, update gn->mtime from its858* archived form, if it exists.859*/860void861Arch_UpdateMemberMTime(GNode *gn)862{863GNodeListNode *ln;864865for (ln = gn->parents.first; ln != NULL; ln = ln->next) {866GNode *pgn = ln->datum;867868if (pgn->type & OP_ARCHV) {869/*870* If the parent is an archive specification and is871* being made and its member's name matches the name872* of the node we were given, record the modification873* time of the parent in the child. We keep searching874* its parents in case some other parent requires this875* child to exist.876*/877const char *nameStart = strchr(pgn->name, '(') + 1;878const char *nameEnd = strchr(nameStart, ')');879size_t nameLen = (size_t)(nameEnd - nameStart);880881if (pgn->flags.remake &&882strncmp(nameStart, gn->name, nameLen) == 0) {883Arch_UpdateMTime(pgn);884gn->mtime = pgn->mtime;885}886} else if (pgn->flags.remake) {887/*888* Something which isn't a library depends on the889* existence of this target, so it needs to exist.890*/891gn->mtime = 0;892break;893}894}895}896897/*898* Search for a library along the given search path.899*900* The node's 'path' field is set to the found path (including the901* actual file name, not -l...). If the system can handle the -L902* flag when linking (or we cannot find the library), we assume that903* the user has placed the .LIBS variable in the final linking904* command (or the linker will know where to find it) and set the905* TARGET variable for this node to be the node's name. Otherwise,906* we set the TARGET variable to be the full path of the library,907* as returned by Dir_FindFile.908*/909void910Arch_FindLib(GNode *gn, SearchPath *path)911{912char *libName = str_concat3("lib", gn->name + 2, ".a");913gn->path = Dir_FindFile(libName, path);914free(libName);915916Var_Set(gn, TARGET, gn->name);917}918919static bool920RanlibOODate(const GNode *gn MAKE_ATTR_UNUSED)921{922#ifdef RANLIBMAG923struct ar_hdr *arh; /* Header for __.SYMDEF */924int tocModTime; /* The table-of-contents' mod time */925926arh = ArchStatMember(gn->path, RANLIBMAG, false);927928if (arh == NULL) {929/* A library without a table of contents is out-of-date. */930if (DEBUG(ARCH) || DEBUG(MAKE))931debug_printf("no toc...");932return true;933}934935tocModTime = (int)strtol(arh->ar_date, NULL, 10);936937if (DEBUG(ARCH) || DEBUG(MAKE))938debug_printf("%s modified %s...",939RANLIBMAG, Targ_FmtTime(tocModTime));940return gn->youngestChild == NULL ||941gn->youngestChild->mtime > tocModTime;942#else943return false;944#endif945}946947/*948* Decide if a node with the OP_LIB attribute is out-of-date.949* The library is cached if it hasn't been already.950*951* There are several ways for a library to be out-of-date that are not952* available to ordinary files. In addition, there are ways that are open to953* regular files that are not available to libraries.954*955* A library that is only used as a source is never considered out-of-date by956* itself. This does not preclude the library's modification time from making957* its parent be out-of-date. A library will be considered out-of-date for958* any of these reasons, given that it is a target on a dependency line959* somewhere:960*961* Its modification time is less than that of one of its sources962* (gn->mtime < gn->youngestChild->mtime).963*964* Its modification time is greater than the time at which the make965* began (i.e. it's been modified in the course of the make, probably966* by archiving).967*968* The modification time of one of its sources is greater than the one969* of its RANLIBMAG member (i.e. its table of contents is out-of-date).970* We don't compare the archive time vs. TOC time because they can be971* too close. In my opinion we should not bother with the TOC at all972* since this is used by 'ar' rules that affect the data contents of the973* archive, not by ranlib rules, which affect the TOC.974*/975bool976Arch_LibOODate(GNode *gn)977{978979if (gn->type & OP_PHONY)980return true;981if (!GNode_IsTarget(gn) && Lst_IsEmpty(&gn->children))982return false;983if ((!Lst_IsEmpty(&gn->children) && gn->youngestChild == NULL) ||984(gn->mtime > now) ||985(gn->youngestChild != NULL &&986gn->mtime < gn->youngestChild->mtime))987return true;988return RanlibOODate(gn);989}990991/* Initialize the archives module. */992void993Arch_Init(void)994{995Lst_Init(&archives);996}997998#ifdef CLEANUP999/* Clean up the archives module. */1000void1001Arch_End(void)1002{1003ArchListNode *ln;10041005for (ln = archives.first; ln != NULL; ln = ln->next)1006ArchFree(ln->datum);1007Lst_Done(&archives);1008}1009#endif10101011bool1012Arch_IsLib(GNode *gn)1013{1014char buf[8];1015int fd;1016bool isLib;10171018if ((fd = open(gn->path, O_RDONLY)) == -1)1019return false;1020isLib = read(fd, buf, sizeof buf) == sizeof buf1021&& memcmp(buf, "!<arch>\n", sizeof buf) == 0;1022(void)close(fd);1023return isLib;1024}102510261027