xref: /freebsd/usr.bin/tsort/tsort.c (revision 5b31cc94b10d4bb7109c6b27940a0fc76a44a331)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 #ifndef lint
36 static const char copyright[] =
37 "@(#) Copyright (c) 1989, 1993, 1994\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40 
41 
42 #include <sys/cdefs.h>
43 #include <sys/types.h>
44 
45 #include <ctype.h>
46 #include <db.h>
47 #include <err.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 
55 /*
56  *  Topological sort.  Input is a list of pairs of strings separated by
57  *  white space (spaces, tabs, and/or newlines); strings are written to
58  *  standard output in sorted order, one per line.
59  *
60  *  usage:
61  *     tsort [-dlq] [inputfile]
62  *  If no input file is specified, standard input is read.
63  *
64  *  Should be compatible with AT&T tsort HOWEVER the output is not identical
65  *  (i.e. for most graphs there is more than one sorted order, and this tsort
66  *  usually generates a different one then the AT&T tsort).  Also, cycle
67  *  reporting seems to be more accurate in this version (the AT&T tsort
68  *  sometimes says a node is in a cycle when it isn't).
69  *
70  *  Michael Rendell, michael@stretch.cs.mun.ca - Feb 26, '90
71  */
72 
73 #define	NF_MARK		0x1		/* marker for cycle detection */
74 #define	NF_ACYCLIC	0x2		/* this node is cycle free */
75 #define	NF_NODEST	0x4		/* Unreachable */
76 
77 
78 typedef struct node_str NODE;
79 
80 struct node_str {
81 	NODE **n_prevp;			/* pointer to previous node's n_next */
82 	NODE *n_next;			/* next node in graph */
83 	NODE **n_arcs;			/* array of arcs to other nodes */
84 	int n_narcs;			/* number of arcs in n_arcs[] */
85 	int n_arcsize;			/* size of n_arcs[] array */
86 	int n_refcnt;			/* # of arcs pointing to this node */
87 	int n_flags;			/* NF_* */
88 	char n_name[1];			/* name of this node */
89 };
90 
91 typedef struct _buf {
92 	char *b_buf;
93 	int b_bsize;
94 } BUF;
95 
96 static DB *db;
97 static NODE *graph, **cycle_buf, **longest_cycle;
98 static int debug, longest, quiet;
99 
100 static void	 add_arc(char *, char *);
101 static int	 find_cycle(NODE *, NODE *, int, int);
102 static NODE	*get_node(char *);
103 static void	*grow_buf(void *, size_t);
104 static void	 remove_node(NODE *);
105 static void	 clear_cycle(void);
106 static void	 tsort(void);
107 static void	 usage(void);
108 
109 int
110 main(int argc, char *argv[])
111 {
112 	BUF *b;
113 	int c, n;
114 	FILE *fp;
115 	int bsize, ch, nused;
116 	BUF bufs[2];
117 
118 	fp = NULL;
119 	while ((ch = getopt(argc, argv, "dlq")) != -1)
120 		switch (ch) {
121 		case 'd':
122 			debug = 1;
123 			break;
124 		case 'l':
125 			longest = 1;
126 			break;
127 		case 'q':
128 			quiet = 1;
129 			break;
130 		case '?':
131 		default:
132 			usage();
133 		}
134 	argc -= optind;
135 	argv += optind;
136 
137 	switch (argc) {
138 	case 0:
139 		fp = stdin;
140 		break;
141 	case 1:
142 		if ((fp = fopen(*argv, "r")) == NULL)
143 			err(1, "%s", *argv);
144 		break;
145 	default:
146 		usage();
147 	}
148 
149 	for (b = bufs, n = 2; --n >= 0; b++)
150 		b->b_buf = grow_buf(NULL, b->b_bsize = 1024);
151 
152 	/* parse input and build the graph */
153 	for (n = 0, c = getc(fp);;) {
154 		while (c != EOF && isspace(c))
155 			c = getc(fp);
156 		if (c == EOF)
157 			break;
158 
159 		nused = 0;
160 		b = &bufs[n];
161 		bsize = b->b_bsize;
162 		do {
163 			b->b_buf[nused++] = c;
164 			if (nused == bsize)
165 				b->b_buf = grow_buf(b->b_buf, bsize *= 2);
166 			c = getc(fp);
167 		} while (c != EOF && !isspace(c));
168 
169 		b->b_buf[nused] = '\0';
170 		b->b_bsize = bsize;
171 		if (n)
172 			add_arc(bufs[0].b_buf, bufs[1].b_buf);
173 		n = !n;
174 	}
175 	(void)fclose(fp);
176 	if (n)
177 		errx(1, "odd data count");
178 
179 	/* do the sort */
180 	tsort();
181 	if (ferror(stdout) != 0 || fflush(stdout) != 0)
182 		err(1, "stdout");
183 	exit(0);
184 }
185 
186 /* double the size of oldbuf and return a pointer to the new buffer. */
187 static void *
188 grow_buf(void *bp, size_t size)
189 {
190 	if ((bp = realloc(bp, size)) == NULL)
191 		err(1, NULL);
192 	return (bp);
193 }
194 
195 /*
196  * add an arc from node s1 to node s2 in the graph.  If s1 or s2 are not in
197  * the graph, then add them.
198  */
199 static void
200 add_arc(char *s1, char *s2)
201 {
202 	NODE *n1;
203 	NODE *n2;
204 	int bsize, i;
205 
206 	n1 = get_node(s1);
207 
208 	if (!strcmp(s1, s2))
209 		return;
210 
211 	n2 = get_node(s2);
212 
213 	/*
214 	 * Check if this arc is already here.
215 	 */
216 	for (i = 0; i < n1->n_narcs; i++)
217 		if (n1->n_arcs[i] == n2)
218 			return;
219 	/*
220 	 * Add it.
221 	 */
222 	if (n1->n_narcs == n1->n_arcsize) {
223 		if (!n1->n_arcsize)
224 			n1->n_arcsize = 10;
225 		bsize = n1->n_arcsize * sizeof(*n1->n_arcs) * 2;
226 		n1->n_arcs = grow_buf(n1->n_arcs, bsize);
227 		n1->n_arcsize = bsize / sizeof(*n1->n_arcs);
228 	}
229 	n1->n_arcs[n1->n_narcs++] = n2;
230 	++n2->n_refcnt;
231 }
232 
233 /* Find a node in the graph (insert if not found) and return a pointer to it. */
234 static NODE *
235 get_node(char *name)
236 {
237 	DBT data, key;
238 	NODE *n;
239 
240 	if (db == NULL &&
241 	    (db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL)
242 		err(1, "db: %s", name);
243 
244 	key.data = name;
245 	key.size = strlen(name) + 1;
246 
247 	switch ((*db->get)(db, &key, &data, 0)) {
248 	case 0:
249 		memcpy(&n, data.data, sizeof(n));
250 		return (n);
251 	case 1:
252 		break;
253 	default:
254 	case -1:
255 		err(1, "db: %s", name);
256 	}
257 
258 	if ((n = malloc(sizeof(NODE) + key.size)) == NULL)
259 		err(1, NULL);
260 
261 	n->n_narcs = 0;
262 	n->n_arcsize = 0;
263 	n->n_arcs = NULL;
264 	n->n_refcnt = 0;
265 	n->n_flags = 0;
266 	memcpy(n->n_name, name, key.size);
267 
268 	/* Add to linked list. */
269 	if ((n->n_next = graph) != NULL)
270 		graph->n_prevp = &n->n_next;
271 	n->n_prevp = &graph;
272 	graph = n;
273 
274 	/* Add to hash table. */
275 	data.data = &n;
276 	data.size = sizeof(n);
277 	if ((*db->put)(db, &key, &data, 0))
278 		err(1, "db: %s", name);
279 	return (n);
280 }
281 
282 
283 /*
284  * Clear the NODEST flag from all nodes.
285  */
286 static void
287 clear_cycle(void)
288 {
289 	NODE *n;
290 
291 	for (n = graph; n != NULL; n = n->n_next)
292 		n->n_flags &= ~NF_NODEST;
293 }
294 
295 /* do topological sort on graph */
296 static void
297 tsort(void)
298 {
299 	NODE *n, *next;
300 	int cnt, i;
301 
302 	while (graph != NULL) {
303 		/*
304 		 * Keep getting rid of simple cases until there are none left,
305 		 * if there are any nodes still in the graph, then there is
306 		 * a cycle in it.
307 		 */
308 		do {
309 			for (cnt = 0, n = graph; n != NULL; n = next) {
310 				next = n->n_next;
311 				if (n->n_refcnt == 0) {
312 					remove_node(n);
313 					++cnt;
314 				}
315 			}
316 		} while (graph != NULL && cnt);
317 
318 		if (graph == NULL)
319 			break;
320 
321 		if (!cycle_buf) {
322 			/*
323 			 * Allocate space for two cycle logs - one to be used
324 			 * as scratch space, the other to save the longest
325 			 * cycle.
326 			 */
327 			for (cnt = 0, n = graph; n != NULL; n = n->n_next)
328 				++cnt;
329 			cycle_buf = malloc(sizeof(NODE *) * cnt);
330 			longest_cycle = malloc(sizeof(NODE *) * cnt);
331 			if (cycle_buf == NULL || longest_cycle == NULL)
332 				err(1, NULL);
333 		}
334 		for (n = graph; n != NULL; n = n->n_next)
335 			if (!(n->n_flags & NF_ACYCLIC)) {
336 				if ((cnt = find_cycle(n, n, 0, 0))) {
337 					if (!quiet) {
338 						warnx("cycle in data");
339 						for (i = 0; i < cnt; i++)
340 							warnx("%s",
341 							    longest_cycle[i]->n_name);
342 					}
343 					remove_node(n);
344 					clear_cycle();
345 					break;
346 				} else {
347 					/* to avoid further checks */
348 					n->n_flags  |= NF_ACYCLIC;
349 					clear_cycle();
350 				}
351 			}
352 
353 		if (n == NULL)
354 			errx(1, "internal error -- could not find cycle");
355 	}
356 }
357 
358 /* print node and remove from graph (does not actually free node) */
359 static void
360 remove_node(NODE *n)
361 {
362 	NODE **np;
363 	int i;
364 
365 	(void)printf("%s\n", n->n_name);
366 	for (np = n->n_arcs, i = n->n_narcs; --i >= 0; np++)
367 		--(*np)->n_refcnt;
368 	n->n_narcs = 0;
369 	*n->n_prevp = n->n_next;
370 	if (n->n_next)
371 		n->n_next->n_prevp = n->n_prevp;
372 }
373 
374 
375 /* look for the longest? cycle from node from to node to. */
376 static int
377 find_cycle(NODE *from, NODE *to, int longest_len, int depth)
378 {
379 	NODE **np;
380 	int i, len;
381 
382 	/*
383 	 * avoid infinite loops and ignore portions of the graph known
384 	 * to be acyclic
385 	 */
386 	if (from->n_flags & (NF_NODEST|NF_MARK|NF_ACYCLIC))
387 		return (0);
388 	from->n_flags |= NF_MARK;
389 
390 	for (np = from->n_arcs, i = from->n_narcs; --i >= 0; np++) {
391 		cycle_buf[depth] = *np;
392 		if (*np == to) {
393 			if (depth + 1 > longest_len) {
394 				longest_len = depth + 1;
395 				(void)memcpy((char *)longest_cycle,
396 				    (char *)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 %d\n", 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
423 usage(void)
424 {
425 	(void)fprintf(stderr, "usage: tsort [-dlq] [file]\n");
426 	exit(1);
427 }
428