2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1989, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Michael Rendell of Memorial University of Newfoundland.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
36 static const char copyright[] =
37 "@(#) Copyright (c) 1989, 1993, 1994\n\
38 The Regents of the University of California. All rights reserved.\n";
42 static const char sccsid[] = "@(#)tsort.c 8.3 (Berkeley) 5/4/95";
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
48 #include <sys/types.h>
61 * Topological sort. Input is a list of pairs of strings separated by
62 * white space (spaces, tabs, and/or newlines); strings are written to
63 * standard output in sorted order, one per line.
66 * tsort [-dlq] [inputfile]
67 * If no input file is specified, standard input is read.
69 * Should be compatible with AT&T tsort HOWEVER the output is not identical
70 * (i.e. for most graphs there is more than one sorted order, and this tsort
71 * usually generates a different one then the AT&T tsort). Also, cycle
72 * reporting seems to be more accurate in this version (the AT&T tsort
73 * sometimes says a node is in a cycle when it isn't).
75 * Michael Rendell, michael@stretch.cs.mun.ca - Feb 26, '90
78 #define NF_MARK 0x1 /* marker for cycle detection */
79 #define NF_ACYCLIC 0x2 /* this node is cycle free */
80 #define NF_NODEST 0x4 /* Unreachable */
83 typedef struct node_str NODE;
86 NODE **n_prevp; /* pointer to previous node's n_next */
87 NODE *n_next; /* next node in graph */
88 NODE **n_arcs; /* array of arcs to other nodes */
89 int n_narcs; /* number of arcs in n_arcs[] */
90 int n_arcsize; /* size of n_arcs[] array */
91 int n_refcnt; /* # of arcs pointing to this node */
92 int n_flags; /* NF_* */
93 char n_name[1]; /* name of this node */
102 static NODE *graph, **cycle_buf, **longest_cycle;
103 static int debug, longest, quiet;
105 static void add_arc(char *, char *);
106 static int find_cycle(NODE *, NODE *, int, int);
107 static NODE *get_node(char *);
108 static void *grow_buf(void *, size_t);
109 static void remove_node(NODE *);
110 static void clear_cycle(void);
111 static void tsort(void);
112 static void usage(void);
115 main(int argc, char *argv[])
120 int bsize, ch, nused;
124 while ((ch = getopt(argc, argv, "dlq")) != -1)
147 if ((fp = fopen(*argv, "r")) == NULL)
154 for (b = bufs, n = 2; --n >= 0; b++)
155 b->b_buf = grow_buf(NULL, b->b_bsize = 1024);
157 /* parse input and build the graph */
158 for (n = 0, c = getc(fp);;) {
159 while (c != EOF && isspace(c))
168 b->b_buf[nused++] = c;
170 b->b_buf = grow_buf(b->b_buf, bsize *= 2);
172 } while (c != EOF && !isspace(c));
174 b->b_buf[nused] = '\0';
177 add_arc(bufs[0].b_buf, bufs[1].b_buf);
182 errx(1, "odd data count");
189 /* double the size of oldbuf and return a pointer to the new buffer. */
191 grow_buf(void *bp, size_t size)
193 if ((bp = realloc(bp, size)) == NULL)
199 * add an arc from node s1 to node s2 in the graph. If s1 or s2 are not in
200 * the graph, then add them.
203 add_arc(char *s1, char *s2)
217 * Check if this arc is already here.
219 for (i = 0; i < n1->n_narcs; i++)
220 if (n1->n_arcs[i] == n2)
225 if (n1->n_narcs == n1->n_arcsize) {
228 bsize = n1->n_arcsize * sizeof(*n1->n_arcs) * 2;
229 n1->n_arcs = grow_buf(n1->n_arcs, bsize);
230 n1->n_arcsize = bsize / sizeof(*n1->n_arcs);
232 n1->n_arcs[n1->n_narcs++] = n2;
236 /* Find a node in the graph (insert if not found) and return a pointer to it. */
244 (db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL)
245 err(1, "db: %s", name);
248 key.size = strlen(name) + 1;
250 switch ((*db->get)(db, &key, &data, 0)) {
252 bcopy(data.data, &n, sizeof(n));
258 err(1, "db: %s", name);
261 if ((n = malloc(sizeof(NODE) + key.size)) == NULL)
269 bcopy(name, n->n_name, key.size);
271 /* Add to linked list. */
272 if ((n->n_next = graph) != NULL)
273 graph->n_prevp = &n->n_next;
277 /* Add to hash table. */
279 data.size = sizeof(n);
280 if ((*db->put)(db, &key, &data, 0))
281 err(1, "db: %s", name);
287 * Clear the NODEST flag from all nodes.
294 for (n = graph; n != NULL; n = n->n_next)
295 n->n_flags &= ~NF_NODEST;
298 /* do topological sort on graph */
305 while (graph != NULL) {
307 * Keep getting rid of simple cases until there are none left,
308 * if there are any nodes still in the graph, then there is
312 for (cnt = 0, n = graph; n != NULL; n = next) {
314 if (n->n_refcnt == 0) {
319 } while (graph != NULL && cnt);
326 * Allocate space for two cycle logs - one to be used
327 * as scratch space, the other to save the longest
330 for (cnt = 0, n = graph; n != NULL; n = n->n_next)
332 cycle_buf = malloc(sizeof(NODE *) * cnt);
333 longest_cycle = malloc(sizeof(NODE *) * cnt);
334 if (cycle_buf == NULL || longest_cycle == NULL)
337 for (n = graph; n != NULL; n = n->n_next)
338 if (!(n->n_flags & NF_ACYCLIC)) {
339 if ((cnt = find_cycle(n, n, 0, 0))) {
341 warnx("cycle in data");
342 for (i = 0; i < cnt; i++)
344 longest_cycle[i]->n_name);
350 /* to avoid further checks */
351 n->n_flags |= NF_ACYCLIC;
357 errx(1, "internal error -- could not find cycle");
361 /* print node and remove from graph (does not actually free node) */
368 (void)printf("%s\n", n->n_name);
369 for (np = n->n_arcs, i = n->n_narcs; --i >= 0; np++)
372 *n->n_prevp = n->n_next;
374 n->n_next->n_prevp = n->n_prevp;
378 /* look for the longest? cycle from node from to node to. */
380 find_cycle(NODE *from, NODE *to, int longest_len, int depth)
386 * avoid infinite loops and ignore portions of the graph known
389 if (from->n_flags & (NF_NODEST|NF_MARK|NF_ACYCLIC))
391 from->n_flags |= NF_MARK;
393 for (np = from->n_arcs, i = from->n_narcs; --i >= 0; np++) {
394 cycle_buf[depth] = *np;
396 if (depth + 1 > longest_len) {
397 longest_len = depth + 1;
398 (void)memcpy((char *)longest_cycle,
400 longest_len * sizeof(NODE *));
403 if ((*np)->n_flags & (NF_MARK|NF_ACYCLIC|NF_NODEST))
405 len = find_cycle(*np, to, longest_len, depth + 1);
408 (void)printf("%*s %s->%s %d\n", depth, "",
409 from->n_name, to->n_name, len);
412 (*np)->n_flags |= NF_NODEST;
414 if (len > longest_len)
417 if (len > 0 && !longest)
421 from->n_flags &= ~NF_MARK;
422 return (longest_len);
428 (void)fprintf(stderr, "usage: tsort [-dlq] [file]\n");