路径:kexec-tools-2.0.20\kexec\lzma.c
char *lzma_decompress_file(const char *filename, off_t *r_size) { LZFILE *fp; char *buf; off_t size, allocated; ssize_t result;
dbgprintf("Try LZMA decompression.\n");
*r_size = 0;
//如果filename为空,返回NULL if (!filename) return NULL;
//以只读二进制方式打开filename文件,如果失败,报错并返回NULL
fp = lzopen(filename, "rb"); if (fp == 0) { dbgprintf("Cannot open `%s'\n", filename); return NULL; } size = 0;
//动态分配65536个字节 allocated = 65536; buf = xmalloc(allocated);
// do {
//如果文件大于已分配的大小,则重新分配2倍大小的内存已读取完整文件 if (size == allocated) { allocated <<= 1; buf = xrealloc(buf, allocated); }
读取allocated - size个字节,保存到buf中,如果失败(但不是EINTR和EAGAIN错误),跳出循环 result = lzread(fp, buf + size, allocated - size); if (result < 0) { if ((errno == EINTR) || (errno == EAGAIN)) continue;
dbgprintf("%s: read on %s of %ld bytes failed\n", __func__, filename, (allocated - size) + 0UL); break; } size += result; } while (result > 0);
//关闭文件,如果失败,报错并跳转到fail
if (lzclose(fp) != LZMA_OK) { dbgprintf("%s: Close of %s failed\n", __func__, filename); goto fail; } if (result < 0) goto fail;
//如果读到的字节数大于0,则将其保存于*r_size返回,并返回分配的内存首地址
*r_size = size; return buf; fail:
//释放掉分配的内存,返回NULL free(buf); return NULL; }
这个函数的作用是:读取压缩文件内容,返回其保存的内存以及长度。