-
Notifications
You must be signed in to change notification settings - Fork 13
/
tape-image.c
126 lines (108 loc) · 2.66 KB
/
tape-image.c
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
/* Copyright (C) 2022 Lars Brinkhoff <lars@nocrew.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stdlib.h>
#include "tape-image.h"
static int big_endian = 0;
static void
read_octets (uint8_t *buffer, int n)
{
int c, i;
for (i = 0; i < n; i++)
{
c = getchar ();
if (c == EOF)
{
printf ("Error reading tape image\n");
exit (1);
}
*buffer++ = c;
}
}
static uint32_t
swap (uint32_t x)
{
return ((x >> 24) & 0x000000FF) |
((x >> 8) & 0x0000FF00) |
((x << 8) & 0x00FF0000) |
((x << 24) & 0xFF000000);
}
static uint32_t
read_16bits_l (uint8_t *start)
{
return start[0] | (start[1] << 8);
}
static uint32_t
read_32bits_l (uint8_t *start)
{
return read_16bits_l (start) | (read_16bits_l (start + 2) << 16);
}
static uint32_t
read_reclen (uint8_t *start)
{
uint32_t x;
x = read_32bits_l (start);
if (big_endian)
x = swap (x);
return x;
}
uint32_t
read_record (FILE *f, uint8_t *buffer, uint32_t n)
{
uint8_t size[5];
uint32_t len, len2;
read_octets (size, 4);
len = read_reclen (size);
if (len == 0)
return len;
if (len == 0xFFFFFFFF)
return len;
if ((len >> 24) == 0x80)
return len;
if (len > 100000)
{
len = swap (len);
big_endian = !big_endian;
}
if ((len & 0x80000000) != 0)
return len;
if (len > 100000)
{
printf ("Bad record size: %u %x\n", len, len);
exit (1);
}
if (len > 0)
{
if (len > n)
{
printf ("Buffer too small.\n");
exit (1);
}
read_octets (buffer, len);
read_octets (size, 4);
len2 = read_reclen (size);
if (len != len2)
{
if (len & 1) {
read_octets (size + 4, 1);
len2 = read_reclen (size + 1);
}
if (len != len2)
{
printf ("Size mismatch\n");
printf ("Record size: %u %x\n", len, len);
printf ("Second size: %u %x\n", len2, len2);
exit (1);
}
}
}
return len;
}