ar.c 35 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
// Inferno utils/iar/ar.c
// http://code.google.com/p/inferno-os/source/browse/utils/iar/ar.c
//
//	Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
//	Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
//	Portions Copyright © 1997-1999 Vita Nuova Limited
//	Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
//	Portions Copyright © 2004,2006 Bruce Ellis
//	Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
//	Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
//	Portions Copyright © 2009 The Go Authors. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/*
 * ar - portable (ascii) format version
 */

/* protect a couple of our names */
#define select your_select
#define rcmd your_rcmd

#include <u.h>
Russ Cox's avatar
Russ Cox committed
40
#include <time.h>
41 42
#include <libc.h>
#include <bio.h>
Rob Pike's avatar
Rob Pike committed
43
#include <mach.h>
44
#include "../../libmach/obj.h"
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
#include <ar.h>

#undef select
#undef rcmd

/*
 *	The algorithm uses up to 3 temp files.  The "pivot member" is the
 *	archive member specified by and a, b, or i option.  The temp files are
 *	astart - contains existing members up to and including the pivot member.
 *	amiddle - contains new files moved or inserted behind the pivot.
 *	aend - contains the existing members that follow the pivot member.
 *	When all members have been processed, function 'install' streams the
 * 	temp files, in order, back into the archive.
 */

typedef struct	Arsymref
{
	char	*name;
63
	char *file;
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
	int	type;
	int	len;
	vlong	offset;
	struct	Arsymref *next;
} Arsymref;

typedef struct	Armember	/* Temp file entry - one per archive member */
{
	struct Armember	*next;
	struct ar_hdr	hdr;
	long		size;
	long		date;
	void		*member;
} Armember;

typedef	struct Arfile		/* Temp file control block - one per tempfile */
{
	int	paged;		/* set when some data paged to disk */
	char	*fname;		/* paging file name */
	int	fd;		/* paging file descriptor */
	vlong	size;
	Armember *head;		/* head of member chain */
	Armember *tail;		/* tail of member chain */
	Arsymref *sym;		/* head of defined symbol chain */
} Arfile;

typedef struct Hashchain
{
	char	*name;
93
	char *file;
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
	struct Hashchain *next;
} Hashchain;

#define	NHASH	1024

/*
 *	macro to portably read/write archive header.
 *	'cmd' is read/write/Bread/Bwrite, etc.
 */
#define	HEADER_IO(cmd, f, h)	cmd(f, h.name, sizeof(h.name)) != sizeof(h.name)\
				|| cmd(f, h.date, sizeof(h.date)) != sizeof(h.date)\
				|| cmd(f, h.uid, sizeof(h.uid)) != sizeof(h.uid)\
				|| cmd(f, h.gid, sizeof(h.gid)) != sizeof(h.gid)\
				|| cmd(f, h.mode, sizeof(h.mode)) != sizeof(h.mode)\
				|| cmd(f, h.size, sizeof(h.size)) != sizeof(h.size)\
				|| cmd(f, h.fmag, sizeof(h.fmag)) != sizeof(h.fmag)

		/* constants and flags */
char	*man =		"mrxtdpq";
113
char	*opt =		"uvnbailogS";
114 115 116 117
char	artemp[] =	"/tmp/vXXXXX";
char	movtemp[] =	"/tmp/v1XXXXX";
char	tailtemp[] =	"/tmp/v2XXXXX";
char	symdef[] =	"__.SYMDEF";
118
char	pkgdef[] =	"__.PKGDEF";
119 120 121 122

int	aflag;				/* command line flags */
int	bflag;
int	cflag;
123
int	gflag;
124 125 126
int	oflag;
int	uflag;
int	vflag;
127
int	Pflag;	/* remove leading file prefix */
128
int	Sflag;	/* force mark Go package as safe */
129

130 131
int	errors;

132 133 134
Arfile *astart, *amiddle, *aend;	/* Temp file control block pointers */
int	allobj = 1;			/* set when all members are object files of the same type */
int	symdefsize;			/* size of symdef file */
135
char	*pkgstmt;		/* string "package foo" */
136
char	*objhdr;		/* string "go object darwin 386 release.2010-01-01 2345+" */
137 138
int	dupfound;			/* flag for duplicate symbol */
Hashchain	*hash[NHASH];		/* hash table of text symbols */
Russ Cox's avatar
Russ Cox committed
139

140 141 142 143 144 145
#define	ARNAMESIZE	sizeof(astart->tail->hdr.name)

char	poname[ARNAMESIZE+1];		/* name of pivot member */
char	*file;				/* current file or member being worked on */
Biobuf	bout;
Biobuf bar;
146
char	*prefix;
147 148 149 150 151

void	arcopy(Biobuf*, Arfile*, Armember*);
int	arcreate(char*);
void	arfree(Arfile*);
void	arinsert(Arfile*, Armember*);
Russ Cox's avatar
6g:  
Russ Cox committed
152 153
void	*armalloc(int);
char *arstrdup(char*);
154
void	armove(Biobuf*, Arfile*, Armember*);
155
void	arread(Biobuf*, Armember*);
156 157 158
void	arstream(int, Arfile*);
int	arwrite(int, Armember*);
int	bamatch(char*, char*);
159
int	duplicate(char*, char**);
160
Armember *getdir(Biobuf*);
Russ Cox's avatar
6g:  
Russ Cox committed
161
void	getpkgdef(char**, int*);
162 163
int	getspace(void);
void	install(char*, Arfile*, Arfile*, Arfile*, int);
Russ Cox's avatar
6g:  
Russ Cox committed
164
void	loadpkgdata(char*, int);
165 166 167 168 169 170 171 172 173 174 175
void	longt(Armember*);
int	match(int, char**);
void	mesg(int, char*);
Arfile	*newtempfile(char*);
Armember *newmember(void);
void	objsym(Sym*, void*);
int	openar(char*, int, int);
int	page(Arfile*);
void	pmode(long);
void	rl(int);
void	scanobj(Biobuf*, Arfile*, long);
176
void	scanpkg(Biobuf*, long);
177 178 179 180 181 182 183 184
void	select(int*, long);
void	setcom(void(*)(char*, int, char**));
void	skip(Biobuf*, vlong);
int	symcomp(void*, void*);
void	trim(char*, char*, int);
void	usage(void);
void	wrerr(void);
void	wrsym(Biobuf*, long, Arsymref*);
185
int	arread_cutprefix(Biobuf*, Armember*);
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

void	rcmd(char*, int, char**);		/* command processing */
void	dcmd(char*, int, char**);
void	xcmd(char*, int, char**);
void	tcmd(char*, int, char**);
void	pcmd(char*, int, char**);
void	mcmd(char*, int, char**);
void	qcmd(char*, int, char**);
void	(*comfun)(char*, int, char**);

