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