H. Peter Anvin | ea6e34d | 2002-04-30 20:51:32 +0000 | [diff] [blame^] | 1 | /* sync.c the Netwide Disassembler synchronisation processing module |
| 2 | * |
| 3 | * The Netwide Assembler is copyright (C) 1996 Simon Tatham and |
| 4 | * Julian Hall. All rights reserved. The software is |
| 5 | * redistributable under the licence given in the file "Licence" |
| 6 | * distributed in the NASM archive. |
| 7 | */ |
| 8 | |
| 9 | #include <stdio.h> |
| 10 | #include <limits.h> |
| 11 | |
| 12 | #include "sync.h" |
| 13 | |
| 14 | #define SYNC_MAX 4096 /* max # of sync points */ |
| 15 | |
| 16 | static struct Sync { |
| 17 | unsigned long pos; |
| 18 | unsigned long length; |
| 19 | } synx[SYNC_MAX]; |
| 20 | static int nsynx; |
| 21 | |
| 22 | void init_sync(void) { |
| 23 | nsynx = 0; |
| 24 | } |
| 25 | |
| 26 | void add_sync(unsigned long pos, unsigned long length) { |
| 27 | int i; |
| 28 | |
| 29 | if (nsynx == SYNC_MAX) |
| 30 | return; /* can't do anything - overflow */ |
| 31 | |
| 32 | nsynx++; |
| 33 | synx[nsynx].pos = pos; |
| 34 | synx[nsynx].length = length; |
| 35 | |
| 36 | for (i = nsynx; i > 1; i /= 2) { |
| 37 | if (synx[i/2].pos > synx[i].pos) { |
| 38 | struct Sync t; |
| 39 | t = synx[i/2]; /* structure copy */ |
| 40 | synx[i/2] = synx[i]; /* structure copy again */ |
| 41 | synx[i] = t; /* another structure copy */ |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | unsigned long next_sync(unsigned long position, unsigned long *length) { |
| 47 | while (nsynx > 0 && synx[1].pos + synx[1].length <= position) { |
| 48 | int i, j; |
| 49 | struct Sync t; |
| 50 | t = synx[nsynx]; /* structure copy */ |
| 51 | synx[nsynx] = synx[1]; /* structure copy */ |
| 52 | synx[1] = t; /* ditto */ |
| 53 | |
| 54 | nsynx--; |
| 55 | |
| 56 | i = 1; |
| 57 | while (i*2 <= nsynx) { |
| 58 | j = i*2; |
| 59 | if (synx[j].pos < synx[i].pos && |
| 60 | (j+1 > nsynx || synx[j+1].pos > synx[j].pos)) { |
| 61 | t = synx[j]; /* structure copy */ |
| 62 | synx[j] = synx[i]; /* lots of these... */ |
| 63 | synx[i] = t; /* ...aren't there? */ |
| 64 | i = j; |
| 65 | } else if (j+1 <= nsynx && synx[j+1].pos < synx[i].pos) { |
| 66 | t = synx[j+1]; /* structure copy */ |
| 67 | synx[j+1] = synx[i]; /* structure <yawn> copy */ |
| 68 | synx[i] = t; /* structure copy <zzzz....> */ |
| 69 | i = j+1; |
| 70 | } else |
| 71 | break; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | if (nsynx > 0) { |
| 76 | if (length) |
| 77 | *length = synx[1].length; |
| 78 | return synx[1].pos; |
| 79 | } else { |
| 80 | if (length) |
| 81 | *length = 0L; |
| 82 | return ULONG_MAX; |
| 83 | } |
| 84 | } |