void
main(int argc, char *argv[])
{
	char *cp;

	Binit(&bout, 1, OWRITE);
	if(argc < 3)
		usage();
	for (cp = argv[1]; *cp; cp++) {
		switch(*cp) {
		case 'a':	aflag = 1;	break;
		case 'b':	bflag = 1;	break;
		case 'c':	cflag = 1;	break;
		case 'd':	setcom(dcmd);	break;
210
		case 'g':	gflag = 1; break;
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
		case 'i':	bflag = 1;	break;
		case 'l':
				strcpy(artemp, "vXXXXX");
				strcpy(movtemp, "v1XXXXX");
				strcpy(tailtemp, "v2XXXXX");
				break;
		case 'm':	setcom(mcmd);	break;
		case 'o':	oflag = 1;	break;
		case 'p':	setcom(pcmd);	break;
		case 'q':	setcom(qcmd);	break;
		case 'r':	setcom(rcmd);	break;
		case 't':	setcom(tcmd);	break;
		case 'u':	uflag = 1;	break;
		case 'v':	vflag = 1;	break;
		case 'x':	setcom(xcmd);	break;
226
		case 'S':	Sflag = 1;  break;
227
		case 'P':	Pflag = 1;  break;
228
		default:
Rob Pike's avatar
Rob Pike committed
229
			fprint(2, "gopack: bad option `%c'\n", *cp);
230 231 232 233
			exits("error");
		}
	}
	if (aflag && bflag) {
Rob Pike's avatar
Rob Pike committed
234
		fprint(2, "gopack: only one of 'a' and 'b' can be specified\n");
235 236 237 238 239 240 241 242 243
		usage();
	}
	if(aflag || bflag) {
		trim(argv[2], poname, sizeof(poname));
		argv++;
		argc--;
		if(argc < 3)
			usage();
	}
244 245 246 247 248 249 250 251 252
	if(Pflag) {
		if(argc < 4) {
			fprint(2, "gopack: P flag requires prefix argument\n");
			usage();
		}
		prefix = argv[2];
		argv++;
		argc--;
	}
253 254
	if(comfun == 0) {
		if(uflag == 0) {
Rob Pike's avatar
Rob Pike committed
255
			fprint(2, "gopack: one of [%s] must be specified\n", man);
256 257 258 259 260 261 262 263
			usage();
		}
		setcom(rcmd);
	}
	cp = argv[2];
	argc -= 3;
	argv += 3;
	(*comfun)(cp, argc, argv);	/* do the command */
264 265
	if(errors && cflag)
		remove(cp);
266 267 268
	cp = 0;
	while (argc--) {
		if (*argv) {
Rob Pike's avatar
Rob Pike committed
269
			fprint(2, "gopack: %s not found\n", *argv);
270 271 272 273
			cp = "error";
		}
		argv++;
	}
274 275
	if (errors)
		cp = "error";
276 277 278 279 280 281 282 283 284 285
	exits(cp);
}
/*
 *	select a command
 */
void
setcom(void (*fun)(char *, int, char**))
{

	if(comfun != 0) {
Rob Pike's avatar
Rob Pike committed
286
		fprint(2, "gopack: only one of [%s] allowed\n", man);
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
		usage();
	}
	comfun = fun;
}
/*
 *	perform the 'r' and 'u' commands
 */
void
rcmd(char *arname, int count, char **files)
{
	int fd;
	int i;
	Arfile *ap;
	Armember *bp;
	Dir *d;
	Biobuf *bfile;

	fd = openar(arname, ORDWR, 1);
	if (fd >= 0) {
		Binit(&bar, fd, OREAD);
		Bseek(&bar,seek(fd,0,1), 1);
	}
	astart = newtempfile(artemp);
	ap = astart;
	aend = 0;
	for(i = 0; fd >= 0; i++) {
		bp = getdir(&bar);
		if (!bp)
			break;
		if (bamatch(file, poname)) {		/* check for pivot */
			aend = newtempfile(tailtemp);
			ap = aend;
		}
			/* pitch symdef file */
		if (i == 0 && strcmp(file, symdef) == 0) {
			skip(&bar, bp->size);
			continue;
324 325 326 327 328
		}
			/* pitch pkgdef file */
		if (gflag && strcmp(file, pkgdef) == 0) {
			skip(&bar, bp->size);
			continue;
329
		}
330 331 332 333 334 335 336 337 338 339
		/*
		 * the plan 9 ar treats count == 0 as equivalent
		 * to listing all the archive's files on the command line:
		 * it will try to open every file name in the archive
		 * and copy that file into the archive if it exists.
		 * for go we disable that behavior, because we use
		 * r with no files to make changes to the archive itself,
		 * using the S or P flags.
		 */
		if (!match(count, files)) {
340 341 342 343 344 345
			scanobj(&bar, ap, bp->size);
			arcopy(&bar, ap, bp);
			continue;
		}
		bfile = Bopen(file, OREAD);
		if (!bfile) {
346
			if (count != 0) {
Rob Pike's avatar
Rob Pike committed
347
				fprint(2, "gopack: cannot open %s\n", file);
348 349
				errors++;
			}
350 351 352 353 354 355
			scanobj(&bar, ap, bp->size);
			arcopy(&bar, ap, bp);
			continue;
		}
		d = dirfstat(Bfildes(bfile));
		if(d == nil)
Rob Pike's avatar
Rob Pike committed
356
			fprint(2, "gopack: cannot stat %s: %r\n", file);
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
		if (uflag && (d==nil || d->mtime <= bp->date)) {
			scanobj(&bar, ap, bp->size);
			arcopy(&bar, ap, bp);
			Bterm(bfile);
			free(d);
			continue;
		}
		mesg('r', file);
		skip(&bar, bp->size);
		scanobj(bfile, ap, d->length);
		free(d);
		armove(bfile, ap, bp);
		Bterm(bfile);
	}
	if(fd >= 0)
		close(fd);
		/* copy in remaining files named on command line */
	for (i = 0; i < count; i++) {
		file = files[i];
		if(file == 0)
			continue;
		files[i] = 0;
		bfile = Bopen(file, OREAD);
380
		if (!bfile) {
Rob Pike's avatar
Rob Pike committed
381
			fprint(2, "gopack: cannot open %s\n", file);
382 383
			errors++;
		} else {
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
			mesg('a', file);
			d = dirfstat(Bfildes(bfile));
			if (d == nil)
				fprint(2, "can't stat %s\n", file);
			else {
				scanobj(bfile, astart, d->length);
				armove(bfile, astart, newmember());
				free(d);
			}
			Bterm(bfile);
		}
	}
	if(fd < 0 && !cflag)
		install(arname, astart, 0, aend, 1);	/* issue 'creating' msg */
	else
		install(arname, astart, 0, aend, 0);
}

