tsort.c revision 1.11 1 /* $NetBSD: tsort.c,v 1.11 1996/01/17 20:37:53 mycroft 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.3 (Berkeley) 5/4/95";
48 #endif
49 static char rcsid[] = "$NetBSD: tsort.c,v 1.11 1996/01/17 20:37:53 mycroft 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 int find_cycle __P((NODE *, NODE *, int, int));
110 NODE *get_node __P((char *));
111 void *grow_buf __P((void *, int));
112 void remove_node __P((NODE *));
113 void tsort __P((void));
114 void usage __P((void));
115
116 int
117 main(argc, argv)
118 int argc;
119 char *argv[];
120 {
121 register BUF *b;
122 register int c, n;
123 FILE *fp;
124 int bsize, ch, nused;
125 BUF bufs[2];
126
127 while ((ch = getopt(argc, argv, "dlq")) != EOF)
128 switch (ch) {
129 case 'd':
130 debug = 1;
131 break;
132 case 'l':
133 longest = 1;
134 break;
135 case 'q':
136 quiet = 1;
137 break;
138 case '?':
139 default:
140 usage();
141 }
142 argc -= optind;
143 argv += optind;
144
145 switch (argc) {
146 case 0:
147 fp = stdin;
148 break;
149 case 1:
150 if ((fp = fopen(*argv, "r")) == NULL)
151 err(1, "%s", *argv);
152 break;
153 default:
154 usage();
155 }
156
157 for (b = bufs, n = 2; --n >= 0; b++)
158 b->b_buf = grow_buf(NULL, b->b_bsize = 1024);
159
160 /* parse input and build the graph */
161 for (n = 0, c = getc(fp);;) {
162 while (c != EOF && isspace(c))
163 c = getc(fp);
164 if (c == EOF)
165 break;
166
167 nused = 0;
168 b = &bufs[n];
169 bsize = b->b_bsize;
170 do {
171 b->b_buf[nused++] = c;
172 if (nused == bsize)
173 b->b_buf = grow_buf(b->b_buf, bsize *= 2);
174 c = getc(fp);
175 } while (c != EOF && !isspace(c));
176
177 b->b_buf[nused] = '\0';
178 b->b_bsize = bsize;
179 if (n)
180 add_arc(bufs[0].b_buf, bufs[1].b_buf);
181 n = !n;
182 }
183 (void)fclose(fp);
184 if (n)
185 errx(1, "odd data count");
186
187 /* do the sort */
188 tsort();
189 exit(0);
190 }
191
192 /* double the size of oldbuf and return a pointer to the new buffer. */
193 void *
194 grow_buf(bp, size)
195 void *bp;
196 int size;
197 {
198 if ((bp = realloc(bp, (u_int)size)) == NULL)
199 err(1, NULL);
200 return (bp);
201 }
202
203 /*
204 * add an arc from node s1 to node s2 in the graph. If s1 or s2 are not in
205 * the graph, then add them.
206 */
207 void
208 add_arc(s1, s2)
209 char *s1, *s2;
210 {
211 register NODE *n1;
212 NODE *n2;
213 int bsize, i;
214
215 n1 = get_node(s1);
216
217 if (!strcmp(s1, s2))
218 return;
219
220 n2 = get_node(s2);
221
222 /*
223 * Check if this arc is already here.
224 */
225 for (i = 0; i < n1->n_narcs; i++)
226 if (n1->n_arcs[i] == n2)
227 return;
228 /*
229 * Add it.
230 */
231 if (n1->n_narcs == n1->n_arcsize) {
232 if (!n1->n_arcsize)
233 n1->n_arcsize = 10;
234 bsize = n1->n_arcsize * sizeof(*n1->n_arcs) * 2;
235 n1->n_arcs = grow_buf(n1->n_arcs, bsize);
236 n1->n_arcsize = bsize / sizeof(*n1->n_arcs);
237 }
238 n1->n_arcs[n1->n_narcs++] = n2;
239 ++n2->n_refcnt;
240 }
241
242 /* Find a node in the graph (insert if not found) and return a pointer to it. */
243 NODE *
244 get_node(name)
245 char *name;
246 {
247 DBT data, key;
248 NODE *n;
249
250 if (db == NULL &&
251 (db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL)
252 err(1, "db: %s", name);
253
254 key.data = name;
255 key.size = strlen(name) + 1;
256
257 switch ((*db->get)(db, &key, &data, 0)) {
258 case 0:
259 bcopy(data.data, &n, sizeof(n));
260 return (n);
261 case 1:
262 break;
263 default:
264 case -1:
265 err(1, "db: %s", name);
266 }
267
268 if ((n = malloc(sizeof(NODE) + key.size)) == NULL)
269 err(1, NULL);
270
271 n->n_narcs = 0;
272 n->n_arcsize = 0;
273 n->n_arcs = NULL;
274 n->n_refcnt = 0;
275 n->n_flags = 0;
276 bcopy(name, n->n_name, key.size);
277
278 /* Add to linked list. */
279 if ((n->n_next = graph) != NULL)
280 graph->n_prevp = &n->n_next;
281 n->n_prevp = &graph;
282 graph = n;
283
284 /* Add to hash table. */
285 data.data = &n;
286 data.size = sizeof(n);
287 if ((*db->put)(db, &key, &data, 0))
288 err(1, "db: %s", name);
289 return (n);
290 }
291
292
293 /*
294 * Clear the NODEST flag from all nodes.
295 */
296 void
297 clear_cycle()
298 {
299 NODE *n;
300
301 for (n = graph; n != NULL; n = n->n_next)
302 n->n_flags &= ~NF_NODEST;
303 }
304
305 /* do topological sort on graph */
306 void
307 tsort()
308 {
309 register NODE *n, *next;
310 register int cnt, i;
311
312 while (graph != NULL) {
313 /*
314 * Keep getting rid of simple cases until there are none left,
315 * if there are any nodes still in the graph, then there is
316 * a cycle in it.
317 */
318 do {
319 for (cnt = 0, n = graph; n != NULL; n = next) {
320 next = n->n_next;
321 if (n->n_refcnt == 0) {
322 remove_node(n);
323 ++cnt;
324 }
325 }
326 } while (graph != NULL && cnt);
327
328 if (graph == NULL)
329 break;
330
331 if (!cycle_buf) {
332 /*
333 * Allocate space for two cycle logs - one to be used
334 * as scratch space, the other to save the longest
335 * cycle.
336 */
337 for (cnt = 0, n = graph; n != NULL; n = n->n_next)
338 ++cnt;
339 cycle_buf = malloc((u_int)sizeof(NODE *) * cnt);
340 longest_cycle = malloc((u_int)sizeof(NODE *) * cnt);
341 if (cycle_buf == NULL || longest_cycle == NULL)
342 err(1, NULL);
343 }
344 for (n = graph; n != NULL; n = n->n_next)
345 if (!(n->n_flags & NF_ACYCLIC))
346 if (cnt = find_cycle(n, n, 0, 0)) {
347 if (!quiet) {
348 warnx("cycle in data");
349 for (i = 0; i < cnt; i++)
350 warnx("%s",
351 longest_cycle[i]->n_name);
352 }
353 remove_node(n);
354 clear_cycle();
355 break;
356 } else {
357 /* to avoid further checks */
358 n->n_flags |= NF_ACYCLIC;
359 clear_cycle();
360 }
361
362 if (n == NULL)
363 errx(1, "internal error -- could not find cycle");
364 }
365 }
366
367 /* print node and remove from graph (does not actually free node) */
368 void
369 remove_node(n)
370 register NODE *n;
371 {
372 register NODE **np;
373 register int i;
374
375 (void)printf("%s\n", n->n_name);
376 for (np = n->n_arcs, i = n->n_narcs; --i >= 0; np++)
377 --(*np)->n_refcnt;
378 n->n_narcs = 0;
379 *n->n_prevp = n->n_next;
380 if (n->n_next)
381 n->n_next->n_prevp = n->n_prevp;
382 }
383
384
385 /* look for the longest? cycle from node from to node to. */
386 int
387 find_cycle(from, to, longest_len, depth)
388 NODE *from, *to;
389 int depth, longest_len;
390 {
391 register NODE **np;
392 register int i, len;
393
394 /*
395 * avoid infinite loops and ignore portions of the graph known
396 * to be acyclic
397 */
398 if (from->n_flags & (NF_NODEST|NF_MARK|NF_ACYCLIC))
399 return (0);
400 from->n_flags |= NF_MARK;
401
402 for (np = from->n_arcs, i = from->n_narcs; --i >= 0; np++) {
403 cycle_buf[depth] = *np;
404 if (*np == to) {
405 if (depth + 1 > longest_len) {
406 longest_len = depth + 1;
407 (void)memcpy((char *)longest_cycle,
408 (char *)cycle_buf,
409 longest_len * sizeof(NODE *));
410 }
411 } else {
412 if ((*np)->n_flags & (NF_MARK|NF_ACYCLIC|NF_NODEST))
413 continue;
414 len = find_cycle(*np, to, longest_len, depth + 1);
415
416 if (debug)
417 (void)printf("%*s %s->%s %d\n", depth, "",
418 from->n_name, to->n_name, len);
419
420 if (len == 0)
421 (*np)->n_flags |= NF_NODEST;
422
423 if (len > longest_len)
424 longest_len = len;
425
426 if (len > 0 && !longest)
427 break;
428 }
429 }
430 from->n_flags &= ~NF_MARK;
431 return (longest_len);
432 }
433
434 void
435 usage()
436 {
437 (void)fprintf(stderr, "usage: tsort [-lq] [file]\n");
438 exit(1);
439 }
440