[BACK]Return to tsort.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / tsort

Annotation of src/usr.bin/tsort/tsort.c, Revision 1.29

1.29    ! espie       1: /* $OpenBSD: tsort.c,v 1.28 2015/08/31 09:36:02 espie Exp $ */
1.15      espie       2: /* ex:ts=8 sw=4:
1.1       deraadt     3:  *
1.19      espie       4:  * Copyright (c) 1999-2004 Marc Espie <espie@openbsd.org>
1.1       deraadt     5:  *
1.19      espie       6:  * Permission to use, copy, modify, and distribute this software for any
                      7:  * purpose with or without fee is hereby granted, provided that the above
                      8:  * copyright notice and this permission notice appear in all copies.
                      9:  *
                     10:  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
                     11:  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
                     12:  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
                     13:  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
                     14:  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
                     15:  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
                     16:  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1.1       deraadt    17:  */
                     18:
1.5       espie      19: #include <assert.h>
1.1       deraadt    20: #include <ctype.h>
                     21: #include <err.h>
1.5       espie      22: #include <limits.h>
                     23: #include <stddef.h>
1.1       deraadt    24: #include <stdio.h>
1.20      espie      25: #include <stdint.h>
1.1       deraadt    26: #include <stdlib.h>
                     27: #include <string.h>
1.5       espie      28: #include <sysexits.h>
1.1       deraadt    29: #include <unistd.h>
1.20      espie      30: #include <ohash.h>
1.1       deraadt    31:
1.15      espie      32: /* The complexity of topological sorting is O(e), where e is the
1.5       espie      33:  * size of input.  While reading input, vertices have to be identified,
                     34:  * thus add the complexity of e keys retrieval among v keys using
1.15      espie      35:  * an appropriate data structure.  This program uses open double hashing
                     36:  * for that purpose.  See Knuth for the expected complexity of double
1.5       espie      37:  * hashing (Brent variation should probably be used if v << e, as a user
                     38:  * option).
                     39:  *
                     40:  * The algorithm used for longest cycle reporting is accurate, but somewhat
                     41:  * expensive.  It may need to build all free paths of the graph (a free
                     42:  * path is a path that never goes twice through the same node), whose
1.15      espie      43:  * number can be as high as O(2^e).  Usually, the number of free paths is
1.5       espie      44:  * much smaller though.  This program's author does not believe that a
                     45:  * significantly better worst-case complexity algorithm exists.
                     46:  *
                     47:  * In case of a hints file, the set of minimal nodes is maintained as a
                     48:  * heap.  The resulting complexity is O(e+v log v) for the worst case.
                     49:  * The average should actually be near O(e).
                     50:  *
1.8       espie      51:  * If the hints file is incomplete, there is some extra complexity incurred
                     52:  * by make_transparent, which does propagate order values to unmarked
                     53:  * nodes. In the worst case, make_transparent is  O(e u),
                     54:  * where u is the number of originally unmarked nodes.
                     55:  * In practice, it is much faster.
                     56:  *
1.5       espie      57:  * The simple topological sort algorithm detects cycles.  This program
1.15      espie      58:  * goes further, breaking cycles through the use of simple heuristics.
                     59:  * Each cycle break checks the whole set of nodes, hence if c cycles break
1.5       espie      60:  * are needed, this is an extra cost of O(c v).
1.1       deraadt    61:  *
1.5       espie      62:  * Possible heuristics are as follows:
                     63:  * - break cycle at node with lowest number of predecessors (default case),
                     64:  * - break longest cycle at node with lowest number of predecessors,
                     65:  * - break cycle at next node from the hints file.
1.1       deraadt    66:  *
1.5       espie      67:  * Except for the hints file case, which sets an explicit constraint on
1.15      espie      68:  * which cycle to break, those heuristics locally result in the smallest
1.5       espie      69:  * number of broken edges.
1.1       deraadt    70:  *
1.5       espie      71:  * Those are admittedly greedy strategies, as is the selection of the next
                     72:  * node from the hints file amongst equivalent candidates that is used for
                     73:  * `stable' topological sorting.
1.1       deraadt    74:  */
1.5       espie      75:
                     76: #ifdef __GNUC__
                     77: #define UNUSED __attribute__((unused))
                     78: #else
                     79: #define UNUSED
                     80: #endif
                     81:
                     82: struct node;
                     83:
                     84: /* The set of arcs from a given node is stored as a linked list.  */
                     85: struct link {
                     86:        struct link *next;
                     87:        struct node *node;
                     88: };
                     89:
1.7       espie      90: #define NO_ORDER       UINT_MAX
                     91:
1.5       espie      92: struct node {
1.15      espie      93:        unsigned int refs;      /* Number of arcs left, coming into this node.
                     94:                                 * Note that nodes with a null count can't
1.5       espie      95:                                 * be part of cycles.  */
                     96:        struct link  *arcs;     /* List of forward arcs.  */
                     97:
                     98:        unsigned int order;     /* Order of nodes according to a hint file.  */
                     99:
                    100:        /* Cycle detection algorithms build a free path of nodes.  */
                    101:        struct node  *from;     /* Previous node in the current path.  */
                    102:
                    103:        unsigned int mark;      /* Mark processed nodes in cycle discovery.  */
                    104:        struct link  *traverse; /* Next link to traverse when backtracking.  */
                    105:        char         k[1];      /* Name of this node.  */
1.1       deraadt   106: };
                    107:
