1 /* $NetBSD: tsort.c,v 1.22 2008/07/21 14:19:27 lukem 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. 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. 21 * 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 32 * SUCH DAMAGE. 33 */ 34 35 #if HAVE_NBTOOL_CONFIG_H 36 #include "nbtool_config.h" 37 #endif 38 39 #include <sys/cdefs.h> 40 #if !defined(lint) 41 __COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\ 42 The Regents of the University of California. All rights reserved."); 43 #if 0 44 static char sccsid[] = "@(#)tsort.c 8.3 (Berkeley) 5/4/95"; 45 #endif 46 __RCSID("$NetBSD: tsort.c,v 1.22 2008/07/21 14:19:27 lukem Exp $"); 47 #endif /* not lint */ 48 49 #include <sys/types.h> 50 #include <ctype.h> 51 #include <db.h> 52 #include <err.h> 53 #include <errno.h> 54 #include <fcntl.h> 55 #include <stdio.h> 56 #include <stdlib.h> 57 #include <string.h> 58 #include <unistd.h> 59 60 /* 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. 64 * 65 * usage: 66 * tsort [-l] [inputfile] 67 * If no input file is specified, standard input is read. 68 * 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). 74 * 75 * Michael Rendell, michael@stretch.cs.mun.ca - Feb 26, '90 76 */ 77 #define HASHSIZE 53 /* doesn't need to be big */ 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 */ 81 82 typedef struct node_str NODE; 83 84 struct node_str { 85 NODE **n_prevp; /* pointer to previous node's n_next */ 86 NODE *n_next; /* next node in graph */ 87 NODE **n_arcs; /* array of arcs to other nodes */ 88 int n_narcs; /* number of arcs in n_arcs[] */ 89 int n_arcsize; /* size of n_arcs[] array */ 90 int n_refcnt; /* # of arcs pointing to this node */ 91 int n_flags; /* NF_* */ 92 char n_name[1]; /* name of this node */ 93 }; 94 95 typedef struct _buf { 96 char *b_buf; 97 int b_bsize; 98 } BUF; 99 100 DB *db; 101 NODE *graph, **cycle_buf, **longest_cycle; 102 int debug, longest, quiet; 103 104 void add_arc __P((char *, char *)); 105 void clear_cycle __P((void)); 106 int find_cycle __P((NODE *, NODE *, int, int)); 107 NODE *get_node __P((char *)); 108 void *grow_buf __P((void *, int)); 109 int main __P((int, char **)); 110 void remove_node __P((NODE *)); 111 void tsort __P((void)); 112 void usage __P((void)); 113 114 int 115 main(argc, argv) 116 int argc; 117 char *argv[]; 118 { 119 BUF *b; 120 int c, n; 121 FILE *fp; 122 int bsize, ch, nused; 123 BUF bufs[2]; 124 125 setprogname(argv[0]); 126 127 fp = NULL; 128 while ((ch = getopt(argc, argv, "dlq")) != -1) 129 switch (ch) { 130 case 'd': 131 debug = 1; 132 break; 133 case 'l': 134 longest = 1; 135 break; 136 case 'q': 137 quiet = 1; 138 break; 139 case '?': 140 default: 141 usage(); 142 } 143 argc -= optind; 144 argv += optind; 145 146 switch (argc) { 147 case 0: 148 fp = stdin; 149 break; 150 case 1: 151 if ((fp = fopen(*argv, "r")) == NULL) 152 err(1, "%s", *argv); 153 break; 154 default: 155 usage(); 156 } 157 158 for (b = bufs, n = 2; --n >= 0; b++) 159 b->b_buf = grow_buf(NULL, b->b_bsize = 1024); 160 161 /* parse input and build the graph */ 162 for (n = 0, c = getc(fp);;) { 163 while (c != EOF && isspace(c)) 164 c = getc(fp); 165 if (c == EOF) 166 break; 167 168 nused = 0; 169 b = &bufs[n]; 170 bsize = b->b_bsize; 171 do { 172 b->b_buf[nused++] = c; 173 if (nused == bsize) 174 b->b_buf = grow_buf(b->b_buf, bsize *= 2); 175 c = getc(fp); 176 } while (c != EOF && !isspace(c)); 177 178 b->b_buf[nused] = '\0'; 179 b->b_bsize = bsize; 180 if (n) 181 add_arc(bufs[0].b_buf, bufs[1].b_buf); 182 n = !n; 183 } 184 (void)fclose(fp); 185 if (n) 186 errx(1, "odd data count"); 187 188 /* do the sort */ 189 tsort(); 190 return(0); 191 } 192 193 /* double the size of oldbuf and return a pointer to the new buffer. */ 194 void * 195 grow_buf(bp, size) 196 void *bp; 197 int size; 198 { 199 void *n; 200 201 if ((n = realloc(bp, (u_int)size)) == NULL) 202 err(1, "realloc"); 203 bp = n; 204 return (bp); 205 } 206 207 /* 208 * add an arc from node s1 to node s2 in the graph. If s1 or s2 are not in 209 * the graph, then add them. 210 */ 211 void 212 add_arc(s1, s2) 213 char *s1, *s2; 214 { 215 NODE *n1; 216 NODE *n2; 217 int bsize, i; 218 219 n1 = get_node(s1); 220 221 if (!strcmp(s1, s2)) 222 return; 223 224 n2 = get_node(s2); 225 226 /* 227 * Check if this arc is already here. 228 */ 229 for (i = 0; i < n1->n_narcs; i++) 230 if (n1->n_arcs[i] == n2) 231 return; 232 /* 233 * Add it. 234 */ 235 if (n1->n_narcs == n1->n_arcsize) { 236 if (!n1->n_arcsize) 237 n1->n_arcsize = 10; 238 bsize = n1->n_arcsize * sizeof(*n1->n_arcs) * 2; 239 n1->n_arcs = grow_buf(n1->n_arcs, bsize); 240 n1->n_arcsize = bsize / sizeof(*n1->n_arcs); 241 } 242 n1->n_arcs[n1->n_narcs++] = n2; 243 ++n2->n_refcnt; 244 } 245 246 /* Find a node in the graph (insert if not found) and return a pointer to it. */ 247 NODE * 248 get_node(name) 249 char *name; 250 { 251 DBT data, key; 252 NODE *n; 253 254 if (db == NULL && 255 (db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) 256 err(1, "db: %s", name); 257 258 key.data = name; 259 key.size = strlen(name) + 1; 260 261 switch ((*db->get)(db, &key, &data, 0)) { 262 case 0: 263 (void)memmove(&n, data.data, sizeof(n)); 264 return (n); 265 case 1: 266 break; 267 default: 268 case -1: 269 err(1, "db: %s", name); 270 } 271 272 if ((n = malloc(sizeof(NODE) + key.size)) == NULL) 273 err(1, "malloc"); 274 275 n->n_narcs = 0; 276 n->n_arcsize = 0; 277 n->n_arcs = NULL; 278 n->n_refcnt = 0; 279 n->n_flags = 0; 280 (void)memmove(n->n_name, name, key.size); 281 282 /* Add to linked list. */ 283 if ((n->n_next = graph) != NULL) 284 graph->n_prevp = &n->n_next; 285 n->n_prevp = &graph; 286 graph = n; 287 288 /* Add to hash table. */ 289 data.data = &n; 290 data.size = sizeof(n); 291 if ((*db->put)(db, &key, &data, 0)) 292 err(1, "db: %s", name); 293 return (n); 294 } 295 296 297 /* 298 * Clear the NODEST flag from all nodes. 299 */ 300 void 301 clear_cycle() 302 { 303 NODE *n; 304 305 for (n = graph; n != NULL; n = n->n_next) 306 n->n_flags &= ~NF_NODEST; 307 } 308 309 /* do topological sort on graph */ 310 void 311 tsort() 312 { 313 NODE *n, *next; 314 int cnt, i; 315 316 while (graph != NULL) { 317 /* 318 * Keep getting rid of simple cases until there are none left, 319 * if there are any nodes still in the graph, then there is 320 * a cycle in it. 321 */ 322 do { 323 for (cnt = 0, n = graph; n != NULL; n = next) { 324 next = n->n_next; 325 if (n->n_refcnt == 0) { 326 remove_node(n); 327 ++cnt; 328 } 329 } 330 } while (graph != NULL && cnt); 331 332 if (graph == NULL) 333 break; 334 335 if (!cycle_buf) { 336 /* 337 * Allocate space for two cycle logs - one to be used 338 * as scratch space, the other to save the longest 339 * cycle. 340 */ 341 for (cnt = 0, n = graph; n != NULL; n = n->n_next) 342 ++cnt; 343 cycle_buf = malloc((u_int)sizeof(NODE *) * cnt); 344 longest_cycle = malloc((u_int)sizeof(NODE *) * cnt); 345 if (cycle_buf == NULL || longest_cycle == NULL) 346 err(1, "malloc"); 347 } 348 for (n = graph; n != NULL; n = n->n_next) { 349 if (!(n->n_flags & NF_ACYCLIC)) { 350 if ((cnt = find_cycle(n, n, 0, 0)) != 0) { 351 if (!quiet) { 352 warnx("cycle in data"); 353 for (i = 0; i < cnt; i++) 354 warnx("%s", 355 longest_cycle[i]->n_name); 356 } 357 remove_node(n); 358 clear_cycle(); 359 break; 360 } else { 361 /* to avoid further checks */ 362 n->n_flags |= NF_ACYCLIC; 363 clear_cycle(); 364 } 365 } 366 } 367 if (n == NULL) 368 errx(1, "internal error -- could not find cycle"); 369 } 370 } 371 372 /* print node and remove from graph (does not actually free node) */ 373 void 374 remove_node(n) 375 NODE *n; 376 { 377 NODE **np; 378 int i; 379 380 (void)printf("%s\n", n->n_name); 381 for (np = n->n_arcs, i = n->n_narcs; --i >= 0; np++) 382 --(*np)->n_refcnt; 383 n->n_narcs = 0; 384 *n->n_prevp = n->n_next; 385 if (n->n_next) 386 n->n_next->n_prevp = n->n_prevp; 387 } 388 389 390 /* look for the longest? cycle from node from to node to. */ 391 int 392 find_cycle(from, to, longest_len, depth) 393 NODE *from, *to; 394 int depth, longest_len; 395 { 396 NODE **np; 397 int i, len; 398 399 /* 400 * avoid infinite loops and ignore portions of the graph known 401 * to be acyclic 402 */ 403 if (from->n_flags & (NF_NODEST|NF_MARK|NF_ACYCLIC)) 404 return (0); 405 from->n_flags |= NF_MARK; 406 407 for (np = from->n_arcs, i = from->n_narcs; --i >= 0; np++) { 408 cycle_buf[depth] = *np; 409 if (*np == to) { 410 if (depth + 1 > longest_len) { 411 longest_len = depth + 1; 412 (void)memcpy(longest_cycle, cycle_buf, 413 longest_len * sizeof(NODE *)); 414 } 415 } else { 416 if ((*np)->n_flags & (NF_MARK|NF_ACYCLIC|NF_NODEST)) 417 continue; 418 len = find_cycle(*np, to, longest_len, depth + 1); 419 420 if (debug) 421 (void)printf("%*s %s->%s %d\n", depth, "", 422 from->n_name, to->n_name, len); 423 424 if (len == 0) 425 (*np)->n_flags |= NF_NODEST; 426 427 if (len > longest_len) 428 longest_len = len; 429 430 if (len > 0 && !longest) 431 break; 432 } 433 } 434 from->n_flags &= ~NF_MARK; 435 return (longest_len); 436 } 437 438 void 439 usage() 440 { 441 (void)fprintf(stderr, "usage: tsort [-lq] [file]\n"); 442 exit(1); 443 } 444