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