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