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