blob: 71665915ff54d601818ac524826fedfce7a4a0f0 [file] [log] [blame]
H. Peter Anvinea6e34d2002-04-30 20:51:32 +00001/* 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
H. Peter Anvind7ed89e2002-04-30 20:52:08 +000016/*
17 * This lot manages the current set of sync points by means of a
18 * heap (priority queue) structure.
19 */
20
H. Peter Anvinea6e34d2002-04-30 20:51:32 +000021static struct Sync {
22 unsigned long pos;
23 unsigned long length;
H. Peter Anvind7ed89e2002-04-30 20:52:08 +000024} synx[SYNC_MAX+1]; /* synx[0] never used - who cares :) */
H. Peter Anvinea6e34d2002-04-30 20:51:32 +000025static int nsynx;
26
27void init_sync(void) {
28 nsynx = 0;
29}
30
31void add_sync(unsigned long pos, unsigned long length) {
32 int i;
33
34 if (nsynx == SYNC_MAX)
35 return; /* can't do anything - overflow */
36
37 nsynx++;
38 synx[nsynx].pos = pos;
39 synx[nsynx].length = length;
40
41 for (i = nsynx; i > 1; i /= 2) {
42 if (synx[i/2].pos > synx[i].pos) {
43 struct Sync t;
44 t = synx[i/2]; /* structure copy */
45 synx[i/2] = synx[i]; /* structure copy again */
46 synx[i] = t; /* another structure copy */
47 }
48 }
49}
50
51unsigned long next_sync(unsigned long position, unsigned long *length) {
52 while (nsynx > 0 && synx[1].pos + synx[1].length <= position) {
53 int i, j;
54 struct Sync t;
55 t = synx[nsynx]; /* structure copy */
56 synx[nsynx] = synx[1]; /* structure copy */
57 synx[1] = t; /* ditto */
58
59 nsynx--;
60
61 i = 1;
62 while (i*2 <= nsynx) {
63 j = i*2;
64 if (synx[j].pos < synx[i].pos &&
65 (j+1 > nsynx || synx[j+1].pos > synx[j].pos)) {
66 t = synx[j]; /* structure copy */
67 synx[j] = synx[i]; /* lots of these... */
68 synx[i] = t; /* ...aren't there? */
69 i = j;
70 } else if (j+1 <= nsynx && synx[j+1].pos < synx[i].pos) {
71 t = synx[j+1]; /* structure copy */
72 synx[j+1] = synx[i]; /* structure <yawn> copy */
73 synx[i] = t; /* structure copy <zzzz....> */
74 i = j+1;
75 } else
76 break;
77 }
78 }
79
80 if (nsynx > 0) {
81 if (length)
82 *length = synx[1].length;
83 return synx[1].pos;
84 } else {
85 if (length)
86 *length = 0L;
87 return ULONG_MAX;
88 }
89}