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