aboutsummaryrefslogtreecommitdiffgithub
path: root/novice/simulator/loaders/complx.ts
blob: 51a33a958bd4c04a27fe216caa66dda0a4032ef4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import { Buffer } from 'buffer';
import { Readable } from 'stream';
import { Isa, SymbTable } from '../../isa';
import { Memory } from '../mem';
import { Loader } from './loader';

type State = 'addr'|'len'|'words';

class ComplxObjectFileLoader implements Loader {
    public async load(isa: Isa, fp: Readable, mem: Memory): Promise<void> {
        const wordBytes = Math.ceil(isa.mem.word / 8);
        const excessBuf = Buffer.alloc(wordBytes);
        let excessLen = 0;
        let pc = 0;
        let wordsLeft = 0;

        let state: State = 'addr';

        while (true) {
            const buf = fp.read();

            if (!buf) {
                break;
            }

            if (buf.length + excessLen < wordBytes) {
                for (const byte of buf) {
                    excessBuf[excessLen++] = byte;
                }
                continue;
            }

            const excess = (excessLen + buf.length) % wordBytes;
            const words = (excessLen + buf.length - excess) / wordBytes;

            for (let i = 0; i < words; i++) {
                let word = 0;

                for (let j = 0; j < wordBytes; j++) {
                    const idx = i * wordBytes + j;
                    const byte = (idx < excessLen) ? excessBuf[idx]
                                                   : buf[idx - excessLen];
                    word |= byte << (8 * (wordBytes - j - 1));
                }

                switch (state) {
                    case 'addr':
                        pc = word;
                        state = 'len';
                        break;

                    case 'len':
                        if (word) {
                            wordsLeft = word;
                            state = 'words';
                        } else {
                            // If we don't expect any words, go ahead
                            // and skip to the next section
                            state = 'addr';
                        }
                        break;

                    case 'words':
                        mem.store(pc, word);
                        pc += Math.ceil(isa.mem.word / isa.mem.addressability);

                        if (!--wordsLeft) {
                            state = 'addr';
                        }
                        break;
                }
            }

            for (let i = 0; i < excess; i++) {
                excessBuf[i] = buf[buf.length - excess + i];
            }
            excessLen = excess;
        }

        if (excessLen) {
            throw new Error(`number of bytes in object file is not ` +
                            `divisible by ${wordBytes}`);
        }
        if (state === 'len') {
            throw new Error('unexpected end-of-file before section length');
        }
        if (state === 'words') {
            throw new Error(`expected ${wordsLeft} more words`);
        }
    }

    public fileExt(): string {
        return 'obj';
    }

    public symbFileExt(): string {
        return 'sym';
    }

    public async loadSymb(fp: Readable, symbtable: SymbTable): Promise<void> {
        // If you have any lines this long, I'm praying for your entire
        // family
        const buf = Buffer.alloc(1024);
        let size = 0;
        let lines = 1;
        let err: Error|null = null;

        const endPromise = new Promise<void>(resolve => {
            fp.on('end', resolve);
        });

        fp.on('data', recvBuf => {
            if (err) {
                return;
            }

            let start = 0;
            for (let i = 0; i < recvBuf.length; i++) {
                // hooray! we have a newline so this is a whole line.
                // let's copy it to the buffer so we can decode it
                if (recvBuf[i] === '\n'.charCodeAt(0)) {
                    const totalLen = size + i - start + 1;
                    if (totalLen > buf.length) {
                        err = new Error(`line of ${totalLen} bytes exceeds ` +
                                        `maximum length of ${buf.length} on ` +
                                        `line ${lines}`);
                        return;
                    }

                    recvBuf.copy(buf, size, start, i + 1);

                    try {
                        this.parseLine(buf.slice(0, totalLen).toString(),
                                       lines, symbtable);
                    } catch (e) {
                        err = e;
                        return;
                    }

                    // Empty buffer
                    size = 0;
                    start = i + 1;
                    lines++;
                }
            }

            // Copy excess
            if (start < recvBuf.length) {
                const totalLen = size + recvBuf.length - start;

                if (totalLen > buf.length) {
                    err = new Error(`line of >=${totalLen} bytes exceeds ` +
                                    `maximum length of ${buf.length} on ` +
                                    `line ${lines}`);
                }
                recvBuf.copy(buf, 0, start, recvBuf.length);
                size = totalLen;
            }
        });

        await endPromise;

        if (err) {
            throw err;
        }

        if (size > 0) {
            this.parseLine(buf.slice(0, size).toString(), lines, symbtable);
            size = 0;
        }
    }

    private parseLine(line: string, lines: number, symbtable: SymbTable) {
        line = line.trim();

        // Ignore empty lines
        if (!line) {
            return;
        }

        const splat = line.split('\t');

        if (splat.length !== 2) {
            throw new Error(`found ${splat.length - 1} tabs instead of 1 ` +
                            `on line ${lines}`);
        }

        const [hexAddr, sym] = splat;
        const addr = parseInt(hexAddr, 16);

        if (addr < 0) {
            throw new Error(`negative address \`${hexAddr}' on line ${lines}`);
        }

        if (isNaN(addr)) {
            throw new Error(`invalid address \`${hexAddr}' on line ${lines}`);
        }

        if (sym in symbtable) {
            throw new Error(`duplicate symbol \`${sym}' on line ${lines}`);
        }

        symbtable[sym] = addr;
    }
}

export { ComplxObjectFileLoader };