void
dcmd(char *arname, int count, char **files)
{
	Armember *bp;
	int fd, i;

	if (!count)
		return;
	fd = openar(arname, ORDWR, 0);
	Binit(&bar, fd, OREAD);
	Bseek(&bar,seek(fd,0,1), 1);
	astart = newtempfile(artemp);
	for (i = 0; bp = getdir(&bar); i++) {
		if(match(count, files)) {
			mesg('d', file);
			skip(&bar, bp->size);
			if (strcmp(file, symdef) == 0)
				allobj = 0;
420 421 422 423 424
		} else if (i == 0 && strcmp(file, symdef) == 0) {
			skip(&bar, bp->size);
		} else if (gflag && strcmp(file, pkgdef) == 0) {
			skip(&bar, bp->size);
		} else {
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
			scanobj(&bar, astart, bp->size);
			arcopy(&bar, astart, bp);
		}
	}
	close(fd);
	install(arname, astart, 0, 0, 0);
}

void
xcmd(char *arname, int count, char **files)
{
	int fd, f, mode, i;
	Armember *bp;
	Dir dx;

	fd = openar(arname, OREAD, 0);
	Binit(&bar, fd, OREAD);
	Bseek(&bar,seek(fd,0,1), 1);
	i = 0;
	while (bp = getdir(&bar)) {
		if(count == 0 || match(count, files)) {
			mode = strtoul(bp->hdr.mode, 0, 8) & 0777;
			f = create(file, OWRITE, mode);
			if(f < 0) {
Rob Pike's avatar
Rob Pike committed
449
				fprint(2, "gopack: %s cannot create\n", file);
450 451 452 453 454 455
				skip(&bar, bp->size);
			} else {
				mesg('x', file);
				arcopy(&bar, 0, bp);
				if (write(f, bp->member, bp->size) < 0)
					wrerr();
Russ Cox's avatar
Russ Cox committed
456
				if(oflag && bp->date != 0) {
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
					nulldir(&dx);
					dx.atime = bp->date;
					dx.mtime = bp->date;
					if(dirwstat(file, &dx) < 0)
						perror(file);
				}
				free(bp->member);
				close(f);
			}
			free(bp);
			if (count && ++i >= count)
				break;
		} else {
			skip(&bar, bp->size);
			free(bp);
		}
	}
	close(fd);
}
void
pcmd(char *arname, int count, char **files)
{
	int fd;
	Armember *bp;

	fd = openar(arname, OREAD, 0);
	Binit(&bar, fd, OREAD);
	Bseek(&bar,seek(fd,0,1), 1);
	while(bp = getdir(&bar)) {
		if(count == 0 || match(count, files)) {
			if(vflag)
				print("\n<%s>\n\n", file);
			arcopy(&bar, 0, bp);
			if (write(1, bp->member, bp->size) < 0)
				wrerr();
		} else
			skip(&bar, bp->size);
		free(bp);
	}
	close(fd);
}
void
mcmd(char *arname, int count, char **files)
{
	int fd, i;
	Arfile *ap;
	Armember *bp;

	if (count == 0)
		return;
	fd = openar(arname, ORDWR, 0);
	Binit(&bar, fd, OREAD);
	Bseek(&bar,seek(fd,0,1), 1);
	astart = newtempfile(artemp);
	amiddle = newtempfile(movtemp);
	aend = 0;
	ap = astart;
	for (i = 0; bp = getdir(&bar); i++) {
		if (bamatch(file, poname)) {
			aend = newtempfile(tailtemp);
			ap = aend;
		}
		if(match(count, files)) {
			mesg('m', file);
			scanobj(&bar, amiddle, bp->size);
			arcopy(&bar, amiddle, bp);
523
		} else if (ap == astart && i == 0 && strcmp(file, symdef) == 0) {
524 525 526 527 528 529
			/*
			 * pitch the symdef file if it is at the beginning
			 * of the archive and we aren't inserting in front
			 * of it (ap == astart).
			 */
			skip(&bar, bp->size);
530 531 532 533 534 535 536
		} else if (ap == astart && gflag && strcmp(file, pkgdef) == 0) {
			/*
			 * pitch the pkgdef file if we aren't inserting in front
			 * of it (ap == astart).
			 */
			skip(&bar, bp->size);
		} else {
537 538 539 540 541 542
			scanobj(&bar, ap, bp->size);
			arcopy(&bar, ap, bp);
		}
	}
	close(fd);
	if (poname[0] && aend == 0)
Rob Pike's avatar
Rob Pike committed
543
		fprint(2, "gopack: %s not found - files moved to end.\n", poname);
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
	install(arname, astart, amiddle, aend, 0);
}
void
tcmd(char *arname, int count, char **files)
{
	int fd;
	Armember *bp;
	char name[ARNAMESIZE+1];

	fd = openar(arname, OREAD, 0);
	Binit(&bar, fd, OREAD);
	Bseek(&bar,seek(fd,0,1), 1);
	while(bp = getdir(&bar)) {
		if(count == 0 || match(count, files)) {
			if(vflag)
				longt(bp);
			trim(file, name, ARNAMESIZE);
			Bprint(&bout, "%s\n", name);
		}
		skip(&bar, bp->size);
		free(bp);
	}
	close(fd);
}
void
qcmd(char *arname, int count, char **files)
{
	int fd, i;
	Armember *bp;
	Biobuf *bfile;

	if(aflag || bflag) {
Rob Pike's avatar
Rob Pike committed
576
		fprint(2, "gopack: abi not allowed with q\n");
577 578 579 580 581
		exits("error");
	}
	fd = openar(arname, ORDWR, 1);
	if (fd < 0) {
		if(!cflag)
Rob Pike's avatar
Rob Pike committed
582
			fprint(2, "gopack: creating %s\n", arname);
583 584 585 586 587 588 589 590 591 592 593 594
		fd = arcreate(arname);
	}
	Binit(&bar, fd, OREAD);
	Bseek(&bar,seek(fd,0,1), 1);
	/* leave note group behind when writing archive; i.e. sidestep interrupts */
	rfork(RFNOTEG);
	Bseek(&bar, 0, 2);
	bp = newmember();
	for(i=0; i<count && files[i]; i++) {
		file = files[i];
		files[i] = 0;
		bfile = Bopen(file, OREAD);
595
		if(!bfile) {
Rob Pike's avatar
Rob Pike committed
596
			fprint(2, "gopack: cannot open %s\n", file);
597 598
			errors++;
		} else {
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
			mesg('q', file);
			armove(bfile, 0, bp);
			if (!arwrite(fd, bp))
				wrerr();
			free(bp->member);
			bp->member = 0;
			Bterm(bfile);
		}
	}
	free(bp);
	close(fd);
}

/*
 *	extract the symbol references from an object file
 */