1.5       espie     108: #define HASH_START 9
                    109:
                    110: struct array {
                    111:        unsigned int entries;
                    112:        struct node  **t;
                    113: };
                    114:
1.12      millert   115: static void nodes_init(struct ohash *);
                    116: static struct node *node_lookup(struct ohash *, const char *, const char *);
                    117: static void usage(void);
                    118: static struct node *new_node(const char *, const char *);
1.5       espie     119:
1.15      espie     120: static unsigned int read_pairs(FILE *, struct ohash *, int,
1.13      millert   121:     const char *, unsigned int, int);
1.12      millert   122: static void split_nodes(struct ohash *, struct array *, struct array *);
                    123: static void make_transparent(struct ohash *);
                    124: static void insert_arc(struct node *, struct node *);
1.5       espie     125:
                    126: #ifdef DEBUG
1.12      millert   127: static void dump_node(struct node *);
                    128: static void dump_array(struct array *);
                    129: static void dump_hash(struct ohash *);
1.5       espie     130: #endif
1.15      espie     131: static unsigned int read_hints(FILE *, struct ohash *, int,
1.13      millert   132:     const char *, unsigned int);
1.12      millert   133: static struct node *find_smallest_node(struct array *);
                    134: static struct node *find_good_cycle_break(struct array *);
                    135: static void print_cycle(struct array *);
                    136: static struct node *find_cycle_from(struct node *, struct array *);
                    137: static struct node *find_predecessor(struct array *, struct node *);
                    138: static unsigned int traverse_node(struct node *, unsigned int, struct array *);
                    139: static struct node *find_longest_cycle(struct array *, struct array *);
1.29    ! espie     140: static struct node *find_normal_cycle(struct array *, struct array *);
1.12      millert   141:
                    142: static void heap_down(struct array *, unsigned int);
                    143: static void heapify(struct array *, int);
                    144: static struct node *dequeue(struct array *);
                    145: static void enqueue(struct array *, struct node *);
1.5       espie     146:
1.1       deraadt   147:
1.5       espie     148:
1.23      espie     149: static void *hash_calloc(size_t, size_t, void *);
                    150: static void hash_free(void *, void *);
1.12      millert   151: static void* entry_alloc(size_t, void *);
1.24      deraadt   152: static void *ereallocarray(void *, size_t, size_t);
1.12      millert   153: static void *emem(void *);
1.5       espie     154: #define DEBUG_TRAVERSE 0
1.15      espie     155: static struct ohash_info node_info = {
1.23      espie     156:        offsetof(struct node, k), NULL, hash_calloc, hash_free, entry_alloc };
1.29    ! espie     157: static void parse_args(int, char *[], struct ohash *);
        !           158: static int tsort(struct ohash *);
        !           159:
        !           160: static int             quiet_flag, long_flag,
        !           161:                        warn_flag, hints_flag, verbose_flag;
1.5       espie     162:
                    163:
1.12      millert   164: int main(int, char *[]);
1.5       espie     165:
                    166: /***
1.15      espie     167:  *** Memory handling.
1.5       espie     168:  ***/
                    169:
                    170: static void *
1.14      espie     171: emem(void *p)
1.5       espie     172: {
                    173:        if (p)
                    174:                return p;
                    175:        else
                    176:                errx(EX_SOFTWARE, "Memory exhausted");
                    177: }
                    178:
                    179: static void *
1.23      espie     180: hash_calloc(size_t n, size_t s, void *u UNUSED)
1.5       espie     181: {
1.23      espie     182:        return emem(calloc(n, s));
1.5       espie     183: }
                    184:
                    185: static void
1.23      espie     186: hash_free(void *p, void *u UNUSED)
1.5       espie     187: {
                    188:        free(p);
                    189: }
                    190:
                    191: static void *
1.14      espie     192: entry_alloc(size_t s, void *u UNUSED)
1.5       espie     193: {
1.24      deraadt   194:        return ereallocarray(NULL, 1, s);
1.5       espie     195: }
                    196:
                    197: static void *
1.24      deraadt   198: ereallocarray(void *p, size_t n, size_t s)
1.1       deraadt   199: {
1.24      deraadt   200:        return emem(reallocarray(p, n, s));
1.5       espie     201: }
1.1       deraadt   202:
1.5       espie     203: 
1.15      espie     204: /***
1.5       espie     205:  *** Hash table.
                    206:  ***/
                    207:
                    208: /* Inserting and finding nodes in the hash structure.
                    209:  * We handle interval strings for efficiency wrt fgetln.  */
                    210: static struct node *
1.14      espie     211: new_node(const char *start, const char *end)
1.5       espie     212: {
                    213:        struct node     *n;
1.1       deraadt   214:
1.5       espie     215:        n = ohash_create_entry(&node_info, start, &end);
                    216:        n->from = NULL;
                    217:        n->arcs = NULL;
                    218:        n->refs = 0;
                    219:        n->mark = 0;
1.7       espie     220:        n->order = NO_ORDER;
1.5       espie     221:        n->traverse = NULL;
                    222:        return n;
                    223: }
