summaryrefslogtreecommitdiffstatshomepage
path: root/src/tools/imgtool/stream.cpp
blob: 014d57355141fa0ec9fa3df1f2d27b1e84850374 (plain) (blame)
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
// license:BSD-3-Clause
// copyright-holders:Nathan Woods
/***************************************************************************

    stream.cpp

    Code for implementing Imgtool streams

***************************************************************************/

#include "stream.h"

#include "imgtool.h"

#include "corefile.h"
#include "ioprocs.h"
#include "unzip.h"

#include <cassert>
#include <cstdio>
#include <cstring>

#include <zlib.h> // for crc32


namespace imgtool {

namespace {

class stream_read_wrapper : public virtual util::random_read
{
public:
	stream_read_wrapper(stream::ptr &&stream, std::uint8_t filler) noexcept
		: m_stream(stream.release())
		, m_filler(filler)
		, m_close(true)
	{
		assert(m_stream);
	}

	stream_read_wrapper(stream &stream, std::uint8_t filler) noexcept
		: m_stream(&stream)
		, m_filler(filler)
		, m_close(false)
	{
	}

	virtual ~stream_read_wrapper()
	{
		if (m_close)
			delete m_stream;
	}

	virtual std::error_condition seek(std::int64_t offset, int whence) noexcept override
	{
		m_stream->seek(offset, whence);
		return std::error_condition();
	}

	virtual std::error_condition tell(std::uint64_t &result) noexcept override
	{
		result = m_stream->tell();
		return std::error_condition();
	}

	virtual std::error_condition length(std::uint64_t &result) noexcept override
	{
		result = m_stream->size();
		return std::error_condition();
	}

	virtual std::error_condition read(void *buffer, std::size_t length, std::size_t &actual) noexcept override
	{
		actual = m_stream->read(buffer, length);
		if (actual < length)
			std::memset(reinterpret_cast<std::uint8_t *>(buffer) + actual, m_filler, length - actual);
		return std::error_condition();
	}

	virtual std::error_condition read_at(std::uint64_t offset, void *buffer, std::size_t length, std::size_t &actual) noexcept override
	{
		std::uint64_t const pos = m_stream->tell();
		m_stream->seek(offset, SEEK_SET);
		actual = m_stream->read(buffer, length);
		m_stream->seek(pos, SEEK_SET);
		if (actual < length)
			std::memset(reinterpret_cast<std::uint8_t *>(buffer) + actual, m_filler, length - actual);
		return std::error_condition();
	}

protected:
	stream *const m_stream;
	std::uint8_t m_filler;
	bool const m_close;
};


class stream_read_write_wrapper : public stream_read_wrapper, public util::random_read_write
{
public:
	using stream_read_wrapper::stream_read_wrapper;

	virtual std::error_condition finalize() noexcept override
	{
		return std::error_condition();
	}

	virtual std::error_condition flush() noexcept override
	{
		return std::error_condition();
	}

	virtual std::error_condition write(void const *buffer, std::size_t length, std::size_t &actual) noexcept override
	{
		std::uint64_t const pos = m_stream->tell();
		std::uint64_t size = m_stream->size();
		if (size < pos)
		{
			m_stream->seek(size, SEEK_SET);
			size += m_stream->fill(m_filler, pos - size);
		}
		actual = (size >= pos) ? m_stream->write(buffer, length) : 0U;
		return (actual == length) ? std::error_condition() : std::errc::io_error;
	}