void
scanobj(Biobuf *b, Arfile *ap, long size)
{
	int obj;
619
	vlong offset, offset1;
620 621
	Dir *d;
	static int lastobj = -1;
622
	uchar buf[4];
Yasuhiro Matsumoto's avatar
Yasuhiro Matsumoto committed
623
	char *p;
624 625 626 627 628 629

	if (!allobj)			/* non-object file encountered */
		return;
	offset = Boffset(b);
	obj = objtype(b, 0);
	if (obj < 0) {			/* not an object file */
630 631 632 633 634 635 636
		/* maybe a foreign object file */
		Bseek(b, offset, 0);
		memset(buf, 0, sizeof buf);
		Bread(b, buf, 4);
		
		/* maybe a foreign object file?  that's okay */
		if((buf[0] == 0x7F && buf[1] == 'E' && buf[2] == 'L' && buf[3] == 'F') ||   // ELF
Wei Guangjing's avatar
Wei Guangjing committed
637
		   (buf[0] == 0x4c && buf[1] == 0x01 || buf[0] == 0x64 && buf[1] == 0x86) || // Windows PE
638 639 640 641 642 643
		   (buf[0] == 0xFE && buf[1] == 0xED && buf[2] == 0xFA && (buf[3]&~1) == 0xCE) ||  // Mach-O big-endian
		   (buf[3] == 0xFE && buf[2] == 0xED && buf[1] == 0xFA && (buf[0]&~1) == 0xCE)) {  // Mach-O little-endian
			Bseek(b, offset, 0);
			return;
		}
		
644
		if (!gflag || strcmp(file, pkgdef) != 0) {  /* don't clear allobj if it's pkg defs */
Rob Pike's avatar
Rob Pike committed
645
			fprint(2, "gopack: non-object file %s\n", file);
646
			errors++;
647
			allobj = 0;
648
		}
649
		d = dirfstat(Bfildes(b));
650
		if (d != nil && d->length == 0) {
Rob Pike's avatar
Rob Pike committed
651
			fprint(2, "gopack: zero length file %s\n", file);
652 653
			errors++;
		}
654 655 656 657
		free(d);
		Bseek(b, offset, 0);
		return;
	}
658 659 660 661 662 663 664 665 666 667 668 669 670 671

	offset1 = Boffset(b);
	Bseek(b, offset, 0);
	p = Brdstr(b, '\n', 1);
	Bseek(b, offset1, 0);
	if(p == nil || strncmp(p, "go object ", 10) != 0) {
		fprint(2, "gopack: malformed object file %s\n", file);
		errors++;
		Bseek(b, offset, 0);
		free(p);
		return;
	}
	
	if ((lastobj >= 0 && obj != lastobj) || (objhdr != nil && strcmp(p, objhdr) != 0)) {
Rob Pike's avatar
Rob Pike committed
672
		fprint(2, "gopack: inconsistent object file %s\n", file);
673
		errors++;
674
		allobj = 0;
675
		free(p);
676 677 678
		return;
	}
	lastobj = obj;
679 680 681 682 683
	if(objhdr == nil)
		objhdr = p;
	else
		free(p);
		
684
	if (!readar(b, obj, offset+size, 0)) {
Rob Pike's avatar
Rob Pike committed
685
		fprint(2, "gopack: invalid symbol reference in file %s\n", file);
686
		errors++;
687 688 689 690 691 692
		allobj = 0;
		Bseek(b, offset, 0);
		return;
	}
	Bseek(b, offset, 0);
	objtraverse(objsym, ap);
693 694 695 696 697 698 699
	if (gflag) {
		scanpkg(b, size);
		Bseek(b, offset, 0);
	}
}

/*
Russ Cox's avatar
Russ Cox committed
700
 *	does line contain substring (length-limited)
701 702 703 704 705
 */
int
strstrn(char *line, int len, char *sub)
{
	int i;
Russ Cox's avatar
Russ Cox committed
706
	int sublen;
707 708 709 710 711 712 713 714 715

	sublen = strlen(sub);
	for (i = 0; i < len - sublen; i++)
		if (memcmp(line+i, sub, sublen) == 0)
			return 1;
	return 0;
}

/*
Russ Cox's avatar
Russ Cox committed
716 717
 *	package import data
 */
718
int	safe = 1;
Russ Cox's avatar
Russ Cox committed
719 720 721 722 723 724
char*	pkgname;
char*	importblock;

void
getpkgdef(char **datap, int *lenp)
{
725
	char *tag, *hdr;
726

Russ Cox's avatar
Russ Cox committed
727 728 729 730 731
	if(pkgname == nil) {
		pkgname = "__emptyarchive__";
		importblock = "";
	}
	
732 733 734 735
	tag = "";
	if(safe || Sflag)
		tag = "safe";

736 737 738 739 740
	hdr = "empty archive";
	if(objhdr != nil)
		hdr = objhdr;

	*datap = smprint("%s\nimport\n$$\npackage %s %s\n%s\n$$\n", hdr, pkgname, tag, importblock);
Russ Cox's avatar
Russ Cox committed
741 742 743 744 745 746
	*lenp = strlen(*datap);
}

/*
 *	extract the package definition data from an object file.
 *	there can be only one.
747 748 749 750 751 752 753
 */
