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