summaryrefslogtreecommitdiff
path: root/lib/sqfs/write_table.c
blob: 8d20a7461a92821258cde44047687aa6707dcb9d (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
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * write_table.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#define SQFS_BUILDING_DLL
#include "config.h"

#include "sqfs/meta_writer.h"
#include "sqfs/error.h"
#include "sqfs/super.h"
#include "sqfs/table.h"
#include "sqfs/data.h"
#include "sqfs/io.h"
#include "util.h"

#include <endian.h>
#include <stdlib.h>

int sqfs_write_table(sqfs_file_t *file, sqfs_compressor_t *cmp,
		     const void *data, size_t table_size, uint64_t *start)
{
	size_t block_count, list_size, diff, blkidx = 0;
	uint64_t off, *locations;
	sqfs_meta_writer_t *m;
	int ret;

	block_count = table_size / SQFS_META_BLOCK_SIZE;
	if ((table_size % SQFS_META_BLOCK_SIZE) != 0)
		++block_count;

	locations = alloc_array(sizeof(uint64_t), block_count);

	if (locations == NULL)
		return SQFS_ERROR_ALLOC;

	/* Write actual data */
	m = sqfs_meta_writer_create(file, cmp, false);
	if (m == NULL) {
		ret = SQFS_ERROR_ALLOC;
		goto out_idx;
	}

	while (table_size > 0) {
		locations[blkidx++] = htole64(file->get_size(file));

		diff = SQFS_META_BLOCK_SIZE;
		if (diff > table_size)
			diff = table_size;

		ret = sqfs_meta_writer_append(m, data, diff);
		if (ret)
			goto out;

		data = (const char *)data + diff;
		table_size -= diff;
	}

	ret = sqfs_meta_writer_flush(m);
	if (ret)
		goto out;

	/* write location list */
	*start = file->get_size(file);

	list_size = sizeof(uint64_t) * block_count;

	off = file->get_size(file);

	ret = file->write_at(file, off, locations, list_size);
	if (ret)
		goto out;

	/* cleanup */
	ret = 0;
out:
	sqfs_meta_writer_destroy(m);
out_idx:
	free(locations);
	return ret;
}