void
scanpkg(Biobuf *b, long size)
{
	long n;
	int c;
	long start, end, pkgsize;
Russ Cox's avatar
6g:  
Russ Cox committed
754
	char *data, *line, pkgbuf[1024], *pkg;
755 756 757
	int first;

	/*
Russ Cox's avatar
Russ Cox committed
758
	 * scan until $$
759 760 761 762 763 764
	 */
	for (n=0; n<size; ) {
		c = Bgetc(b);
		if(c == Beof)
			break;
		n++;
Russ Cox's avatar
Russ Cox committed
765
		if(c != '$')
766 767 768 769 770
			continue;
		c = Bgetc(b);
		if(c == Beof)
			break;
		n++;
Russ Cox's avatar
Russ Cox committed
771
		if(c != '$')
772 773 774
			continue;
		goto foundstart;
	}
Rob Pike's avatar
Rob Pike committed
775
	// fprint(2, "gopack: warning: no package import section in %s\n", file);
776
	safe = 0;	// non-Go file (C or assembly)
777 778 779
	return;

foundstart:
Russ Cox's avatar
6g:  
Russ Cox committed
780 781 782 783 784
	/* found $$; skip rest of line */
	while((c = Bgetc(b)) != '\n')
		if(c == Beof)
			goto bad;

785
	/* how big is it? */
Russ Cox's avatar
6g:  
Russ Cox committed
786
	pkg = nil;
787 788 789
	first = 1;
	start = end = 0;
	for (n=0; n<size; n+=Blinelen(b)) {
790 791
		line = Brdstr(b, '\n', 0);
		if (line == nil)
792 793
			goto bad;
		if (first && strstrn(line, Blinelen(b), "package ")) {
Russ Cox's avatar
6g:  
Russ Cox committed
794 795 796 797 798 799 800 801
			if (Blinelen(b) > sizeof(pkgbuf)-1)
				goto bad;
			memmove(pkgbuf, line, Blinelen(b));
			pkgbuf[Blinelen(b)] = '\0';
			pkg = pkgbuf;
			while(*pkg == ' ' || *pkg == '\t')
				pkg++;
			if(strncmp(pkg, "package ", 8) != 0)
802
				goto bad;
Russ Cox's avatar
Russ Cox committed
803 804 805 806 807 808 809
			pkg += 8;
			data = pkg;
			while(*pkg != ' ' && *pkg != '\n' && *pkg != '\0')
				pkg++;
			pkgname = armalloc(pkg - data + 1);
			memmove(pkgname, data, pkg - data);
			pkgname[pkg-data] = '\0';
810 811
			if(strcmp(pkg, " safe\n") != 0)
				safe = 0;
812 813
			start = Boffset(b);  // after package statement
			first = 0;
814
			free(line);
815 816
			continue;
		}
817 818
		if(line[0] == '$' && line[1] == '$') {
			free(line);
819
			goto foundend;
820
		}
Russ Cox's avatar
Russ Cox committed
821
		end = Boffset(b);  // before closing $$
822
		free(line);
823 824
	}
bad:
Rob Pike's avatar
Rob Pike committed
825
	fprint(2, "gopack: bad package import section in %s\n", file);
826
	errors++;
827 828 829
	return;

foundend:
Russ Cox's avatar
Russ Cox committed
830 831 832
	if (start == 0)
		return;
	if (end == 0)
833
		goto bad;
Russ Cox's avatar
Russ Cox committed
834 835 836 837
	if(importblock != nil) {
		fprint(2, "gopack: multiple Go object files\n");
		errors++;
		return;
838 839
	}
	pkgsize = end-start;
Russ Cox's avatar
Russ Cox committed
840
	data = armalloc(end - start + 1);
841
	Bseek(b, start, 0);
Russ Cox's avatar
6g:  
Russ Cox committed
842
	if (Bread(b, data, pkgsize) != pkgsize) {
Rob Pike's avatar
Rob Pike committed
843
		fprint(2, "gopack: error reading package import section in %s\n", file);
Russ Cox's avatar
Russ Cox committed
844
		errors++;
845 846
		return;
	}
Russ Cox's avatar
Russ Cox committed
847 848
	data[end-start] = '\0';
	importblock = data;
849 850 851 852 853 854 855 856 857 858 859
}

/*
 *	add text and data symbols to the symbol list
 */
void
objsym(Sym *s, void *p)
{
	int n;
	Arsymref *as;
	Arfile *ap;
860
	char *ofile;
861 862 863 864

	if (s->type != 'T' &&  s->type != 'D')
		return;
	ap = (Arfile*)p;
Russ Cox's avatar
6g:  
Russ Cox committed
865
	as = armalloc(sizeof(Arsymref));
866
	as->offset = ap->size;
Russ Cox's avatar
6g:  
Russ Cox committed
867
	as->name = arstrdup(s->name);
868 869
	as->file = arstrdup(file);
	if(s->type == 'T' && duplicate(as->name, &ofile)) {
870
		dupfound = 1;
871
		fprint(2, "duplicate text symbol: %s and %s: %s\n", as->file, ofile, as->name);
872
		errors++;
873 874 875 876 877
		free(as->name);
		free(as);
		return;
	}
	as->type = s->type;
Russ Cox's avatar
6g:  
Russ Cox committed
878
	n = strlen(s->name);
879 880 881 882 883 884 885 886 887 888
	symdefsize += 4+(n+1)+1;
	as->len = n;
	as->next = ap->sym;
	ap->sym = as;
}

/*
 *	Check the symbol table for duplicate text symbols
 */
int
Russ Cox's avatar
6g:  
Russ Cox committed
889
hashstr(char *name)
890 891
{
	int h;
Russ Cox's avatar
6g:  
Russ Cox committed
892
	char *cp;
893 894 895 896

	h = 0;
	for(cp = name; *cp; h += *cp++)
		h *= 1119;
897 898 899 900 901 902 903 904 905 906
	
	// the code used to say
	//	if(h < 0)
	//		h = ~h;
	// but on gcc 4.3 with -O2 on some systems,
	// the if(h < 0) gets compiled away as not possible.
	// use a mask instead, leaving plenty of bits but
	// definitely not the sign bit.

	return h & 0xfffffff;
Russ Cox's avatar
6g:  
Russ Cox committed
907 908 909
}

int
910
duplicate(char *name, char **ofile)
Russ Cox's avatar
6g:  
Russ Cox committed
911 912 913 914 915
{
	Hashchain *p;
	int h;

	h = hashstr(name) % NHASH;
916 917

	for(p = hash[h]; p; p = p->next)
918 919
		if(strcmp(p->name, name) == 0) {
			*ofile = p->file;
920
			return 1;
921
		}
Russ Cox's avatar
6g:  
Russ Cox committed
922
	p = armalloc(sizeof(Hashchain));
923 924
	p->next = hash[h];
	p->name = name;
925
	p->file = file;
926
	hash[h] = p;
927
	*ofile = nil;
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
	return 0;
}

/*
 *	open an archive and validate its header
 */
int
openar(char *arname, int mode, int errok)
{
	int fd;
	char mbuf[SARMAG];

	fd = open(arname, mode);
	if(fd >= 0){
		if(read(fd, mbuf, SARMAG) != SARMAG || strncmp(mbuf, ARMAG, SARMAG)) {
Rob Pike's avatar
Rob Pike committed
943
			fprint(2, "gopack: %s not in archive format\n", arname);
944 945 946
			exits("error");
		}
	}else if(!errok){
Rob Pike's avatar
Rob Pike committed
947
		fprint(2, "gopack: cannot open %s: %r\n", arname);
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
		exits("error");
	}
	return fd;
}

/*
 *	create an archive and set its header
 */
int
arcreate(char *arname)
{
	int fd;

	fd = create(arname, OWRITE, 0664);
	if(fd < 0){
Rob Pike's avatar
Rob Pike committed
963
		fprint(2, "gopack: cannot create %s: %r\n", arname);
964 965 966 967 968 969 970 971 972 973 974 975 976
		exits("error");
	}
	if(write(fd, ARMAG, SARMAG) != SARMAG)
		wrerr();
	return fd;
}

/*
 *		error handling
 */
void
wrerr(void)
{
Rob Pike's avatar
Rob Pike committed
977
	perror("gopack: write error");
978 979 980 981 982 983
	exits("error");
}

void
rderr(void)
{
Rob Pike's avatar
Rob Pike committed
984
	perror("gopack: read error");
985 986 987 988 989 990
	exits("error");
}

void
phaseerr(int offset)
{
Rob Pike's avatar
Rob Pike committed
991
	fprint(2, "gopack: phase error at offset %d\n", offset);
992 993 994 995 996 997
	exits("error");
}