1.1       deraadt   224:
                    225:
1.15      espie     226: static void
1.14      espie     227: nodes_init(struct ohash *h)
1.5       espie     228: {
                    229:        ohash_init(h, HASH_START, &node_info);
1.1       deraadt   230: }
                    231:
1.5       espie     232: static struct node *
1.14      espie     233: node_lookup(struct ohash *h, const char *start, const char *end)
1.1       deraadt   234: {
1.5       espie     235:        unsigned int    i;
                    236:        struct node *   n;
1.1       deraadt   237:
1.5       espie     238:        i = ohash_qlookupi(h, start, &end);
1.1       deraadt   239:
1.5       espie     240:        n = ohash_find(h, i);
                    241:        if (n == NULL)
                    242:                n = ohash_insert(h, i, new_node(start, end));
                    243:        return n;
                    244: }
1.25      jasper    245:
1.5       espie     246: #ifdef DEBUG
                    247: static void
1.14      espie     248: dump_node(struct node *n)
1.5       espie     249: {
                    250:        struct link     *l;
                    251:
                    252:        if (n->refs == 0)
1.1       deraadt   253:                return;
1.8       espie     254:        printf("%s (%u/%u): ", n->k, n->order, n->refs);
1.5       espie     255:        for (l = n->arcs; l != NULL; l = l->next)
                    256:                if (n->refs != 0)
1.8       espie     257:                printf("%s(%u/%u) ", l->node->k, l->node->order, l->node->refs);
1.5       espie     258:        putchar('\n');
                    259: }
1.1       deraadt   260:
1.5       espie     261: static void
1.14      espie     262: dump_array(struct array *a)
1.5       espie     263: {
                    264:        unsigned int    i;
1.1       deraadt   265:
1.5       espie     266:        for (i = 0; i < a->entries; i++)
                    267:                dump_node(a->t[i]);
                    268: }
1.25      jasper    269:
1.15      espie     270: static void
1.14      espie     271: dump_hash(struct ohash *h)
1.5       espie     272: {
                    273:        unsigned int    i;
                    274:        struct node     *n;
                    275:
                    276:        for (n = ohash_first(h, &i); n != NULL; n = ohash_next(h, &i))
                    277:                dump_node(n);
                    278: }
                    279: #endif
1.25      jasper    280:
1.5       espie     281: /***
                    282:  *** Reading data.
                    283:  ***/
                    284:
1.15      espie     285: static void
1.14      espie     286: insert_arc(struct node *a, struct node *b)
1.5       espie     287: {
                    288:        struct link     *l;
                    289:
                    290:        /* Check that this arc is not already present.  */
                    291:        for (l = a->arcs; l != NULL; l = l->next) {
                    292:                if (l->node == b)
1.1       deraadt   293:                        return;
1.5       espie     294:        }
                    295:        b->refs++;
1.24      deraadt   296:        l = ereallocarray(NULL, 1, sizeof(struct link));
1.5       espie     297:        l->node = b;
                    298:        l->next = a->arcs;
                    299:        a->arcs = l;
                    300: }
1.1       deraadt   301:
1.7       espie     302: static unsigned int
1.15      espie     303: read_pairs(FILE *f, struct ohash *h, int reverse, const char *name,
1.14      espie     304:     unsigned int order, int hint)
1.5       espie     305: {
                    306:        int             toggle;
                    307:        struct node     *a;
                    308:        size_t          size;
                    309:        char            *str;
                    310:
                    311:        toggle = 1;
                    312:        a = NULL;
1.25      jasper    313:
1.5       espie     314:        while ((str = fgetln(f, &size)) != NULL) {
                    315:                char *sentinel;
                    316:
                    317:                sentinel = str + size;
                    318:                for (;;) {
                    319:                        char *e;
                    320:
1.22      deraadt   321:                        while (str < sentinel &&
                    322:                            isspace((unsigned char)*str))
1.5       espie     323:                                str++;
                    324:                        if (str == sentinel)
                    325:                                break;
1.22      deraadt   326:                        for (e = str;
                    327:                            e < sentinel && !isspace((unsigned char)*e); e++)
1.5       espie     328:                                continue;
                    329:                        if (toggle) {
                    330:                                a = node_lookup(h, str, e);
1.8       espie     331:                                if (a->order == NO_ORDER && hint)
1.7       espie     332:                                        a->order = order++;
1.5       espie     333:                        } else {
                    334:                                struct node *b;
                    335:
                    336:                                b = node_lookup(h, str, e);
                    337:                                assert(a != NULL);
                    338:                                if (b != a) {
1.15      espie     339:                                        if (reverse)
1.5       espie     340:                                                insert_arc(b, a);
1.15      espie     341:                                        else
1.5       espie     342:                                                insert_arc(a, b);
                    343:                                }
                    344:                        }
                    345:                        toggle = !toggle;
                    346:                        str = e;
                    347:                }
                    348:        }
                    349:        if (toggle == 0)
1.21      jmc       350:                errx(EX_DATAERR, "odd number of node names in %s", name);
1.5       espie     351:        if (!feof(f))
                    352:                err(EX_IOERR, "error reading %s", name);
1.7       espie     353:        return order;
1.5       espie     354: }
1.1       deraadt   355:
1.7       espie     356: static unsigned int
1.15      espie     357: read_hints(FILE *f, struct ohash *h, int quiet, const char *name,
1.14      espie     358:     unsigned int order)
1.5       espie     359: {
                    360:        char            *str;
                    361:        size_t          size;
                    362:
                    363:        while ((str = fgetln(f, &size)) != NULL) {
                    364:                char *sentinel;
                    365:
                    366:                sentinel = str + size;
                    367:                for (;;) {
                    368:                        char *e;
                    369:                        struct node *a;
                    370:
1.22      deraadt   371:                        while (str < sentinel && isspace((unsigned char)*str))
1.5       espie     372:                                str++;
                    373:                        if (str == sentinel)
                    374:                                break;
1.22      deraadt   375:                        for (e = str;
                    376:                            e < sentinel && !isspace((unsigned char)*e); e++)
1.5       espie     377:                                continue;
                    378:                        a = node_lookup(h, str, e);
1.7       espie     379:                        if (a->order != NO_ORDER) {
1.6       espie     380:                                if (!quiet)
                    381:                                    warnx(
1.5       espie     382:                                        "duplicate node %s in hints file %s",
                    383:                                        a->k, name);
1.7       espie     384:                        } else
                    385:                                a->order = order++;
1.5       espie     386:                        str = e;
                    387:                }
                    388:        }
1.7       espie     389:        return order;
1.5       espie     390: }
                    391:
                    392: 
                    393: /***
1.15      espie     394:  *** Standard heap handling routines.
1.5       espie     395:  ***/
                    396:
1.15      espie     397: static void
1.14      espie     398: heap_down(struct array *h, unsigned int i)
1.5       espie     399: {
                    400:        unsigned int    j;
                    401:        struct node     *swap;
                    402:
                    403:        for (; (j=2*i+1) < h->entries; i = j) {
                    404:                if (j+1 < h->entries && h->t[j+1]->order < h->t[j]->order)
                    405:                        j++;
                    406:                if (h->t[i]->order <= h->t[j]->order)
                    407:                        break;
                    408:                swap = h->t[i];
                    409:                h->t[i] = h->t[j];
                    410:                h->t[j] = swap;
1.1       deraadt   411:        }
1.5       espie     412: }
                    413:
1.15      espie     414: static void
1.14      espie     415: heapify(struct array *h, int verbose)
1.5       espie     416: {
                    417:        unsigned int    i;
1.1       deraadt   418:
1.6       espie     419:        for (i = h->entries; i != 0;) {
1.8       espie     420:                if (h->t[--i]->order == NO_ORDER && verbose)
1.6       espie     421:                        warnx("node %s absent from hints file", h->t[i]->k);
                    422:                heap_down(h, i);
                    423:        }
1.5       espie     424: }
                    425:
                    426: #define DEQUEUE(h) ( hints_flag ? dequeue(h) : (h)->t[--(h)->entries] )
1.1       deraadt   427:
1.5       espie     428: static struct node *
1.14      espie     429: dequeue(struct array *h)
1.5       espie     430: {
                    431:        struct node     *n;
                    432:
                    433:        if (h->entries == 0)
                    434:                n = NULL;
                    435:        else {
                    436:                n = h->t[0];
                    437:                if (--h->entries != 0) {
                    438:                    h->t[0] = h->t[h->entries];
                    439:                    heap_down(h, 0);
                    440:                }
                    441:        }
                    442:        return n;
1.1       deraadt   443: }
1.25      jasper    444:
1.5       espie     445: #define ENQUEUE(h, n) do {                     \
                    446:        if (hints_flag)                         \
                    447:                enqueue((h), (n));              \
                    448:        else                                    \
                    449:                (h)->t[(h)->entries++] = (n);   \
                    450:        } while(0);
                    451:
1.15      espie     452: static void
1.14      espie     453: enqueue(struct array *h, struct node *n)
1.5       espie     454: {
                    455:        unsigned int    i, j;
                    456:        struct node     *swap;
1.1       deraadt   457:
1.5       espie     458:        h->t[h->entries++] = n;
                    459:        for (i = h->entries-1; i > 0; i = j) {
                    460:                j = (i-1)/2;
                    461:                if (h->t[j]->order < h->t[i]->order)
                    462:                        break;
                    463:                swap = h->t[j];
                    464:                h->t[j] = h->t[i];
                    465:                h->t[i] = swap;
                    466:        }
                    467: }
1.1       deraadt   468:
1.8       espie     469: /* Nodes without order should not hinder direct dependencies.
1.15      espie     470:  * Iterate until no nodes are left.
1.8       espie     471:  */
                    472: static void
