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