void
usage(void)
{
998
	fprint(2, "usage: gopack [%s][%s][P prefix] archive files ...\n", opt, man);
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
	exits("error");
}

/*
 *	read the header for the next archive member
 */
Armember *
getdir(Biobuf *b)
{
	Armember *bp;
	char *cp;
	static char name[ARNAMESIZE+1];

	bp = newmember();
	if(HEADER_IO(Bread, b, bp->hdr)) {
		free(bp);
		return 0;
	}
	if(strncmp(bp->hdr.fmag, ARFMAG, sizeof(bp->hdr.fmag)))
		phaseerr(Boffset(b));
	strncpy(name, bp->hdr.name, sizeof(bp->hdr.name));
	cp = name+sizeof(name)-1;
	while(*--cp==' ')
		;
	cp[1] = '\0';
1024
	file = arstrdup(name);
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
	bp->date = strtol(bp->hdr.date, 0, 0);
	bp->size = strtol(bp->hdr.size, 0, 0);
	return bp;
}

/*
 *	Copy the file referenced by fd to the temp file
 */
void
armove(Biobuf *b, Arfile *ap, Armember *bp)
{
	char *cp;
	Dir *d;
1038
	vlong n;
1039 1040 1041

	d = dirfstat(Bfildes(b));
	if (d == nil) {
Rob Pike's avatar
Rob Pike committed
1042
		fprint(2, "gopack: cannot stat %s\n", file);
1043 1044
		return;
	}
1045

1046 1047 1048 1049
	trim(file, bp->hdr.name, sizeof(bp->hdr.name));
	for (cp = strchr(bp->hdr.name, 0);		/* blank pad on right */
		cp < bp->hdr.name+sizeof(bp->hdr.name); cp++)
			*cp = ' ';
Russ Cox's avatar
Russ Cox committed
1050
	sprint(bp->hdr.date, "%-12ld", 0);  // was d->mtime but removed for idempotent builds
1051 1052 1053 1054 1055 1056
	sprint(bp->hdr.uid, "%-6d", 0);
	sprint(bp->hdr.gid, "%-6d", 0);
	sprint(bp->hdr.mode, "%-8lo", d->mode);
	sprint(bp->hdr.size, "%-10lld", d->length);
	strncpy(bp->hdr.fmag, ARFMAG, 2);
	bp->size = d->length;
1057 1058 1059 1060
	arread(b, bp);
	n = bp->size;
	if (n&1)
		n++;
1061 1062
	if (ap) {
		arinsert(ap, bp);
1063
		ap->size += n+SAR_HDR;
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
	}
	free(d);
}

/*
 *	Copy the archive member at the current offset into the temp file.
 */
void
arcopy(Biobuf *b, Arfile *ap, Armember *bp)
{
	long n;

1076
	arread(b, bp);
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
	n = bp->size;
	if (n & 01)
		n++;
	if (ap) {
		arinsert(ap, bp);
		ap->size += n+SAR_HDR;
	}
}

/*
 *	Skip an archive member
 */
void
skip(Biobuf *bp, vlong len)
{
	if (len & 01)
		len++;
	Bseek(bp, len, 1);
}

/*
 *	Stream the three temp files to an archive
 */
void
install(char *arname, Arfile *astart, Arfile *amiddle, Arfile *aend, int createflag)
{
	int fd;

	if(allobj && dupfound) {
		fprint(2, "%s not changed\n", arname);
		return;
	}
	/* leave note group behind when copying back; i.e. sidestep interrupts */
	rfork(RFNOTEG);

	if(createflag)
Rob Pike's avatar
Rob Pike committed
1113
		fprint(2, "gopack: creating %s\n", arname);
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
	fd = arcreate(arname);

	if(allobj)
		rl(fd);

	if (astart) {
		arstream(fd, astart);
		arfree(astart);
	}
	if (amiddle) {
		arstream(fd, amiddle);
		arfree(amiddle);
	}
	if (aend) {
		arstream(fd, aend);
		arfree(aend);
	}
	close(fd);
}

void
rl(int fd)
{
	Biobuf b;
	char *cp;
	struct ar_hdr a;
	long len;
1141
	int headlen;
Russ Cox's avatar
6g:  
Russ Cox committed
1142 1143 1144 1145 1146
	char *pkgdefdata;
	int pkgdefsize;

	pkgdefdata = nil;
	pkgdefsize = 0;
1147 1148 1149 1150 1151 1152 1153

	Binit(&b, fd, OWRITE);
	Bseek(&b,seek(fd,0,1), 0);

	len = symdefsize;
	if(len&01)
		len++;
Russ Cox's avatar
Russ Cox committed
1154
	sprint(a.date, "%-12ld", 0);  // time(0)
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
	sprint(a.uid, "%-6d", 0);
	sprint(a.gid, "%-6d", 0);
	sprint(a.mode, "%-8lo", 0644L);
	sprint(a.size, "%-10ld", len);
	strncpy(a.fmag, ARFMAG, 2);
	strcpy(a.name, symdef);
	for (cp = strchr(a.name, 0);		/* blank pad on right */
		cp < a.name+sizeof(a.name); cp++)
			*cp = ' ';
	if(HEADER_IO(Bwrite, &b, a))
			wrerr();

1167 1168 1169
	headlen = Boffset(&b);
	len += headlen;
	if (gflag) {
Russ Cox's avatar
6g:  
Russ Cox committed
1170 1171
		getpkgdef(&pkgdefdata, &pkgdefsize);
		len += SAR_HDR + pkgdefsize;
1172 1173 1174
		if (len & 1)
			len++;
	}
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
	if (astart) {
		wrsym(&b, len, astart->sym);
		len += astart->size;
	}
	if(amiddle) {
		wrsym(&b, len, amiddle->sym);
		len += amiddle->size;
	}
	if(aend)
		wrsym(&b, len, aend->sym);

	if(symdefsize&0x01)
		Bputc(&b, 0);
1188 1189

	if (gflag) {
Russ Cox's avatar
6g:  
Russ Cox committed
1190
		len = pkgdefsize;
Russ Cox's avatar
Russ Cox committed
1191
		sprint(a.date, "%-12ld", 0);  // time(0)
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
		sprint(a.uid, "%-6d", 0);
		sprint(a.gid, "%-6d", 0);
		sprint(a.mode, "%-8lo", 0644L);
		sprint(a.size, "%-10ld", (len + 1) & ~1);
		strncpy(a.fmag, ARFMAG, 2);
		strcpy(a.name, pkgdef);
		for (cp = strchr(a.name, 0);		/* blank pad on right */
			cp < a.name+sizeof(a.name); cp++)
				*cp = ' ';
		if(HEADER_IO(Bwrite, &b, a))
				wrerr();

Russ Cox's avatar
6g:  
Russ Cox committed
1204
		if (Bwrite(&b, pkgdefdata, pkgdefsize) != pkgdefsize)
1205 1206 1207 1208
			wrerr();
		if(len&0x01)
			Bputc(&b, 0);
	}
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
	Bterm(&b);
}