1.14      espie     473: make_transparent(struct ohash *hash)
1.8       espie     474: {
                    475:        struct node     *n;
                    476:        unsigned int    i;
                    477:        struct link     *l;
                    478:        int             adjusted;
                    479:        int             bad;
                    480:        unsigned int    min;
                    481:
                    482:        /* first try to solve complete nodes */
                    483:        do {
                    484:                adjusted = 0;
                    485:                bad = 0;
1.15      espie     486:                for (n = ohash_first(hash, &i); n != NULL;
1.8       espie     487:                    n = ohash_next(hash, &i)) {
                    488:                        if (n->order == NO_ORDER) {
                    489:                                min = NO_ORDER;
                    490:
                    491:                                for (l = n->arcs; l != NULL; l = l->next) {
                    492:                                        /* unsolved node -> delay resolution */
                    493:                                        if (l->node->order == NO_ORDER) {
                    494:                                                bad = 1;
                    495:                                                break;
                    496:                                        } else if (l->node->order < min)
                    497:                                                min = l->node->order;
                    498:                                }
                    499:                                if (min < NO_ORDER && l == NULL) {
                    500:                                        n->order = min;
                    501:                                        adjusted = 1;
                    502:                                }
                    503:                        }
                    504:                }
                    505:
                    506:        } while (adjusted);
                    507:
                    508:        /* then, if incomplete nodes are left, do them */
                    509:        if (bad) do {
                    510:                adjusted = 0;
1.15      espie     511:                for (n = ohash_first(hash, &i); n != NULL;
1.8       espie     512:                    n = ohash_next(hash, &i))
                    513:                        if (n->order == NO_ORDER)
                    514:                                for (l = n->arcs; l != NULL; l = l->next)
                    515:                                        if (l->node->order < n->order) {
                    516:                                                n->order = l->node->order;
                    517:                                                adjusted = 1;
                    518:                                        }
                    519:        } while (adjusted);
                    520: }
                    521:
1.5       espie     522: 
                    523: /***
                    524:  *** Search through hash array for nodes.
                    525:  ***/
                    526:
                    527: /* Split nodes into unrefed nodes/live nodes.  */
                    528: static void
1.14      espie     529: split_nodes(struct ohash *hash, struct array *heap, struct array *remaining)
1.1       deraadt   530: {
                    531:
1.5       espie     532:        struct node *n;
                    533:        unsigned int i;
                    534:
1.24      deraadt   535:        heap->t = ereallocarray(NULL, ohash_entries(hash),
                    536:            sizeof(struct node *));
                    537:        remaining->t = ereallocarray(NULL, ohash_entries(hash),
                    538:            sizeof(struct node *));
1.5       espie     539:        heap->entries = 0;
                    540:        remaining->entries = 0;
                    541:
                    542:        for (n = ohash_first(hash, &i); n != NULL; n = ohash_next(hash, &i)) {
1.15      espie     543:                if (n->refs == 0)
1.5       espie     544:                        heap->t[heap->entries++] = n;
                    545:                else
1.9       espie     546:                        remaining->t[remaining->entries++] = n;
1.5       espie     547:        }
1.1       deraadt   548: }
                    549:
1.5       espie     550: /* Good point to break a cycle: live node with as few refs as possible. */
                    551: static struct node *
1.14      espie     552: find_good_cycle_break(struct array *h)
1.5       espie     553: {
                    554:        unsigned int    i;
1.15      espie     555:        unsigned int    best;
                    556:        struct node     *u;
1.5       espie     557:
                    558:        best = UINT_MAX;
                    559:        u = NULL;
                    560:
                    561:        assert(h->entries != 0);
                    562:        for (i = 0; i < h->entries; i++) {
                    563:                struct node *n = h->t[i];
1.25      jasper    564:                /* No need to look further. */
1.5       espie     565:                if (n->refs == 1)
                    566:                        return n;
                    567:                if (n->refs != 0 && n->refs < best) {
                    568:                        best = n->refs;
                    569:                        u = n;
                    570:                }
                    571:        }
                    572:        assert(u != NULL);
                    573:        return u;
                    574: }
1.25      jasper    575:
1.5       espie     576: /*  Retrieve the node with the smallest order.  */
1.15      espie     577: static struct node *
1.14      espie     578: find_smallest_node(struct array *h)
1.5       espie     579: {
                    580:        unsigned int    i;
                    581:        unsigned int    best;
                    582:        struct node     *u;
                    583:
                    584:        best = UINT_MAX;
                    585:        u = NULL;
                    586:
                    587:        assert(h->entries != 0);
                    588:        for (i = 0; i < h->entries; i++) {
                    589:                struct node *n = h->t[i];
                    590:                if (n->refs != 0 && n->order < best) {
                    591:                        best = n->order;
                    592:                        u = n;
                    593:                }
                    594:        }
                    595:        assert(u != NULL);
                    596:        return u;
                    597: }
                    598:
                    599: 
                    600: /***
                    601:  *** Graph algorithms.
                    602:  ***/
                    603:
1.15      espie     604: /* Explore the nodes reachable from i to find a cycle, store it in c.
1.10      espie     605:  * This may fail.  */
1.15      espie     606: static struct node *
1.14      espie     607: find_cycle_from(struct node *i, struct array *c)
1.5       espie     608: {
                    609:        struct node     *n;
                    610:
                    611:        n = i;
                    612:        /* XXX Previous cycle findings may have left this pointer non-null.  */
                    613:        i->from = NULL;
                    614:
                    615:        for (;;) {
                    616:                /* Note that all marks are reversed before this code exits.  */
                    617:                n->mark = 1;
1.15      espie     618:                if (n->traverse)
1.5       espie     619:                        n->traverse = n->traverse->next;
                    620:                else
                    621:                        n->traverse = n->arcs;
                    622:                /* Skip over dead nodes.  */
                    623:                while (n->traverse && n->traverse->node->refs == 0)
                    624:                        n->traverse = n->traverse->next;
                    625:                if (n->traverse) {
                    626:                        struct node *go = n->traverse->node;
                    627:
                    628:                        if (go->mark) {
1.10      espie     629:                                c->entries = 0;
                    630:                                for (; n != NULL && n != go; n = n->from) {
                    631:                                        c->t[c->entries++] = n;
                    632:                                        n->mark = 0;
1.1       deraadt   633:                                }
1.10      espie     634:                                for (; n != NULL; n = n->from)
                    635:                                        n->mark = 0;
                    636:                                c->t[c->entries++] = go;
                    637:                                return go;
1.5       espie     638:                        } else {
                    639:                            go->from = n;
                    640:                            n = go;
1.1       deraadt   641:                        }
1.5       espie     642:                } else {
                    643:                        n->mark = 0;
                    644:                        n = n->from;
1.15      espie     645:                        if (n == NULL)
1.10      espie     646:                                return NULL;
1.5       espie     647:                }
                    648:        }
                    649: }
1.1       deraadt   650:
1.5       espie     651: /* Find a live predecessor of node n.  This is a slow routine, as it needs
                    652:  * to go through the whole array, but it is not needed often.
                    653:  */
                    654: static struct node *
1.14      espie     655: find_predecessor(struct array *a, struct node *n)
1.5       espie     656: {
                    657:        unsigned int i;
                    658:
                    659:        for (i = 0; i < a->entries; i++) {
                    660:                struct node *m;
1.1       deraadt   661:
1.5       espie     662:                m = a->t[i];
                    663:                if (m->refs != 0) {
                    664:                        struct link *l;
                    665:
                    666:                        for (l = m->arcs; l != NULL; l = l->next)
                    667:                                if (l->node == n)
                    668:                                        return m;
1.1       deraadt   669:                }
1.5       espie     670:        }
                    671:        assert(1 == 0);
                    672:        return NULL;
                    673: }
                    674:
                    675: /* Traverse all strongly connected components reachable from node n.
                    676:    Start numbering them at o. Return the maximum order reached.
                    677:    Update the largest cycle found so far.
                    678:  */
1.15      espie     679: static unsigned int
1.14      espie     680: traverse_node(struct node *n, unsigned int o, struct array *c)
1.5       espie     681: {
                    682:        unsigned int    min, max;
                    683:
                    684:        n->from = NULL;
                    685:        min = o;
                    686:        max = ++o;
                    687:
                    688:        for (;;) {
                    689:                n->mark = o;
                    690:                if (DEBUG_TRAVERSE)
1.11      espie     691:                        printf("%s(%u) ", n->k, n->mark);
1.5       espie     692:                /* Find next arc to explore.  */
1.15      espie     693:                if (n->traverse)
1.5       espie     694:                        n->traverse = n->traverse->next;
                    695:                else
                    696:                        n->traverse = n->arcs;
                    697:                /* Skip over dead nodes.  */
                    698:                while (n->traverse && n->traverse->node->refs == 0)
                    699:                        n->traverse = n->traverse->next;
                    700:                /* If arc left.  */
                    701:                if (n->traverse) {
                    702:                        struct node     *go;
                    703:
                    704:                        go = n->traverse->node;
1.15      espie     705:                        /* Optimisation: if go->mark < min, we already
1.5       espie     706:                         * visited this strongly-connected component in
                    707:                         * a previous pass.  Hence, this can yield no new
                    708:                         * cycle.  */
                    709:
                    710:                        /* Not part of the current path: go for it.  */
                    711:                        if (go->mark == 0 || go->mark == min) {
                    712:                                go->from = n;
                    713:                                n = go;
                    714:                                o++;
                    715:                                if (o > max)
                    716:                                        max = o;
                    717:                        /* Part of the current path: check cycle length.  */
                    718:                        } else if (go->mark > min) {
                    719:                                if (DEBUG_TRAVERSE)
                    720:                                        printf("%d\n", o - go->mark + 1);
                    721:                                if (o - go->mark + 1 > c->entries) {
                    722:                                        struct node *t;
                    723:                                        unsigned int i;
                    724:
                    725:                                        c->entries = o - go->mark + 1;
                    726:                                        i = 0;
                    727:                                        c->t[i++] = go;
                    728:                                        for (t = n; t != go; t = t->from)
                    729:                                                c->t[i++] = t;
1.1       deraadt   730:                                }
1.5       espie     731:                        }
1.1       deraadt   732:
1.5       espie     733:                /* No arc left: backtrack.  */
                    734:                } else {
                    735:                        n->mark = min;
                    736:                        n = n->from;
                    737:                        if (!n)
                    738:                                return max;
1.25      jasper    739:                        o--;
1.5       espie     740:                }
1.1       deraadt   741:        }
                    742: }
                    743:
