walk.c revision 1.39
1/*	$NetBSD: walk.c,v 1.39 2024/04/24 21:59:39 rillig Exp $	*/
2
3/*
4 * Copyright (c) 2001 Wasabi Systems, Inc.
5 * All rights reserved.
6 *
7 * Written by Luke Mewburn for Wasabi Systems, Inc.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 *    must display the following acknowledgement:
19 *      This product includes software developed for the NetBSD Project by
20 *      Wasabi Systems, Inc.
21 * 4. The name of Wasabi Systems, Inc. may not be used to endorse
22 *    or promote products derived from this software without specific prior
23 *    written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
29 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 * POSSIBILITY OF SUCH DAMAGE.
36 */
37
38#if HAVE_NBTOOL_CONFIG_H
39#include "nbtool_config.h"
40#endif
41
42#include <sys/cdefs.h>
43#if defined(__RCSID) && !defined(__lint)
44__RCSID("$NetBSD: walk.c,v 1.39 2024/04/24 21:59:39 rillig Exp $");
45#endif	/* !__lint */
46
47#include <sys/param.h>
48#include <sys/stat.h>
49
50#include <assert.h>
51#include <errno.h>
52#include <fcntl.h>
53#include <stdio.h>
54#include <dirent.h>
55#include <stdlib.h>
56#include <string.h>
57#include <unistd.h>
58#include <util.h>
59
60#include "makefs.h"
61#include "mtree.h"
62
63static	void	 apply_specdir(const char *, NODE *, fsnode *, int);
64static	void	 apply_specentry(const char *, NODE *, fsnode *);
65static	fsnode	*create_fsnode(const char *, const char *, const char *,
66			       struct stat *);
67static	fsinode	*link_check(fsinode *);
68
69/*
70 * fsnode_cmp --
71 *	This function is used by `qsort` so sort one directory's
72 *	entries.  `.` is always first, sollowed by anything else
73 *	as compared by `strcmp()`.
74 */
75static int
76fsnode_cmp(const void *vleft, const void *vright)
77{
78	const fsnode * const *left  = vleft;
79	const fsnode * const *right = vright;
80	const char *lname = (*left)->name, *rname = (*right)->name;
81
82	if (strcmp(lname, ".") == 0)
83		return -1;
84	if (strcmp(rname, ".") == 0)
85		return 1;
86	return strcmp(lname, rname);
87}
88
89static fsnode *
90fsnode_sort(fsnode *first, const char *root, const char *dir)
91{
92	fsnode **list, **listptr;
93	size_t num = 0;
94
95	for (fsnode *tmp = first; tmp; tmp = tmp->next, num++) {
96		if (debug & DEBUG_DUMP_FSNODES_VERBOSE)
97			printf("%s: pre sort: %s %s %s\n",
98			    __func__, root, dir, tmp->name);
99	}
100
101	list = listptr = ecalloc(num, sizeof(*list));
102	for (fsnode *tmp = first; tmp; tmp = tmp->next)
103		*listptr++ = tmp;
104
105	qsort(list, num, sizeof(*list), fsnode_cmp);
106
107	for (size_t i = 0; i < num - 1; ++i)
108		list[i]->next = list[i + 1];
109	list[num - 1]->next = NULL;
110	first = list[0];
111	assert(strcmp(first->name, ".") == 0);
112	free(list);
113	if (debug & DEBUG_DUMP_FSNODES_VERBOSE)
114		for (fsnode *tmp = first; tmp; tmp = tmp->next)
115			printf("%s: post sort: %s %s %s\n",
116			    __func__, root, dir, tmp->name);
117
118	return first;
119}
120
121/*
122 * walk_dir --
123 *	build a tree of fsnodes from `root' and `dir', with a parent
124 *	fsnode of `parent' (which may be NULL for the root of the tree).
125 *	append the tree to a fsnode of `join' if it is not NULL.
126 *	each "level" is a directory, with the "." entry guaranteed to be
127 *	at the start of the list, and without ".." entries.
128 */
129fsnode *
130walk_dir(const char *root, const char *dir, fsnode *parent, fsnode *join,
131    int replace, int follow)
132{
133	fsnode		*first, *cur, *prev, *last;
134	DIR		*dirp;
135	struct dirent	*dent;
136	char		path[MAXPATHLEN + 1];
137	struct stat	stbuf;
138	char		*name, *rp;
139	int		dot, len;
140
141	assert(root != NULL);
142	assert(dir != NULL);
143
144	len = snprintf(path, sizeof(path), "%s/%s", root, dir);
145	if ((size_t)len >= sizeof(path))
146		errx(EXIT_FAILURE, "Pathname too long.");
147	if (debug & DEBUG_WALK_DIR)
148		printf("%s: %s %p\n", __func__, path, parent);
149	if ((dirp = opendir(path)) == NULL)
150		err(EXIT_FAILURE, "Can't opendir `%s'", path);
151	rp = path + strlen(root) + 1;
152	if (join != NULL) {
153		first = cur = join;
154		while (cur->next != NULL)
155			cur = cur->next;
156		prev = last = cur;
157	} else
158		last = first = prev = NULL;
159	while ((dent = readdir(dirp)) != NULL) {
160		name = dent->d_name;
161		dot = 0;
162		if (name[0] == '.')
163			switch (name[1]) {
164			case '\0':	/* "." */
165				if (join != NULL)
166					continue;
167				dot = 1;
168				break;
169			case '.':	/* ".." */
170				if (name[2] == '\0')
171					continue;
172				/* FALLTHROUGH */
173			default:
174				dot = 0;
175			}
176		if (debug & DEBUG_WALK_DIR_NODE)
177			printf("%s: scanning %s/%s/%s\n",
178			    __func__, root, dir, name);
179		if (snprintf(path + len, sizeof(path) - len, "/%s", name) >=
180		    (int)sizeof(path) - len)
181			errx(EXIT_FAILURE, "Pathname too long.");
182		if (follow) {
183			if (stat(path, &stbuf) == -1)
184				err(EXIT_FAILURE, "Can't stat `%s'", path);
185		} else {
186			if (lstat(path, &stbuf) == -1)
187				err(EXIT_FAILURE, "Can't lstat `%s'", path);
188			/*
189			 * Symlink permission bits vary between filesystems/OSs
190			 * (ie. 0755 on FFS/NetBSD, 0777 for ext[234]/Linux),
191			 * force them to 0755.
192			 */
193			if (S_ISLNK(stbuf.st_mode)) {
194				stbuf.st_mode &= ~(S_IRWXU | S_IRWXG | S_IRWXO);
195				stbuf.st_mode |= S_IRWXU
196				    | S_IRGRP | S_IXGRP
197				    | S_IROTH | S_IXOTH;
198			}
199		}
200#ifdef S_ISSOCK
201		if (S_ISSOCK(stbuf.st_mode & S_IFMT)) {
202			if (debug & DEBUG_WALK_DIR_NODE)
203				printf("%s: skipping socket %s\n", __func__, path);
204			continue;
205		}
206#endif
207
208		if (join != NULL) {
209			cur = join->next;
210			for (;;) {
211				if (cur == NULL || strcmp(cur->name, name) == 0)
212					break;
213				if (cur == last) {
214					cur = NULL;
215					break;
216				}
217				cur = cur->next;
218			}
219			if (cur != NULL) {
220				if (S_ISDIR(cur->type) &&
221				    S_ISDIR(stbuf.st_mode)) {
222					if (debug & DEBUG_WALK_DIR_NODE)
223						printf("%s: merging %s with %p\n",
224						    __func__, path, cur->child);
225					cur->child = walk_dir(root, rp, cur,
226					    cur->child, replace, follow);
227					continue;
228				}
229				if (!replace)
230					errx(EXIT_FAILURE,
231					    "Can't merge %s `%s' with "
232					    "existing %s",
233					    inode_type(stbuf.st_mode), path,
234					    inode_type(cur->type));
235				else {
236					if (debug & DEBUG_WALK_DIR_NODE)
237						printf("%s: replacing %s %s\n",
238						    __func__,
239						    inode_type(stbuf.st_mode),
240						    path);
241					if (cur == join->next)
242						join->next = cur->next;
243					else {
244						fsnode *p;
245						for (p = join->next;
246						    p->next != cur; p = p->next)
247							continue;
248						p->next = cur->next;
249					}
250					free(cur);
251				}
252			}
253		}
254
255		cur = create_fsnode(root, dir, name, &stbuf);
256		cur->parent = parent;
257		if (dot) {
258				/* ensure "." is at the start of the list */
259			cur->next = first;
260			first = cur;
261			if (! prev)
262				prev = cur;
263			cur->first = first;
264		} else {			/* not "." */
265			if (prev)
266				prev->next = cur;
267			prev = cur;
268			if (!first)
269				first = cur;
270			cur->first = first;
271			if (S_ISDIR(cur->type)) {
272				cur->child = walk_dir(root, rp, cur, NULL,
273				    replace, follow);
274				continue;
275			}
276		}
277		if (stbuf.st_nlink > 1) {
278			fsinode	*curino;
279
280			curino = link_check(cur->inode);
281			if (curino != NULL) {
282				free(cur->inode);
283				cur->inode = curino;
284				cur->inode->nlink++;
285				if (debug & DEBUG_WALK_DIR_LINKCHECK)
286					printf("%s: link check found [%ju, %ju]\n",
287					    __func__,
288					    (uintmax_t)curino->st.st_dev,
289					    (uintmax_t)curino->st.st_ino);
290			}
291		}
292		if (S_ISLNK(cur->type)) {
293			char	slink[PATH_MAX+1];
294			ssize_t	llen;
295
296			llen = readlink(path, slink, sizeof(slink) - 1);
297			if (llen == -1)
298				err(EXIT_FAILURE, "Readlink `%s'", path);
299			slink[llen] = '\0';
300			cur->symlink = estrdup(slink);
301		}
302	}
303	assert(first != NULL);
304	if (join == NULL)
305		for (cur = first->next; cur != NULL; cur = cur->next)
306			cur->first = first;
307	if (closedir(dirp) == -1)
308		err(EXIT_FAILURE, "Can't closedir `%s/%s'", root, dir);
309
310	return fsnode_sort(first, root, dir);
311}
312
313static fsnode *
314create_fsnode(const char *root, const char *path, const char *name,
315    struct stat *stbuf)
316{
317	fsnode *cur;
318
319	cur = ecalloc(1, sizeof(*cur));
320	cur->path = estrdup(path);
321	cur->name = estrdup(name);
322	cur->inode = ecalloc(1, sizeof(*cur->inode));
323	cur->root = root;
324	cur->type = stbuf->st_mode & S_IFMT;
325	cur->inode->nlink = 1;
326	cur->inode->st = *stbuf;
327	if (stampst.st_ino) {
328		cur->inode->st.st_atime = stampst.st_atime;
329		cur->inode->st.st_mtime = stampst.st_mtime;
330		cur->inode->st.st_ctime = stampst.st_ctime;
331#if HAVE_STRUCT_STAT_ST_MTIMENSEC
332		cur->inode->st.st_atimensec = stampst.st_atimensec;
333		cur->inode->st.st_mtimensec = stampst.st_mtimensec;
334		cur->inode->st.st_ctimensec = stampst.st_ctimensec;
335#endif
336#if HAVE_STRUCT_STAT_BIRTHTIME
337		cur->inode->st.st_birthtime = stampst.st_birthtime;
338		cur->inode->st.st_birthtimensec = stampst.st_birthtimensec;
339#endif
340	}
341	return (cur);
342}
343
344/*
345 * free_fsnodes --
346 *	Removes node from tree and frees it and all of
347 *   its descendents.
348 */
349void
350free_fsnodes(fsnode *node)
351{
352	fsnode	*cur, *next;
353
354	assert(node != NULL);
355
356	/* for ".", start with actual parent node */
357	if (node->first == node) {
358		assert(node->name[0] == '.' && node->name[1] == '\0');
359		if (node->parent) {
360			assert(node->parent->child == node);
361			node = node->parent;
362		}
363	}
364
365	/* Find ourselves in our sibling list and unlink */
366	if (node->first != node) {
367		for (cur = node->first; cur->next; cur = cur->next) {
368			if (cur->next == node) {
369				cur->next = node->next;
370				node->next = NULL;
371				break;
372			}
373		}
374	}
375
376	for (cur = node; cur != NULL; cur = next) {
377		next = cur->next;
378		if (cur->child) {
379			cur->child->parent = NULL;
380			free_fsnodes(cur->child);
381		}
382		if (cur->inode->nlink-- == 1)
383			free(cur->inode);
384		if (cur->symlink)
385			free(cur->symlink);
386		free(cur->path);
387		free(cur->name);
388		free(cur);
389	}
390}
391
392/*
393 * apply_specfile --
394 *	read in the mtree(8) specfile, and apply it to the tree
395 *	at dir,parent. parameters in parent on equivalent types
396 *	will be changed to those found in specfile, and missing
397 *	entries will be added.
398 */
399void
400apply_specfile(const char *specfile, const char *dir, fsnode *parent, int speconly)
401{
402	struct timeval	 start;
403	FILE	*fp;
404	NODE	*root;
405
406	assert(specfile != NULL);
407	assert(parent != NULL);
408
409	if (debug & DEBUG_APPLY_SPECFILE)
410		printf("%s: %s, %s %p\n", __func__, specfile, dir, parent);
411
412				/* read in the specfile */
413	if ((fp = fopen(specfile, "r")) == NULL)
414		err(EXIT_FAILURE, "Can't open `%s'", specfile);
415	TIMER_START(start);
416	root = spec(fp);
417	TIMER_RESULTS(start, "spec");
418	if (fclose(fp) == EOF)
419		err(EXIT_FAILURE, "Can't close `%s'", specfile);
420
421				/* perform some sanity checks */
422	if (root == NULL)
423		errx(EXIT_FAILURE,
424		    "Specfile `%s' did not contain a tree", specfile);
425	assert(strcmp(root->name, ".") == 0);
426	assert(root->type == F_DIR);
427
428				/* merge in the changes */
429	apply_specdir(dir, root, parent, speconly);
430
431	free_nodes(root);
432}
433
434static void
435apply_specdir(const char *dir, NODE *specnode, fsnode *dirnode, int speconly)
436{
437	char	 path[MAXPATHLEN + 1];
438	NODE	*curnode;
439	fsnode	*curfsnode;
440
441	assert(specnode != NULL);
442	assert(dirnode != NULL);
443
444	if (debug & DEBUG_APPLY_SPECFILE)
445		printf("%s: %s %p %p\n", __func__, dir, specnode, dirnode);
446
447	if (specnode->type != F_DIR)
448		errx(EXIT_FAILURE, "Specfile node `%s/%s' is not a directory",
449		    dir, specnode->name);
450	if (dirnode->type != S_IFDIR)
451		errx(EXIT_FAILURE, "Directory node `%s/%s' is not a directory",
452		    dir, dirnode->name);
453
454	apply_specentry(dir, specnode, dirnode);
455
456	/* Remove any filesystem nodes not found in specfile */
457	/* XXX inefficient.  This is O^2 in each dir and it would
458	 * have been better never to have walked this part of the tree
459	 * to begin with
460	 */
461	if (speconly) {
462		fsnode *next;
463		assert(dirnode->name[0] == '.' && dirnode->name[1] == '\0');
464		for (curfsnode = dirnode->next; curfsnode != NULL; curfsnode = next) {
465			next = curfsnode->next;
466			for (curnode = specnode->child; curnode != NULL;
467			     curnode = curnode->next) {
468				if (strcmp(curnode->name, curfsnode->name) == 0)
469					break;
470			}
471			if (curnode == NULL) {
472				if (debug & DEBUG_APPLY_SPECONLY) {
473					printf("%s: trimming %s/%s %p\n",
474					    __func__, dir, curfsnode->name,
475					    curfsnode);
476				}
477				free_fsnodes(curfsnode);
478			}
479		}
480	}
481
482			/* now walk specnode->child matching up with dirnode */
483	for (curnode = specnode->child; curnode != NULL;
484	    curnode = curnode->next) {
485		if (debug & DEBUG_APPLY_SPECENTRY)
486			printf("%s:  spec %s\n", __func__, curnode->name);
487		for (curfsnode = dirnode->next; curfsnode != NULL;
488		    curfsnode = curfsnode->next) {
489#if 0	/* too verbose for now */
490			if (debug & DEBUG_APPLY_SPECENTRY)
491				printf("%s: dirent %s\n", __func__,
492				    curfsnode->name);
493#endif
494			if (strcmp(curnode->name, curfsnode->name) == 0)
495				break;
496		}
497		if ((size_t)snprintf(path, sizeof(path), "%s/%s",
498		    dir, curnode->name) >= sizeof(path))
499			errx(EXIT_FAILURE, "Pathname too long.");
500		if (curfsnode == NULL) {	/* need new entry */
501			struct stat	stbuf;
502
503					    /*
504					     * don't add optional spec entries
505					     * that lack an existing fs entry
506					     */
507			if ((curnode->flags & F_OPT) &&
508			    lstat(path, &stbuf) == -1)
509					continue;
510
511					/* check that enough info is provided */
512#define NODETEST(t, m)							\
513			if (!(t))					\
514				errx(EXIT_FAILURE,			\
515				    "`%s': %s not provided", path, m)
516			NODETEST(curnode->flags & F_TYPE, "type");
517			NODETEST(curnode->flags & F_MODE, "mode");
518				/* XXX: require F_TIME ? */
519			NODETEST(curnode->flags & F_GID ||
520			    curnode->flags & F_GNAME, "group");
521			NODETEST(curnode->flags & F_UID ||
522			    curnode->flags & F_UNAME, "user");
523			if (curnode->type == F_BLOCK || curnode->type == F_CHAR)
524				NODETEST(curnode->flags & F_DEV,
525				    "device number");
526#undef NODETEST
527
528			if (debug & DEBUG_APPLY_SPECFILE)
529				printf("%s: adding %s\n", __func__, curnode->name);
530					/* build minimal fsnode */
531			memset(&stbuf, 0, sizeof(stbuf));
532			stbuf.st_mode = nodetoino(curnode->type);
533			stbuf.st_nlink = 1;
534			stbuf.st_mtime = stbuf.st_atime =
535			    stbuf.st_ctime = start_time.tv_sec;
536#if HAVE_STRUCT_STAT_ST_MTIMENSEC
537			stbuf.st_mtimensec = stbuf.st_atimensec =
538			    stbuf.st_ctimensec = start_time.tv_nsec;
539#endif
540			curfsnode = create_fsnode(".", ".", curnode->name,
541			    &stbuf);
542			curfsnode->parent = dirnode->parent;
543			curfsnode->first = dirnode;
544			curfsnode->next = dirnode->next;
545			dirnode->next = curfsnode;
546			if (curfsnode->type == S_IFDIR) {
547					/* for dirs, make "." entry as well */
548				curfsnode->child = create_fsnode(".", ".", ".",
549				    &stbuf);
550				curfsnode->child->parent = curfsnode;
551				curfsnode->child->first = curfsnode->child;
552			}
553			if (curfsnode->type == S_IFLNK) {
554				assert(curnode->slink != NULL);
555					/* for symlinks, copy the target */
556				curfsnode->symlink = estrdup(curnode->slink);
557			}
558		}
559		apply_specentry(dir, curnode, curfsnode);
560		if (curnode->type == F_DIR) {
561			if (curfsnode->type != S_IFDIR)
562				errx(EXIT_FAILURE,
563				    "`%s' is not a directory", path);
564			assert(curfsnode->child != NULL);
565			apply_specdir(path, curnode, curfsnode->child, speconly);
566		}
567	}
568}
569
570static void
571apply_specentry(const char *dir, NODE *specnode, fsnode *dirnode)
572{
573
574	assert(specnode != NULL);
575	assert(dirnode != NULL);
576
577	if (nodetoino(specnode->type) != dirnode->type)
578		errx(EXIT_FAILURE,
579		    "`%s/%s' type mismatch: specfile %s, tree %s",
580		    dir, specnode->name, inode_type(nodetoino(specnode->type)),
581		    inode_type(dirnode->type));
582
583	if (debug & DEBUG_APPLY_SPECENTRY)
584		printf("%s: %s/%s\n", dir, __func__, dirnode->name);
585
586#define ASEPRINT(t, b, o, n) \
587		if (debug & DEBUG_APPLY_SPECENTRY) \
588			printf("\t\t\tchanging %s from " b " to " b "\n", \
589			    t, o, n)
590
591	if (specnode->flags & (F_GID | F_GNAME)) {
592		ASEPRINT("gid", "%d",
593		    dirnode->inode->st.st_gid, specnode->st_gid);
594		dirnode->inode->st.st_gid = specnode->st_gid;
595	}
596	if (specnode->flags & F_MODE) {
597		ASEPRINT("mode", "%#o",
598		    dirnode->inode->st.st_mode & ALLPERMS, specnode->st_mode);
599		dirnode->inode->st.st_mode &= ~ALLPERMS;
600		dirnode->inode->st.st_mode |= (specnode->st_mode & ALLPERMS);
601	}
602		/* XXX: ignoring F_NLINK for now */
603	if (specnode->flags & F_SIZE) {
604		ASEPRINT("size", "%jd",
605		    (intmax_t)dirnode->inode->st.st_size,
606		    (intmax_t)specnode->st_size);
607		dirnode->inode->st.st_size = specnode->st_size;
608	}
609	if (specnode->flags & F_SLINK) {
610		assert(dirnode->symlink != NULL);
611		assert(specnode->slink != NULL);
612		ASEPRINT("symlink", "%s", dirnode->symlink, specnode->slink);
613		free(dirnode->symlink);
614		dirnode->symlink = estrdup(specnode->slink);
615	}
616	if (specnode->flags & F_TIME) {
617		ASEPRINT("time", "%ld",
618		    (long)dirnode->inode->st.st_mtime,
619		    (long)specnode->st_mtimespec.tv_sec);
620		dirnode->inode->st.st_mtime =		specnode->st_mtimespec.tv_sec;
621		dirnode->inode->st.st_atime =		specnode->st_mtimespec.tv_sec;
622		dirnode->inode->st.st_ctime =		start_time.tv_sec;
623#if HAVE_STRUCT_STAT_ST_MTIMENSEC
624		dirnode->inode->st.st_mtimensec =	specnode->st_mtimespec.tv_nsec;
625		dirnode->inode->st.st_atimensec =	specnode->st_mtimespec.tv_nsec;
626		dirnode->inode->st.st_ctimensec =	start_time.tv_nsec;
627#endif
628	}
629	if (specnode->flags & (F_UID | F_UNAME)) {
630		ASEPRINT("uid", "%d",
631		    dirnode->inode->st.st_uid, specnode->st_uid);
632		dirnode->inode->st.st_uid = specnode->st_uid;
633	}
634#if HAVE_STRUCT_STAT_ST_FLAGS
635	if (specnode->flags & F_FLAGS) {
636		ASEPRINT("flags", "%#lX",
637		    (unsigned long)dirnode->inode->st.st_flags,
638		    (unsigned long)specnode->st_flags);
639		dirnode->inode->st.st_flags = (unsigned int)specnode->st_flags;
640	}
641#endif
642	if (specnode->flags & F_DEV) {
643		ASEPRINT("rdev", "%#jx",
644		    (uintmax_t)dirnode->inode->st.st_rdev,
645		    (uintmax_t)specnode->st_rdev);
646		dirnode->inode->st.st_rdev = specnode->st_rdev;
647	}
648#undef ASEPRINT
649
650	dirnode->flags |= FSNODE_F_HASSPEC;
651}
652
653
654/*
655 * dump_fsnodes --
656 *	dump the fsnodes from `cur'
657 */
658void
659dump_fsnodes(fsnode *root)
660{
661	fsnode	*cur;
662	char	path[MAXPATHLEN + 1];
663
664	printf("%s: %s %p\n", __func__, root->path, root);
665	for (cur = root; cur != NULL; cur = cur->next) {
666		if (snprintf(path, sizeof(path), "%s/%s", cur->path,
667		    cur->name) >= (int)sizeof(path))
668			errx(EXIT_FAILURE, "Pathname too long.");
669
670		if (debug & DEBUG_DUMP_FSNODES_VERBOSE)
671			printf("%s: cur=%8p parent=%8p first=%8p ", __func__,
672			    cur, cur->parent, cur->first);
673		printf("%7s: %s", inode_type(cur->type), path);
674		if (S_ISLNK(cur->type)) {
675			assert(cur->symlink != NULL);
676			printf(" -> %s", cur->symlink);
677		} else {
678			assert(cur->symlink == NULL);
679		}
680		if (cur->inode->nlink > 1)
681			printf(", nlinks=%d", cur->inode->nlink);
682		putchar('\n');
683
684		if (cur->child) {
685			assert(cur->type == S_IFDIR);
686			dump_fsnodes(cur->child);
687		}
688	}
689	printf("%s: finished %s/%s\n", __func__, root->path, root->name);
690}
691
692
693/*
694 * inode_type --
695 *	for a given inode type `mode', return a descriptive string.
696 *	for most cases, uses inotype() from mtree/misc.c
697 */
698const char *
699inode_type(mode_t mode)
700{
701
702	if (S_ISLNK(mode))
703		return ("symlink");	/* inotype() returns "link"...  */
704	return (inotype(mode));
705}
706
707
708/*
709 * link_check --
710 *	return pointer to fsinode matching `entry's st_ino & st_dev if it exists,
711 *	otherwise add `entry' to table and return NULL
712 */
713/* This was borrowed from du.c and tweaked to keep an fsnode
714 * pointer instead. -- dbj@netbsd.org
715 */
716static fsinode *
717link_check(fsinode *entry)
718{
719	static struct entry {
720		fsinode *data;
721	} *htable;
722	static size_t htshift;  /* log(allocated size) */
723	static size_t htmask;   /* allocated size - 1 */
724	static size_t htused;   /* 2*number of insertions */
725	size_t h, h2;
726	uint64_t tmp;
727	/* this constant is (1<<64)/((1+sqrt(5))/2)
728	 * aka (word size)/(golden ratio)
729	 */
730	const uint64_t HTCONST = 11400714819323198485ULL;
731	const size_t HTBITS = 64;
732
733	/* Never store zero in hashtable */
734	assert(entry);
735
736	/* Extend hash table if necessary, keep load under 0.5 */
737	if (htused<<1 >= htmask) {
738		struct entry *ohtable;
739
740		if (!htable)
741			htshift = 10;   /* starting hashtable size */
742		else
743			htshift++;   /* exponential hashtable growth */
744
745		htmask  = (1 << htshift) - 1;
746		htused = 0;
747
748		ohtable = htable;
749		htable = ecalloc(htmask+1, sizeof(*htable));
750		/* populate newly allocated hashtable */
751		if (ohtable) {
752			for (size_t i = 0; i <= htmask>>1; i++)
753				if (ohtable[i].data)
754					link_check(ohtable[i].data);
755			free(ohtable);
756		}
757	}
758
759	/* multiplicative hashing */
760	tmp = entry->st.st_dev;
761	tmp <<= HTBITS>>1;
762	tmp |=  entry->st.st_ino;
763	tmp *= HTCONST;
764	h  = tmp >> (HTBITS - htshift);
765	h2 = 1 | ( tmp >> (HTBITS - (htshift<<1) - 1)); /* must be odd */
766
767	/* open address hashtable search with double hash probing */
768	while (htable[h].data) {
769		if ((htable[h].data->st.st_ino == entry->st.st_ino) &&
770		    (htable[h].data->st.st_dev == entry->st.st_dev)) {
771			return htable[h].data;
772		}
773		h = (h + h2) & htmask;
774	}
775
776	/* Insert the current entry into hashtable */
777	htable[h].data = entry;
778	htused++;
779	return NULL;
780}
781