/*
 *	Write the defined symbols to the symdef file
 */
void
wrsym(Biobuf *bp, long offset, Arsymref *as)
{
	int off;

	while(as) {
		Bputc(bp, as->type);
		off = as->offset+offset;
		Bputc(bp, off);
		Bputc(bp, off>>8);
		Bputc(bp, off>>16);
		Bputc(bp, off>>24);
		if (Bwrite(bp, as->name, as->len+1) != as->len+1)
			wrerr();
		as = as->next;
	}
}

/*
 *	Check if the archive member matches an entry on the command line.
 */
int
match(int count, char **files)
{
	int i;
	char name[ARNAMESIZE+1];

	for(i=0; i<count; i++) {
		if(files[i] == 0)
			continue;
		trim(files[i], name, ARNAMESIZE);
		if(strncmp(name, file, ARNAMESIZE) == 0) {
			file = files[i];
			files[i] = 0;
			return 1;
		}
	}
	return 0;
}

/*
 *	compare the current member to the name of the pivot member
 */
int
bamatch(char *file, char *pivot)
{
	static int state = 0;

	switch(state)
	{
	case 0:			/* looking for position file */
		if (aflag) {
			if (strncmp(file, pivot, ARNAMESIZE) == 0)
				state = 1;
		} else if (bflag) {
			if (strncmp(file, pivot, ARNAMESIZE) == 0) {
				state = 2;	/* found */
				return 1;
			}
		}
		break;
	case 1:			/* found - after previous file */
		state = 2;
		return 1;
	case 2:			/* already found position file */
		break;
	}
	return 0;
}

/*
 *	output a message, if 'v' option was specified
 */
void
mesg(int c, char *file)
{

	if(vflag)
		Bprint(&bout, "%c - %s\n", c, file);
}

/*
 *	isolate file name by stripping leading directories and trailing slashes
 */
void
trim(char *s, char *buf, int n)
{
	char *p;

	for(;;) {
		p = strrchr(s, '/');
		if (!p) {		/* no slash in name */
			strncpy(buf, s, n);
			return;
		}
		if (p[1] != 0) {	/* p+1 is first char of file name */
			strncpy(buf, p+1, n);
			return;
		}
		*p = 0;			/* strip trailing slash */
	}
}

/*
 *	utilities for printing long form of 't' command
 */
#define	SUID	04000
#define	SGID	02000
#define	ROWN	0400
#define	WOWN	0200
#define	XOWN	0100
#define	RGRP	040
#define	WGRP	020
#define	XGRP	010
#define	ROTH	04
#define	WOTH	02
#define	XOTH	01
#define	STXT	01000

void
longt(Armember *bp)
{
	char *cp;
1338
	time_t date;
1339 1340 1341 1342

	pmode(strtoul(bp->hdr.mode, 0, 8));
	Bprint(&bout, "%3ld/%1ld", strtol(bp->hdr.uid, 0, 0), strtol(bp->hdr.gid, 0, 0));
	Bprint(&bout, "%7ld", bp->size);
1343 1344
	date = bp->date;
	cp = ctime(&date);
1345 1346
	/* using unix ctime, not plan 9 time, so cp+20 for year, not cp+24 */
	Bprint(&bout, " %-12.12s %-4.4s ", cp+4, cp+20);
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
}

int	m1[] = { 1, ROWN, 'r', '-' };
int	m2[] = { 1, WOWN, 'w', '-' };
int	m3[] = { 2, SUID, 's', XOWN, 'x', '-' };
int	m4[] = { 1, RGRP, 'r', '-' };
int	m5[] = { 1, WGRP, 'w', '-' };
int	m6[] = { 2, SGID, 's', XGRP, 'x', '-' };
int	m7[] = { 1, ROTH, 'r', '-' };
int	m8[] = { 1, WOTH, 'w', '-' };
int	m9[] = { 2, STXT, 't', XOTH, 'x', '-' };

int	*m[] = { m1, m2, m3, m4, m5, m6, m7, m8, m9};

void
pmode(long mode)
{
	int **mp;

	for(mp = &m[0]; mp < &m[9];)
		select(*mp++, mode);
}

void
select(int *ap, long mode)
{
	int n;

	n = *ap++;
	while(--n>=0 && (mode&*ap++)==0)
		ap++;
	Bputc(&bout, *ap);
}

/*
 *	Temp file I/O subsystem.  We attempt to cache all three temp files in
 *	core.  When we run out of memory we spill to disk.
 *	The I/O model assumes that temp files:
 *		1) are only written on the end
 *		2) are only read from the beginning
 *		3) are only read after all writing is complete.
 *	The architecture uses one control block per temp file.  Each control
 *	block anchors a chain of buffers, each containing an archive member.
 */
Arfile *
newtempfile(char *name)		/* allocate a file control block */
{
	Arfile *ap;

Russ Cox's avatar
6g:  
Russ Cox committed
1396
	ap = armalloc(sizeof(Arfile));
1397 1398 1399 1400 1401 1402 1403
	ap->fname = name;
	return ap;
}

Armember *
newmember(void)			/* allocate a member buffer */
{
Russ Cox's avatar
6g:  
Russ Cox committed
1404
	return armalloc(sizeof(Armember));
1405 1406 1407
}

void
1408
arread(Biobuf *b, Armember *bp)	/* read an image into a member buffer */
1409 1410
{
	int i;
1411
	vlong off;
1412

1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
	bp->member = armalloc(bp->size);
	
	// If P flag is set, let arread_cutprefix try.
	// If it succeeds, we're done.  If not, fall back
	// to a direct copy.
	off = Boffset(b);
	if(Pflag && arread_cutprefix(b, bp))
		return;
	Bseek(b, off, 0);

	i = Bread(b, bp->member, bp->size);
1424 1425 1426 1427 1428
	if (i < 0) {
		free(bp->member);
		bp->member = 0;
		rderr();
	}
1429 1430
	if(bp->size&1)
		Bgetc(b);
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
}

/*
 * insert a member buffer into the member chain
 */
void
arinsert(Arfile *ap, Armember *bp)
{
	bp->next = 0;
	if (!ap->tail)
		ap->head = bp;
	else
		ap->tail->next = bp;
	ap->tail = bp;
}

/*
 *	stream the members in a temp file to the file referenced by 'fd'.
 */
