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