1.5       espie     744: static void
1.14      espie     745: print_cycle(struct array *c)
1.5       espie     746: {
                    747:        unsigned int    i;
                    748:
                    749:        /* Printing in reverse order, since cycle discoveries finds reverse
                    750:         * edges.  */
                    751:        for (i = c->entries; i != 0;) {
                    752:                i--;
                    753:                warnx("%s", c->t[i]->k);
                    754:        }
1.1       deraadt   755: }
                    756:
1.5       espie     757: static struct node *
1.14      espie     758: find_longest_cycle(struct array *h, struct array *c)
1.5       espie     759: {
                    760:        unsigned int    i;
                    761:        unsigned int    o;
                    762:        unsigned int    best;
                    763:        struct node     *n;
                    764:        static int      notfirst = 0;
                    765:
                    766:        assert(h->entries != 0);
                    767:
                    768:        /* No cycle found yet.  */
                    769:        c->entries = 0;
                    770:
                    771:        /* Reset the set of marks, except the first time around.  */
                    772:        if (notfirst) {
1.15      espie     773:                for (i = 0; i < h->entries; i++)
1.5       espie     774:                        h->t[i]->mark = 0;
                    775:        } else
                    776:                notfirst = 1;
                    777:
                    778:        o = 0;
                    779:
                    780:        /* Traverse the array.  Each unmarked, live node heralds a
                    781:         * new set of strongly connected components.  */
                    782:        for (i = 0; i < h->entries; i++) {
                    783:                n = h->t[i];
                    784:                if (n->refs != 0 && n->mark == 0) {
                    785:                        /* Each call to traverse_node uses a separate
                    786:                         * interval of numbers to mark nodes.  */
                    787:                        o++;
                    788:                        o = traverse_node(n, o, c);
                    789:                }
                    790:        }
1.25      jasper    791:
1.5       espie     792:        assert(c->entries != 0);
                    793:        n = c->t[0];
                    794:        best = n->refs;
                    795:        for (i = 0; i < c->entries; i++) {
                    796:                if (c->t[i]->refs < best) {
                    797:                        n = c->t[i];
                    798:                        best = n->refs;
                    799:                }
                    800:        }
                    801:        return n;
                    802: }
1.1       deraadt   803:
1.29    ! espie     804: static struct node *
        !           805: find_normal_cycle(struct array *h, struct array *c)
        !           806: {
        !           807:        struct node *b, *n;
        !           808:
        !           809:        if (hints_flag)
        !           810:                n = find_smallest_node(h);
        !           811:        else
        !           812:                n = find_good_cycle_break(h);
        !           813:        while ((b = find_cycle_from(n, c)) == NULL)
        !           814:                n = find_predecessor(h, n);
        !           815:        return b;
        !           816: }
        !           817:
1.5       espie     818: 
                    819: #define plural(n) ((n) > 1 ? "s" : "")
1.1       deraadt   820:
1.29    ! espie     821: static void
        !           822: parse_args(int argc, char *argv[], struct ohash *pairs)
