2 * Copyright (C) 2015 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #define _LARGEFILE64_SOURCE
25 #include <android-base/file.h>
29 #include <openssl/sha.h>
34 #include <sys/ioctl.h>
36 #ifndef IMAGE_NO_SPARSE
37 #include <sparse/sparse.h>
41 #if defined(__linux__)
43 #elif defined(__APPLE__)
45 #define BLKGETSIZE64 DKIOCGETBLOCKCOUNT
49 void image_init(image *ctx)
51 memset(ctx, 0, sizeof(*ctx));
54 static void mmap_image_free(image *ctx)
57 munmap(ctx->input, (size_t)ctx->inp_size);
61 if (ctx->fec_mmap_addr) {
62 munmap(ctx->fec_mmap_addr, FEC_BLOCKSIZE + ctx->fec_size);
66 if (!ctx->inplace && ctx->output) {
71 static void file_image_free(image *ctx)
73 assert(ctx->input == ctx->output);
84 void image_free(image *ctx)
95 static uint64_t get_size(int fd)
99 if (fstat(fd, &st) == -1) {
100 FATAL("failed to fstat: %s\n", strerror(errno));
105 if (S_ISBLK(st.st_mode)) {
106 if (ioctl(fd, BLKGETSIZE64, &size) == -1) {
107 FATAL("failed to ioctl(BLKGETSIZE64): %s\n", strerror(errno));
109 } else if (S_ISREG(st.st_mode)) {
112 FATAL("unknown file mode: %d\n", (int)st.st_mode);
118 static void calculate_rounds(uint64_t size, image *ctx)
121 FATAL("empty file?\n");
122 } else if (size % FEC_BLOCKSIZE) {
123 FATAL("file size %" PRIu64 " is not a multiple of %u bytes\n",
124 size, FEC_BLOCKSIZE);
127 ctx->inp_size = size;
128 ctx->blocks = fec_div_round_up(ctx->inp_size, FEC_BLOCKSIZE);
129 ctx->rounds = fec_div_round_up(ctx->blocks, ctx->rs_n);
132 static void mmap_image_load(const std::vector<int>& fds, image *ctx,
135 if (fds.size() != 1) {
136 FATAL("multiple input files not supported with mmap\n");
139 int fd = fds.front();
141 calculate_rounds(get_size(fd), ctx);
143 /* check that we can memory map the file; on 32-bit platforms we are
144 limited to encoding at most 4 GiB files */
145 if (ctx->inp_size > SIZE_MAX) {
146 FATAL("cannot mmap %" PRIu64 " bytes\n", ctx->inp_size);
150 INFO("memory mapping '%s' (size %" PRIu64 ")\n", ctx->fec_filename,
154 int flags = PROT_READ;
160 void *p = mmap(NULL, (size_t)ctx->inp_size, flags, MAP_SHARED, fd, 0);
162 if (p == MAP_FAILED) {
163 FATAL("failed to mmap '%s' (size %" PRIu64 "): %s\n",
164 ctx->fec_filename, ctx->inp_size, strerror(errno));
168 ctx->input = (uint8_t *)p;
171 ctx->output = ctx->input;
172 } else if (output_needed) {
174 INFO("allocating %" PRIu64 " bytes of memory\n", ctx->inp_size);
177 ctx->output = new uint8_t[ctx->inp_size];
180 FATAL("failed to allocate memory\n");
183 memcpy(ctx->output, ctx->input, ctx->inp_size);
186 /* fd is closed in mmap_image_free */
189 #ifndef IMAGE_NO_SPARSE
190 static int process_chunk(void *priv, const void *data, int len)
192 image *ctx = (image *)priv;
193 assert(len % FEC_BLOCKSIZE == 0);
196 memcpy(&ctx->input[ctx->pos], data, len);
204 static void file_image_load(const std::vector<int>& fds, image *ctx)
207 #ifndef IMAGE_NO_SPARSE
208 std::vector<struct sparse_file *> files;
211 for (auto fd : fds) {
214 #ifdef IMAGE_NO_SPARSE
216 FATAL("sparse files not supported\n");
221 struct sparse_file *file;
224 file = sparse_file_import(fd, false, false);
226 file = sparse_file_import_auto(fd, false, ctx->verbose);
230 FATAL("failed to read file %s\n", ctx->fec_filename);
233 len = sparse_file_len(file, false, false);
234 files.push_back(file);
235 #endif /* IMAGE_NO_SPARSE */
240 calculate_rounds(size, ctx);
243 INFO("allocating %" PRIu64 " bytes of memory\n", ctx->inp_size);
246 ctx->input = new uint8_t[ctx->inp_size];
249 FATAL("failed to allocate memory\n");
252 memset(ctx->input, 0, ctx->inp_size);
253 ctx->output = ctx->input;
256 #ifdef IMAGE_NO_SPARSE
257 for (auto fd : fds) {
258 uint64_t len = get_size(fd);
260 if (!android::base::ReadFully(fd, &ctx->input[ctx->pos], len)) {
261 FATAL("failed to read: %s\n", strerror(errno));
268 for (auto file : files) {
269 sparse_file_callback(file, false, false, process_chunk, ctx);
270 sparse_file_destroy(file);
273 for (auto fd : fds) {
279 bool image_load(const std::vector<std::string>& filenames, image *ctx,
282 assert(ctx->roots > 0 && ctx->roots < FEC_RSM);
283 ctx->rs_n = FEC_RSM - ctx->roots;
285 int flags = O_RDONLY;
291 std::vector<int> fds;
293 for (auto fn : filenames) {
294 int fd = TEMP_FAILURE_RETRY(open(fn.c_str(), flags | O_LARGEFILE));
297 FATAL("failed to open file '%s': %s\n", fn.c_str(), strerror(errno));
304 mmap_image_load(fds, ctx, output_needed);
306 file_image_load(fds, ctx);
312 bool image_save(const std::string& filename, image *ctx)
314 if (ctx->inplace && ctx->mmap) {
315 return true; /* nothing to do */
318 /* TODO: support saving as a sparse file */
319 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(),
320 O_WRONLY | O_CREAT | O_TRUNC, 0666));
323 FATAL("failed to open file '%s: %s'\n", filename.c_str(),
327 if (!android::base::WriteFully(fd, ctx->output, ctx->inp_size)) {
328 FATAL("failed to write to output: %s\n", strerror(errno));
335 static void mmap_image_ecc_new(image *ctx)
338 INFO("mmaping '%s' (size %u)\n", ctx->fec_filename, ctx->fec_size);
341 int fd = TEMP_FAILURE_RETRY(open(ctx->fec_filename,
342 O_RDWR | O_CREAT, 0666));
345 FATAL("failed to open file '%s': %s\n", ctx->fec_filename,
349 assert(sizeof(fec_header) <= FEC_BLOCKSIZE);
350 size_t fec_size = FEC_BLOCKSIZE + ctx->fec_size;
352 if (ftruncate(fd, fec_size) == -1) {
353 FATAL("failed to ftruncate file '%s': %s\n", ctx->fec_filename,
358 INFO("memory mapping '%s' (size %zu)\n", ctx->fec_filename, fec_size);
361 void *p = mmap(NULL, fec_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
363 if (p == MAP_FAILED) {
364 FATAL("failed to mmap '%s' (size %zu): %s\n", ctx->fec_filename,
365 fec_size, strerror(errno));
369 ctx->fec_mmap_addr = (uint8_t *)p;
370 ctx->fec = ctx->fec_mmap_addr;
373 static void file_image_ecc_new(image *ctx)
376 INFO("allocating %u bytes of memory\n", ctx->fec_size);
379 ctx->fec = new uint8_t[ctx->fec_size];
382 FATAL("failed to allocate %u bytes\n", ctx->fec_size);
386 bool image_ecc_new(const std::string& filename, image *ctx)
388 assert(ctx->rounds > 0); /* image_load should be called first */
390 ctx->fec_filename = filename.c_str();
391 ctx->fec_size = ctx->rounds * ctx->roots * FEC_BLOCKSIZE;
394 mmap_image_ecc_new(ctx);
396 file_image_ecc_new(ctx);
402 bool image_ecc_load(const std::string& filename, image *ctx)
404 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY));
407 FATAL("failed to open file '%s': %s\n", filename.c_str(),
411 if (lseek64(fd, -FEC_BLOCKSIZE, SEEK_END) < 0) {
412 FATAL("failed to seek to header in '%s': %s\n", filename.c_str(),
416 assert(sizeof(fec_header) <= FEC_BLOCKSIZE);
418 uint8_t header[FEC_BLOCKSIZE];
419 fec_header *p = (fec_header *)header;
421 if (!android::base::ReadFully(fd, header, sizeof(header))) {
422 FATAL("failed to read %zd bytes from '%s': %s\n", sizeof(header),
423 filename.c_str(), strerror(errno));
426 if (p->magic != FEC_MAGIC) {
427 FATAL("invalid magic in '%s': %08x\n", filename.c_str(), p->magic);
430 if (p->version != FEC_VERSION) {
431 FATAL("unsupported version in '%s': %u\n", filename.c_str(),
435 if (p->size != sizeof(fec_header)) {
436 FATAL("unexpected header size in '%s': %u\n", filename.c_str(),
440 if (p->roots == 0 || p->roots >= FEC_RSM) {
441 FATAL("invalid roots in '%s': %u\n", filename.c_str(), p->roots);
444 if (p->fec_size % p->roots || p->fec_size % FEC_BLOCKSIZE) {
445 FATAL("invalid length in '%s': %u\n", filename.c_str(), p->fec_size);
448 ctx->roots = (int)p->roots;
449 ctx->rs_n = FEC_RSM - ctx->roots;
451 calculate_rounds(p->inp_size, ctx);
453 if (!image_ecc_new(filename, ctx)) {
454 FATAL("failed to allocate ecc\n");
457 if (p->fec_size != ctx->fec_size) {
458 FATAL("inconsistent header in '%s'\n", filename.c_str());
461 if (lseek64(fd, 0, SEEK_SET) < 0) {
462 FATAL("failed to rewind '%s': %s", filename.c_str(), strerror(errno));
465 if (!ctx->mmap && !android::base::ReadFully(fd, ctx->fec, ctx->fec_size)) {
466 FATAL("failed to read %u bytes from '%s': %s\n", ctx->fec_size,
467 filename.c_str(), strerror(errno));
472 uint8_t hash[SHA256_DIGEST_LENGTH];
473 SHA256(ctx->fec, ctx->fec_size, hash);
475 if (memcmp(hash, p->hash, SHA256_DIGEST_LENGTH) != 0) {
476 FATAL("invalid ecc data\n");
482 bool image_ecc_save(image *ctx)
484 assert(sizeof(fec_header) <= FEC_BLOCKSIZE);
486 uint8_t header[FEC_BLOCKSIZE];
490 p = (uint8_t *)&ctx->fec_mmap_addr[ctx->fec_size];
493 memset(p, 0, FEC_BLOCKSIZE);
495 fec_header *f = (fec_header *)p;
497 f->magic = FEC_MAGIC;
498 f->version = FEC_VERSION;
499 f->size = sizeof(fec_header);
500 f->roots = ctx->roots;
501 f->fec_size = ctx->fec_size;
502 f->inp_size = ctx->inp_size;
504 SHA256(ctx->fec, ctx->fec_size, f->hash);
506 /* store a copy of the fec_header at the end of the header block */
507 memcpy(&p[sizeof(header) - sizeof(fec_header)], p, sizeof(fec_header));
510 assert(ctx->fec_filename);
512 int fd = TEMP_FAILURE_RETRY(open(ctx->fec_filename,
513 O_WRONLY | O_CREAT | O_TRUNC, 0666));
516 FATAL("failed to open file '%s': %s\n", ctx->fec_filename,
520 if (!android::base::WriteFully(fd, ctx->fec, ctx->fec_size) ||
521 !android::base::WriteFully(fd, header, sizeof(header))) {
522 FATAL("failed to write to output: %s\n", strerror(errno));
531 static void * process(void *cookie)
533 image_proc_ctx *ctx = (image_proc_ctx *)cookie;
538 bool image_process(image_proc_func func, image *ctx)
540 int threads = ctx->threads;
542 if (threads < IMAGE_MIN_THREADS) {
543 threads = sysconf(_SC_NPROCESSORS_ONLN);
545 if (threads < IMAGE_MIN_THREADS) {
546 threads = IMAGE_MIN_THREADS;
550 assert(ctx->rounds > 0);
552 if ((uint64_t)threads > ctx->rounds) {
553 threads = (int)ctx->rounds;
555 if (threads > IMAGE_MAX_THREADS) {
556 threads = IMAGE_MAX_THREADS;
560 INFO("starting %d threads to compute RS(255, %d)\n", threads,
564 pthread_t pthreads[threads];
565 image_proc_ctx args[threads];
567 uint64_t current = 0;
568 uint64_t end = ctx->rounds * ctx->rs_n * FEC_BLOCKSIZE;
569 uint64_t rs_blocks_per_thread =
570 fec_div_round_up(ctx->rounds * FEC_BLOCKSIZE, threads);
573 INFO("computing %" PRIu64 " codes per thread\n", rs_blocks_per_thread);
576 for (int i = 0; i < threads; ++i) {
581 args[i].fec_pos = current * ctx->roots;
582 args[i].start = current * ctx->rs_n;
583 args[i].end = (current + rs_blocks_per_thread) * ctx->rs_n;
585 args[i].rs = init_rs_char(FEC_PARAMS(ctx->roots));
588 FATAL("failed to initialize encoder for thread %d\n", i);
591 if (args[i].end > end) {
593 } else if (i == threads && args[i].end + rs_blocks_per_thread *
599 INFO("thread %d: [%" PRIu64 ", %" PRIu64 ")\n",
600 i, args[i].start, args[i].end);
603 assert(args[i].start < args[i].end);
604 assert((args[i].end - args[i].start) % ctx->rs_n == 0);
606 if (pthread_create(&pthreads[i], NULL, process, &args[i]) != 0) {
607 FATAL("failed to create thread %d\n", i);
610 current += rs_blocks_per_thread;
615 for (int i = 0; i < threads; ++i) {
616 if (pthread_join(pthreads[i], NULL) != 0) {
617 FATAL("failed to join thread %d: %s\n", i, strerror(errno));
620 ctx->rv += args[i].rv;
623 free_rs_char(args[i].rs);