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