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