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