void
arstream(int fd, Arfile *ap)
{
	Armember *bp;
	int i;
	char buf[8192];

	if (ap->paged) {		/* copy from disk */
		seek(ap->fd, 0, 0);
		for (;;) {
			i = read(ap->fd, buf, sizeof(buf));
			if (i < 0)
				rderr();
			if (i == 0)
				break;
			if (write(fd, buf, i) != i)
				wrerr();
		}
		close(ap->fd);
		ap->paged = 0;
	}
		/* dump the in-core buffers */
	for (bp = ap->head; bp; bp = bp->next) {
		if (!arwrite(fd, bp))
			wrerr();
	}
}

/*
 *	write a member to 'fd'.
 */
int
arwrite(int fd, Armember *bp)
{
	int len;

	if(HEADER_IO(write, fd, bp->hdr))
		return 0;
	len = bp->size;
	if (len & 01)
		len++;
	if (write(fd, bp->member, len) != len)
		return 0;
	return 1;
}

/*
 *	Spill a member to a disk copy of a temp file
 */
int
page(Arfile *ap)
{
	Armember *bp;

	bp = ap->head;
	if (!ap->paged) {		/* not yet paged - create file */
		ap->fname = mktemp(ap->fname);
		ap->fd = create(ap->fname, ORDWR|ORCLOSE, 0600);
		if (ap->fd < 0) {
Rob Pike's avatar
Rob Pike committed
1509
			fprint(2,"gopack: can't create temp file\n");
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
			return 0;
		}
		ap->paged = 1;
	}
	if (!arwrite(ap->fd, bp))	/* write member and free buffer block */
		return 0;
	ap->head = bp->next;
	if (ap->tail == bp)
		ap->tail = bp->next;
	free(bp->member);
	free(bp);
	return 1;
}

/*
 *	try to reclaim space by paging.  we try to spill the start, middle,
 *	and end files, in that order.  there is no particular reason for the
 *	ordering.
 */
int
getspace(void)
{
1532
fprint(2, "IN GETSPACE\n");
1533
	if (astart && astart->head && page(astart))
Russ Cox's avatar
6g:  
Russ Cox committed
1534
		return 1;
1535
	if (amiddle && amiddle->head && page(amiddle))
Russ Cox's avatar
6g:  
Russ Cox committed
1536
		return 1;
1537
	if (aend && aend->head && page(aend))
Russ Cox's avatar
6g:  
Russ Cox committed
1538
		return 1;
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
	return 0;
}

void
arfree(Arfile *ap)		/* free a member buffer */
{
	Armember *bp, *next;

	for (bp = ap->head; bp; bp = next) {
		next = bp->next;
		if (bp->member)
			free(bp->member);
		free(bp);
	}
	free(ap);
}

/*
 *	allocate space for a control block or member buffer.  if the malloc
 *	fails we try to reclaim space by spilling previously allocated
 *	member buffers.
 */
Russ Cox's avatar
6g:  
Russ Cox committed
1561
void *
1562 1563 1564 1565
armalloc(int n)
{
	char *cp;

Russ Cox's avatar
Russ Cox committed
1566 1567 1568 1569
	// bump so that arwrite can do the same
	if(n&1)
		n++;

1570 1571 1572 1573 1574 1575 1576
	do {
		cp = malloc(n);
		if (cp) {
			memset(cp, 0, n);
			return cp;
		}
	} while (getspace());
Rob Pike's avatar
Rob Pike committed
1577
	fprint(2, "gopack: out of memory\n");
1578 1579 1580
	exits("malloc");
	return 0;
}
Russ Cox's avatar
6g:  
Russ Cox committed
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592

char *
arstrdup(char *s)
{
	char *t;

	t = armalloc(strlen(s) + 1);
	strcpy(t, s);
	return t;
}


1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698
/*
 *	Parts of libmach we're not supposed
 *	to look at but need for arread_cutprefix.
 */
extern int _read5(Biobuf*, Prog*);
extern int _read6(Biobuf*, Prog*);
extern int _read8(Biobuf*, Prog*);
int (*reader[256])(Biobuf*, Prog*) = {
	[ObjArm] = _read5,
	[ObjAmd64] = _read6,
	[Obj386] = _read8,
};

/*
 *	copy b into bp->member but rewrite object
 *	during copy to drop prefix from all file names.
 *	return 1 if b was recognized as an object file
 *	and copied successfully, 0 otherwise.
 */
int
arread_cutprefix(Biobuf *b, Armember *bp)
{
	vlong offset, o, end;
	int n, t;
	int (*rd)(Biobuf*, Prog*);
	char *w, *inprefix;
	Prog p;
	
	offset = Boffset(b);
	end = offset + bp->size;
	t = objtype(b, nil);
	if(t < 0)
		return 0;
	if((rd = reader[t]) == nil)
		return 0;
	
	// copy header
	w = bp->member;
	n = Boffset(b) - offset;
	Bseek(b, -n, 1);
	if(Bread(b, w, n) != n)
		return 0;
	offset += n;
	w += n;
	
	// read object file one pseudo-instruction at a time,
	// eliding the file name instructions that refer to
	// the prefix.
	memset(&p, 0, sizeof p);
	inprefix = nil;
	while(Boffset(b) < end && rd(b, &p)) {
		if(p.kind == aName && p.type == UNKNOWN && p.sym == 1 && p.id[0] == '<') {
			// part of a file path.
			// we'll keep continuing (skipping the copy)
			// around the loop until either we get to a
			// name piece that should be kept or we see
			// the whole prefix.

			if(inprefix == nil && prefix[0] == '/' && p.id[1] == '/' && p.id[2] == '\0') {
				// leading /
				inprefix = prefix+1;
			} else if(inprefix != nil) {
				// handle subsequent elements
				n = strlen(p.id+1);
				if(strncmp(p.id+1, inprefix, n) == 0 && (inprefix[n] == '/' || inprefix[n] == '\0')) {
					inprefix += n;
					if(inprefix[0] == '/')
						inprefix++;
				}
			}
			
			if(inprefix && inprefix[0] == '\0') {
				// reached end of prefix.
				// if we another path element follows,
				// nudge the offset to skip over the prefix we saw.
				// if not, leave offset alone, to emit the whole name.
				// additional name elements will not be skipped
				// because inprefix is now nil and we won't see another
				// leading / in this name.
				inprefix = nil;
				o = Boffset(b);
				if(o < end && rd(b, &p) && p.kind == aName && p.type == UNKNOWN && p.sym == 1 && p.id[0] == '<') {
					print("skip %lld-%lld\n", offset, o);
					offset = o;
				}
			}
		}

		// copy instructions
		if(!inprefix) {
			n = Boffset(b) - offset;
			Bseek(b, -n, 1);
			if(Bread(b, w, n) != n)
				return 0;
			offset += n;
			w += n;
		}
	}
	bp->size = w - (char*)bp->member;
	sprint(bp->hdr.size, "%-10lld", (vlong)bp->size);
	strncpy(bp->hdr.fmag, ARFMAG, 2);
	Bseek(b, end, 0);
	if(Boffset(b)&1)
		Bgetc(b);
	return 1;
}