	virtual std::error_condition write_at(std::uint64_t offset, void const *buffer, std::size_t length, std::size_t &actual) noexcept override
	{
		std::uint64_t const pos = m_stream->tell();
		std::uint64_t size = m_stream->size();
		if (offset > size)
		{
			m_stream->seek(size, SEEK_SET);
			size += m_stream->fill(m_filler, offset - size);
		}
		else
		{
			m_stream->seek(offset, SEEK_SET);
		}
		actual = (size >= offset) ? m_stream->write(buffer, length) : 0U;
		m_stream->seek(pos, SEEK_SET);
		return (actual == length) ? std::error_condition() : std::errc::io_error;
	}
};

} // anonymous namespace


util::random_read::ptr stream_read(stream::ptr &&s, std::uint8_t filler) noexcept
{
	util::random_read::ptr result;
	if (s)
		result.reset(new (std::nothrow) stream_read_wrapper(std::move(s), filler));
	return result;
}

util::random_read::ptr stream_read(stream &s, std::uint8_t filler) noexcept
{
	util::random_read::ptr result(new (std::nothrow) stream_read_wrapper(s, filler));
	return result;
}

util::random_read_write::ptr stream_read_write(stream::ptr &&s, std::uint8_t filler) noexcept
{
	util::random_read_write::ptr result;
	if (s)
		result.reset(new (std::nothrow) stream_read_write_wrapper(std::move(s), filler));
	return result;
}

util::random_read_write::ptr stream_read_write(stream &s, std::uint8_t filler) noexcept
{
	util::random_read_write::ptr result(new (std::nothrow) stream_read_write_wrapper(s, filler));
	return result;
}



//-------------------------------------------------
//  ctor
//-------------------------------------------------

stream::stream(bool wp)
	: imgtype(IMG_FILE)
	, write_protect(wp)
	, position(0)
	, filesize(0)
	, file()
	, buffer(nullptr)
{
}


//-------------------------------------------------
//  ctor
//-------------------------------------------------

stream::stream(bool wp, util::core_file::ptr &&f)
	: imgtype(IMG_FILE)
	, write_protect(wp)
	, position(0)
	, filesize(0)
	, file(std::move(f))
	, buffer(nullptr)
{
	file->length(filesize); // FIXME: check error return
}


//-------------------------------------------------
//  ctor
//-------------------------------------------------

stream::stream(bool wp, std::size_t size)
	: imgtype(IMG_MEM)
	, write_protect(wp)
	, position(0)
	, filesize(size)
	, file()
	, buffer(reinterpret_cast<std::uint8_t *>(malloc(size)))
{
}


//-------------------------------------------------
//  ctor
//-------------------------------------------------

stream::stream(bool wp, std::size_t size, void *buf)
	: imgtype(IMG_MEM)
	, write_protect(wp)
	, position(0)
	, filesize(size)
	, file()
	, buffer(reinterpret_cast<std::uint8_t *>(buf))
{
}


//-------------------------------------------------
//  dtor
//-------------------------------------------------

stream::~stream()
{
	if (buffer)
		free(buffer);
}


//-------------------------------------------------
//  open_zip
//-------------------------------------------------

stream::ptr stream::open_zip(const std::string &zipname, const char *subname, int read_or_write)
{
	if (read_or_write)
		return stream::ptr();

	/* check to see if the file exists */
	FILE *f = fopen(zipname.c_str(), "r");
	if (!f)
		return stream::ptr();
	fclose(f);

	stream::ptr imgfile(new stream(true));

	imgfile->imgtype = IMG_MEM;

	util::archive_file::ptr z;
	util::archive_file::open_zip(zipname, z);
	if (!z)
		return stream::ptr();

	int zipent = z->first_file();
	while ((zipent >= 0) && subname && strcmp(subname, z->current_name().c_str()))
		zipent = z->next_file();
	if (zipent < 0)
		return stream::ptr();

	imgfile->filesize = z->current_uncompressed_length();
	imgfile->buffer = reinterpret_cast<std::uint8_t *>(malloc(z->current_uncompressed_length()));
	if (!imgfile->buffer)
		return stream::ptr();

	if (z->decompress(imgfile->buffer, z->current_uncompressed_length()))
		return stream::ptr();

	return imgfile;
}



//-------------------------------------------------
//  open
//-------------------------------------------------

stream::ptr stream::open(const std::string &filename, int read_or_write)
{
	static const uint32_t write_modes[] =
	{
		OPEN_FLAG_READ,
		OPEN_FLAG_WRITE | OPEN_FLAG_CREATE,
		OPEN_FLAG_READ | OPEN_FLAG_WRITE,
		OPEN_FLAG_READ | OPEN_FLAG_WRITE | OPEN_FLAG_CREATE
	};
	stream::ptr s;
	char c;

	// maybe we are just a ZIP?
	if (core_filename_ends_with(filename, ".zip"))
		return open_zip(filename, nullptr, read_or_write);

	util::core_file::ptr f = nullptr;
	auto const filerr = util::core_file::open(filename, write_modes[read_or_write], f);
	if (filerr)
	{
		if (!read_or_write)
		{
			int const len = filename.size();

			// can't open the file; try opening ZIP files with other names
			std::vector<char> buf(len + 1);
			strcpy(&buf[0], filename.c_str());

			for (int i = len-1; !s && (i >= 0); i--)
			{
				if ((buf[i] == '\\') || (buf[i] == '/'))
				{
					c = buf[i];
					buf[i] = '\0';
					s = open_zip(&buf[0], &buf[i + 1], read_or_write);
					buf[i] = c;
				}
			}

			if (s)
				return s;
		}

		// ah well, it was worth a shot
		return stream::ptr();
	}

	stream::ptr imgfile(new stream(read_or_write ? false : true, std::move(f)));

	// normal file
	return imgfile;
}


//-------------------------------------------------
//  open_write_stream
//-------------------------------------------------

stream::ptr stream::open_write_stream(int size)
{
	stream::ptr imgfile(new stream(false, size));
	if (!imgfile->buffer)
		return stream::ptr();

	return imgfile;
}


//-------------------------------------------------
//  open_mem
//-------------------------------------------------

stream::ptr stream::open_mem(void *buf, size_t sz)
{
	stream::ptr imgfile(new stream(false, sz, buf));

	return imgfile;
}


//-------------------------------------------------
//  core_file
//-------------------------------------------------

util::core_file *stream::core_file()
{
	return (imgtype == IMG_FILE) ? file.get() : nullptr;
}


//-------------------------------------------------
//  read
//-------------------------------------------------

uint32_t stream::read(void *buf, uint32_t sz)
{
	size_t result = 0;

	switch(imgtype)
	{
		case IMG_FILE:
			if (!file->seek(position, SEEK_SET))
				file->read(buf, sz, result); // FIXME: check error return
			break;

		case IMG_MEM:
			// do we have to limit sz?
			if (sz > (filesize - position))
				sz = uint32_t(filesize - position);

			memcpy(buf, buffer + position, sz);
			result = sz;
			break;

		default:
			assert(0);
			break;
	}
	position += result;
	return result;
}


//-------------------------------------------------
//  write
//-------------------------------------------------

uint32_t stream::write(const void *buf, uint32_t sz)
{
	size_t result = 0;

	switch(imgtype)
	{
		case IMG_MEM:
			if (!write_protect)
			{
				// do we have to expand the buffer?
				const uint64_t end = position + sz;
				if ((filesize < end) && (size_t(end) == end))
				{
					// try to expand the buffer
					void *const new_buffer = realloc(buffer, size_t(end));
					if (new_buffer)
					{
						buffer = reinterpret_cast<uint8_t *>(new_buffer);
						filesize = end;
					}
				}

				// do we have to limit sz?
				if (sz > (filesize - position))
					sz = uint32_t(filesize - position);

				memcpy(buffer + position, buf, sz);
				result = sz;
			}
			break;

		case IMG_FILE:
			if (!file->seek(position, SEEK_SET))
				file->write(buf, sz, result); // FIXME: check error return
			break;

		default:
			assert(0);
			break;
	}

	// advance the file pointer
	position += result;

	// did we grow the file
	if (position > filesize)
		filesize = position;
	return result;
}


//-------------------------------------------------
//  size
//-------------------------------------------------

uint64_t stream::size() const
{
	return filesize;
}


//-------------------------------------------------
//  getptr
//-------------------------------------------------

void *stream::getptr()
{
	void *ptr;

	switch(imgtype)
	{
		case IMG_MEM:
			ptr = buffer;
			break;

		default:
			ptr = nullptr;
			break;
	}
	return ptr;
}


//-------------------------------------------------
//  seek
//-------------------------------------------------

int stream::seek(int64_t pos, int where)
{
	switch(where)
	{
		case SEEK_CUR:
			pos += position;
			break;
		case SEEK_END:
			pos += size();
			break;
	}

	if (pos < 0)
		position = 0;
	else
		position = std::min(size(), uint64_t(pos));

	if (position < pos)
		fill('\0', pos - position);

	return 0;
}


//-------------------------------------------------
//  tell
//-------------------------------------------------

uint64_t stream::tell()
{
	return position;
}


//-------------------------------------------------
//  transfer
//-------------------------------------------------

uint64_t stream::transfer(stream &dest, stream &source, uint64_t sz)
{
	uint64_t result = 0;
	uint64_t readsz;
	char buf[1024];

	while(sz && (readsz = source.read(buf, std::min(sz, uint64_t(sizeof(buf))))))
	{
		dest.write(buf, readsz);
		sz -= readsz;
		result += readsz;
	}
	return result;
}


//-------------------------------------------------
//  transfer_all
//-------------------------------------------------

uint64_t stream::transfer_all(stream &dest, stream &source)
{
	return transfer(dest, source, source.size());
}


//-------------------------------------------------
//  crc
//-------------------------------------------------

int stream::crc(unsigned long *result)
{
	size_t sz;
	void *ptr;

	switch(imgtype)
	{
		case IMG_MEM:
			*result = crc32(0, (unsigned char *) buffer, (size_t) filesize);
			break;

		default:
			sz = size();
			ptr = malloc(sz);
			if (!ptr)
				return IMGTOOLERR_OUTOFMEMORY;
			seek(0, SEEK_SET);
			if (read(ptr, sz) != sz)
			{
				free(ptr);
				return IMGTOOLERR_READERROR;
			}
			*result = crc32(0, (const Bytef*)ptr, sz);
			free(ptr);
			break;
	}
	return 0;
}


//-------------------------------------------------
//  file_crc
//-------------------------------------------------

int stream::file_crc(const char *fname, unsigned long *result)
{
	int err;
	stream::ptr f;

	f = stream::open(fname, OSD_FOPEN_READ);
	if (!f)
		return IMGTOOLERR_FILENOTFOUND;

	err = f->crc(result);
	return err;
}


//-------------------------------------------------
//  fill
//-------------------------------------------------

uint64_t stream::fill(unsigned char b, uint64_t sz)
{
	uint64_t outsz;
	char buf[1024];

	outsz = 0;
	memset(buf, b, (std::min<uint64_t>)(sz, sizeof(buf)));

	while (sz)
	{
		outsz += write(buf, (std::min<uint64_t>)(sz, sizeof(buf)));
		sz -= (std::min<uint64_t>)(sz, sizeof(buf));
	}
	return outsz;
}


//-------------------------------------------------
//  is_read_only
//-------------------------------------------------

bool stream::is_read_only()
{
	return write_protect;
}


//-------------------------------------------------
//  putc
//-------------------------------------------------

uint32_t stream::putc(char c)
{
	return write(&c, 1);
}


//-------------------------------------------------
//  puts
//-------------------------------------------------

uint32_t stream::puts(const char *s)
{
	return write(s, strlen(s));
}


//-------------------------------------------------
//  printf
//-------------------------------------------------

uint32_t stream::printf(const char *fmt, ...)
{
	va_list va;
	char buf[256];

	va_start(va, fmt);
	vsprintf(buf, fmt, va);
	va_end(va);

	return puts(buf);
}

} // namespace imgtool