xref: /netbsd/usr.bin/tsort/tsort.c (revision b20ac136)
1 /*	$NetBSD: tsort.c,v 1.26 2021/02/06 16:02:16 dbj Exp $	*/
2 
3 /*
4  * Copyright (c) 1989, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Michael Rendell of Memorial University of Newfoundland.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #if HAVE_NBTOOL_CONFIG_H
36 #include "nbtool_config.h"
37 #endif
38 
39 #include <sys/cdefs.h>
40 #if !defined(lint)
41 __COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\
42  The Regents of the University of California.  All rights reserved.");
43 #if 0
44 static char sccsid[] = "@(#)tsort.c	8.3 (Berkeley) 5/4/95";
45 #endif
46 __RCSID("$NetBSD: tsort.c,v 1.26 2021/02/06 16:02:16 dbj Exp $");
47 #endif /* not lint */
48 
49 #include <sys/types.h>
50 #include <ctype.h>
51 #include <db.h>
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59 #if !HAVE_NBTOOL_CONFIG_H
60 #include <util.h>
61 #endif
62 
63 /*
64  *  Topological sort.  Input is a list of pairs of strings separated by
65  *  white space (spaces, tabs, and/or newlines); strings are written to
66  *  standard output in sorted order, one per line.
67  *
68  *  usage:
69  *     tsort [-l] [inputfile]
70  *  If no input file is specified, standard input is read.
71  *
72  *  Should be compatible with AT&T tsort HOWEVER the output is not identical
73  *  (i.e. for most graphs there is more than one sorted order, and this tsort
74  *  usually generates a different one than the AT&T tsort).  Also, cycle
75  *  reporting seems to be more accurate in this version (the AT&T tsort
76  *  sometimes says a node is in a cycle when it isn't).
77  *
78  *  Michael Rendell, michael@stretch.cs.mun.ca - Feb 26, '90
79  */
80 #define	HASHSIZE	53		/* doesn't need to be big */
81 #define	NF_MARK		0x1		/* marker for cycle detection */
82 #define	NF_ACYCLIC	0x2		/* this node is cycle free */
83 #define	NF_NODEST	0x4		/* Unreachable */
84 
85 typedef struct node_str NODE;
86 
87 struct node_str {
88 	NODE **n_prevp;			/* pointer to previous node's n_next */
89 	NODE *n_next;			/* next node in graph */
90 	NODE **n_arcs;			/* array of arcs to other nodes */
91 	size_t n_narcs;			/* number of arcs in n_arcs[] */
92 	size_t n_arcsize;		/* size of n_arcs[] array */
93 	size_t n_refcnt;		/* # of arcs pointing to this node */
94 	int n_flags;			/* NF_* */
95 	char n_name[1];			/* name of this node */
96 };
97 
98 typedef struct _buf {
99 	char *b_buf;
100 	size_t b_bsize;
101 } BUF;
102 
103 static DB *db;
104 static NODE *graph, **cycle_buf, **longest_cycle;
105 static int debug, longest, quiet, reverse;
106 
107 static void	 add_arc(const char *, const char *);
108 static void	 clear_cycle(void);
109 static size_t	 find_cycle(NODE *, NODE *, size_t, size_t);
110 static NODE	*get_node(const char *);
111 static void	 remove_node(NODE *);
112 static void	 tsort(void);
113 __dead static void	 usage(void);
114 
115 int
main(int argc,char * argv[])116 main(int argc, char *argv[])
117 {
118 	BUF *b;
119 	int c, n, ch;
120 	FILE *fp;
121 	size_t bsize, nused;
122 	BUF bufs[2];
123 
124 	setprogname(argv[0]);
125 
126 	fp = NULL;
127 	while ((ch = getopt(argc, argv, "dlqr")) != -1)
128 		switch (ch) {
129 		case 'd':
130 			debug = 1;
131 			break;
132 		case 'l':
133 			longest = 1;
134 			break;
135 		case 'q':
136 			quiet = 1;
137 			break;
138 		case 'r':
139 			reverse = 1;
140 			break;
141 		case '?':
142 		default:
143 			usage();
144 		}
145 	argc -= optind;
146 	argv += optind;
147 
148 	switch (argc) {
149 	case 0:
150 		fp = stdin;
151 		break;
152 	case 1:
153 		if ((fp = fopen(*argv, "r")) == NULL)
154 			err(EXIT_FAILURE, "%s", *argv);
155 		break;
156 	default:
157 		usage();
158 	}
159 
160 	for (b = bufs, n = 2; n-- > 0; b++)
161 		b->b_buf = erealloc(NULL, b->b_bsize = 1024);
162 
163 	/* parse input and build the graph */
164 	for (n = 0, c = getc(fp);;) {
165 		while (c != EOF && isspace(c))
166 			c = getc(fp);
167 		if (c == EOF)
168 			break;
169 
170 		nused = 0;
171 		b = &bufs[n];
172 		bsize = b->b_bsize;
173 		do {
174 			b->b_buf[nused++] = (char)c;
175 			if (nused == bsize)
176 				b->b_buf = erealloc(b->b_buf, bsize *= 2);
177 			c = getc(fp);
178 		} while (c != EOF && !isspace(c));
179 
180 		b->b_buf[nused] = '\0';
181 		b->b_bsize = bsize;
182 		if (n) {
183 			if (reverse)
184 				add_arc(bufs[1].b_buf, bufs[0].b_buf);
185 			else
186 				add_arc(bufs[0].b_buf, bufs[1].b_buf);
187 		}
188 		n = !n;
189 	}
190 	(void)fclose(fp);
191 	if (n)
192 		errx(EXIT_FAILURE, "odd data count");
193 
194 	/* do the sort */
195 	tsort();
196 	return EXIT_SUCCESS;
197 }
198 
199 /*
200  * add an arc from node s1 to node s2 in the graph.  If s1 or s2 are not in
201  * the graph, then add them.
202  */
203 static void
add_arc(const char * s1,const char * s2)204 add_arc(const char *s1, const char *s2)
205 {
206 	NODE *n1;
207 	NODE *n2;
208 	size_t bsize, i;
209 
210 	n1 = get_node(s1);
211 
212 	if (strcmp(s1, s2) == 0)
213 		return;
214 
215 	n2 = get_node(s2);
216 
217 	/*
218 	 * Check if this arc is already here.
219 	 */
220 	for (i = 0; i < n1->n_narcs; i++)
221 		if (n1->n_arcs[i] == n2)
222 			return;
223 	/*
224 	 * Add it.
225 	 */
226 	if (n1->n_narcs == n1->n_arcsize) {
227 		if (!n1->n_arcsize)
228 			n1->n_arcsize = 10;
229 		bsize = n1->n_arcsize * sizeof(*n1->n_arcs) * 2;
230 		n1->n_arcs = erealloc(n1->n_arcs, bsize);
231 		n1->n_arcsize = bsize / sizeof(*n1->n_arcs);
232 	}
233 	n1->n_arcs[n1->n_narcs++] = n2;
234 	++n2->n_refcnt;
235 }
236 
237 /* Find a node in the graph (insert if not found) and return a pointer to it. */
238 static NODE *
get_node(const char * name)239 get_node(const char *name)
240 {
241 	DBT data, key;
242 	NODE *n;
243 
244 	if (db == NULL &&
245 	    (db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL)
246 		err(EXIT_FAILURE, "db: %s", name);
247 
248 	key.data = __UNCONST(name);
249 	key.size = strlen(name) + 1;
250 
251 	switch ((*db->get)(db, &key, &data, 0)) {
252 	case 0:
253 		(void)memmove(&n, data.data, sizeof(n));
254 		return n;
255 	case 1:
256 		break;
257 	default:
258 	case -1:
259 		err(EXIT_FAILURE, "db: %s", name);
260 	}
261 
262 	n = emalloc(sizeof(NODE) + key.size);
263 
264 	n->n_narcs = 0;
265 	n->n_arcsize = 0;
266 	n->n_arcs = NULL;
267 	n->n_refcnt = 0;
268 	n->n_flags = 0;
269 	(void)memmove(n->n_name, name, key.size);
270 
271 	/* Add to linked list. */
272 	if ((n->n_next = graph) != NULL)
273 		graph->n_prevp = &n->n_next;
274 	n->n_prevp = &graph;
275 	graph = n;
276 
277 	/* Add to hash table. */
278 	data.data = &n;
279 	data.size = sizeof(n);
280 	if ((*db->put)(db, &key, &data, 0))
281 		err(EXIT_FAILURE, "db: %s", name);
282 	return n;
283 }
284 
285 
286 /*
287  * Clear the NODEST flag from all nodes.
288  */
289 static void
clear_cycle(void)290 clear_cycle(void)
291 {
292 	NODE *n;
293 
294 	for (n = graph; n != NULL; n = n->n_next)
295 		n->n_flags &= ~NF_NODEST;
296 }
297 
298 /* do topological sort on graph */
299 static void
tsort(void)300 tsort(void)
301 {
302 	NODE *n, *next;
303 	size_t cnt, i;
304 
305 	while (graph != NULL) {
306 		/*
307 		 * Keep getting rid of simple cases until there are none left,
308 		 * if there are any nodes still in the graph, then there is
309 		 * a cycle in it.
310 		 */
311 		do {
312 			for (cnt = 0, n = graph; n != NULL; n = next) {
313 				next = n->n_next;
314 				if (n->n_refcnt == 0) {
315 					remove_node(n);
316 					++cnt;
317 				}
318 			}
319 		} while (graph != NULL && cnt);
320 
321 		if (graph == NULL)
322 			break;
323 
324 		if (!cycle_buf) {
325 			/*
326 			 * Allocate space for two cycle logs - one to be used
327 			 * as scratch space, the other to save the longest
328 			 * cycle.
329 			 */
330 			for (cnt = 0, n = graph; n != NULL; n = n->n_next)
331 				++cnt;
332 			cycle_buf = ecalloc(cnt, sizeof(*cycle_buf));
333 			longest_cycle = ecalloc(cnt, sizeof(*longest_cycle));
334 		}
335 		for (n = graph; n != NULL; n = n->n_next) {
336 			if (!(n->n_flags & NF_ACYCLIC)) {
337 				if ((cnt = find_cycle(n, n, 0, 0)) != 0) {
338 					if (!quiet) {
339 						warnx("cycle in data");
340 						for (i = 0; i < cnt; i++)
341 							warnx("%s",
342 							    longest_cycle[i]->n_name);
343 					}
344 					remove_node(n);
345 					clear_cycle();
346 					break;
347 				} else {
348 					/* to avoid further checks */
349 					n->n_flags  |= NF_ACYCLIC;
350 					clear_cycle();
351 				}
352 			}
353 		}
354 		if (n == NULL)
355 			errx(1, "internal error -- could not find cycle");
356 	}
357 }
358 
359 /* print node and remove from graph (does not actually free node) */
360 static void
remove_node(NODE * n)361 remove_node(NODE *n)
362 {
363 	NODE **np;
364 	size_t i;
365 
366 	(void)printf("%s\n", n->n_name);
367 	for (np = n->n_arcs, i = n->n_narcs; i-- > 0; np++)
368 		--(*np)->n_refcnt;
369 	n->n_narcs = 0;
370 	*n->n_prevp = n->n_next;
371 	if (n->n_next)
372 		n->n_next->n_prevp = n->n_prevp;
373 }
374 
375 
376 /* look for the longest? cycle from node from to node to. */
377 static size_t
find_cycle(NODE * from,NODE * to,size_t longest_len,size_t depth)378 find_cycle(NODE *from, NODE *to, size_t longest_len, size_t depth)
379 {
380 	NODE **np;
381 	size_t i, len;
382 
383 	/*
384 	 * avoid infinite loops and ignore portions of the graph known
385 	 * to be acyclic
386 	 */
387 	if (from->n_flags & (NF_NODEST|NF_MARK|NF_ACYCLIC))
388 		return 0;
389 	from->n_flags |= NF_MARK;
390 
391 	for (np = from->n_arcs, i = from->n_narcs; i-- > 0; np++) {
392 		cycle_buf[depth] = *np;
393 		if (*np == to) {
394 			if (depth + 1 > longest_len) {
395 				longest_len = depth + 1;
396 				(void)memcpy(longest_cycle, cycle_buf,
397 				    longest_len * sizeof(NODE *));
398 			}
399 		} else {
400 			if ((*np)->n_flags & (NF_MARK|NF_ACYCLIC|NF_NODEST))
401 				continue;
402 			len = find_cycle(*np, to, longest_len, depth + 1);
403 
404 			if (debug)
405 				(void)printf("%*s %s->%s %zu\n", (int)depth, "",
406 				    from->n_name, to->n_name, len);
407 
408 			if (len == 0)
409 				(*np)->n_flags |= NF_NODEST;
410 
411 			if (len > longest_len)
412 				longest_len = len;
413 
414 			if (len > 0 && !longest)
415 				break;
416 		}
417 	}
418 	from->n_flags &= ~NF_MARK;
419 	return longest_len;
420 }
421 
422 static void
usage(void)423 usage(void)
424 {
425 	(void)fprintf(stderr, "Usage: %s [-dlqr] [file]\n", getprogname());
426 	exit(EXIT_FAILURE);
427 }
428