1.5       espie     823: {
1.29    ! espie     824:        int c;
1.7       espie     825:        unsigned int    order;
1.29    ! espie     826:        int reverse_flag;
1.7       espie     827:
1.8       espie     828:        order = 0;
1.5       espie     829:
1.15      espie     830:        reverse_flag = quiet_flag = long_flag =
1.5       espie     831:                warn_flag = hints_flag = verbose_flag = 0;
1.29    ! espie     832:        nodes_init(pairs);
        !           833:        while ((c = getopt(argc, argv, "h:flqrvw")) != -1) {
        !           834:                switch(c) {
        !           835:                case 'h': {
        !           836:                        FILE *f;
        !           837:
        !           838:                        f = fopen(optarg, "r");
        !           839:                        if (f == NULL)
        !           840:                                err(EX_NOINPUT, "Can't open hint file %s",
        !           841:                                    optarg);
        !           842:                        order = read_hints(f, pairs, quiet_flag,
        !           843:                            optarg, order);
        !           844:                        fclose(f);
        !           845:                }
        !           846:                        hints_flag = 1;
        !           847:                        break;
        !           848:                        /*FALLTHRU*/
        !           849:                case 'f':
        !           850:                        hints_flag = 2;
        !           851:                        break;
        !           852:                case 'l':
        !           853:                        long_flag = 1;
        !           854:                        break;
        !           855:                case 'q':
        !           856:                        quiet_flag = 1;
        !           857:                        break;
        !           858:                case 'r':
        !           859:                        reverse_flag = 1;
        !           860:                        break;
        !           861:                case 'v':
        !           862:                        verbose_flag = 1;
        !           863:                        break;
        !           864:                case 'w':
        !           865:                        warn_flag = 1;
        !           866:                        break;
        !           867:                default:
        !           868:                        usage();
        !           869:                }
        !           870:        }
1.1       deraadt   871:
1.29    ! espie     872:        argc -= optind;
        !           873:        argv += optind;
1.1       deraadt   874:
1.5       espie     875:        switch(argc) {
                    876:        case 1: {
                    877:                FILE *f;
                    878:
                    879:                f = fopen(argv[0], "r");
                    880:                if (f == NULL)
1.27      espie     881:                        err(EX_NOINPUT, "Can't open file %s", argv[0]);
1.29    ! espie     882:                order = read_pairs(f, pairs, reverse_flag, argv[0], order,
1.8       espie     883:                    hints_flag == 2);
1.5       espie     884:                fclose(f);
                    885:                break;
                    886:        }
                    887:        case 0:
1.29    ! espie     888:                order = read_pairs(stdin, pairs, reverse_flag, "stdin",
1.8       espie     889:                    order, hints_flag == 2);
1.5       espie     890:                break;
                    891:        default:
                    892:                usage();
                    893:        }
1.29    ! espie     894: }
1.1       deraadt   895:
1.29    ! espie     896: static int
        !           897: tsort(struct ohash *pairs)
        !           898: {
1.5       espie     899:            struct array        aux;    /* Unrefed nodes/cycle reporting.  */
                    900:            struct array        remaining;
                    901:            unsigned int        broken_arcs, broken_cycles;
                    902:            unsigned int        left;
                    903:
                    904:            broken_arcs = 0;
                    905:            broken_cycles = 0;
                    906:
1.8       espie     907:            if (hints_flag)
1.29    ! espie     908:                    make_transparent(pairs);
        !           909:            split_nodes(pairs, &aux, &remaining);
        !           910:            ohash_delete(pairs);
1.5       espie     911:
                    912:            if (hints_flag)
1.6       espie     913:                    heapify(&aux, verbose_flag);
1.5       espie     914:
                    915:            left = remaining.entries + aux.entries;
                    916:            while (left != 0) {
                    917:
                    918:                    /* Standard topological sort.  */
                    919:                    while (aux.entries) {
                    920:                            struct link *l;
                    921:                            struct node *n;
                    922:
                    923:                            n = DEQUEUE(&aux);
                    924:                            printf("%s\n", n->k);
                    925:                            left--;
                    926:                            /* We can't free nodes, as we don't know which
                    927:                             * entry we can remove in the hash table.  We
1.15      espie     928:                             * rely on refs == 0 to recognize live nodes.
1.5       espie     929:                             * Decrease ref count of live nodes, enter new
                    930:                             * candidates into the unrefed list.  */
1.15      espie     931:                            for (l = n->arcs; l != NULL; l = l->next)
                    932:                                    if (l->node->refs != 0 &&
1.5       espie     933:                                        --l->node->refs == 0) {
                    934:                                            ENQUEUE(&aux, l->node);
                    935:                                    }
                    936:                    }
                    937:                    /* There are still cycles to break.  */
                    938:                    if (left != 0) {
                    939:                            struct node *n;
                    940:
                    941:                            broken_cycles++;
                    942:                            /* XXX Simple cycle detection and long cycle
                    943:                             * detection are mutually exclusive.  */
                    944:
1.29    ! espie     945:                            if (long_flag)
1.5       espie     946:                                    n = find_longest_cycle(&remaining, &aux);
1.29    ! espie     947:                            else
        !           948:                                    n = find_normal_cycle(&remaining, &aux);
1.5       espie     949:
                    950:                            if (!quiet_flag) {
                    951:                                    warnx("cycle in data");
                    952:                                    print_cycle(&aux);
                    953:                            }
                    954:
                    955:                            if (verbose_flag)
                    956:                                    warnx("%u edge%s broken", n->refs,
                    957:                                        plural(n->refs));
                    958:                            broken_arcs += n->refs;
                    959:                            n->refs = 0;
                    960:                            /* Reinitialization, cycle reporting uses aux.  */
                    961:                            aux.t[0] = n;
                    962:                            aux.entries = 1;
                    963:                    }
                    964:            }
                    965:            if (verbose_flag && broken_cycles != 0)
                    966:                    warnx("%u cycle%s broken, for a total of %u edge%s",
                    967:                        broken_cycles, plural(broken_cycles),
                    968:                        broken_arcs, plural(broken_arcs));
1.15      espie     969:            if (warn_flag)
1.29    ! espie     970:                    return (broken_cycles < 256 ? broken_cycles : 255);
1.5       espie     971:            else
1.29    ! espie     972:                    return (EX_OK);
        !           973: }
        !           974:
        !           975: int
        !           976: main(int argc, char *argv[])
        !           977: {
        !           978:        struct ohash    pairs;
        !           979:
        !           980:        parse_args(argc, argv, &pairs);
        !           981:        return tsort(&pairs);
1.1       deraadt   982: }
                    983:
1.5       espie     984:
                    985: extern char *__progname;
                    986:
                    987: static void
1.16      deraadt   988: usage(void)
1.1       deraadt   989: {
1.18      espie     990:        fprintf(stderr, "Usage: %s [-flqrvw] [-h file] [file]\n", __progname);
1.5       espie     991:        exit(EX_USAGE);
1.1       deraadt   992: }