1 // SPDX-License-Identifier: GPL-2.0-only
2 /* ----------------------------------------------------------------------- *
4 * Copyright 2012 Intel Corporation; author H. Peter Anvin
6 * ----------------------------------------------------------------------- */
11 * Find a specific cpio member; must precede any compressed content.
12 * This is used to locate data items in the initramfs used by the
13 * kernel itself during early boot (before the main initramfs is
14 * decompressed.) It is the responsibility of the initramfs creator
15 * to ensure that these items are uncompressed at the head of the
16 * blob. Depending on the boot loader or package tool that may be a
17 * separate file or part of the same file.
20 #include <linux/earlycpio.h>
21 #include <linux/kernel.h>
22 #include <linux/string.h>
43 * find_cpio_data - Search for files in an uncompressed cpio
44 * @path: The directory to search for, including a slash at the end
45 * @data: Pointer to the cpio archive or a header inside
46 * @len: Remaining length of the cpio based on data pointer
47 * @nextoff: When a matching file is found, this is the offset from the
48 * beginning of the cpio to the beginning of the next file, not the
49 * matching file itself. It can be used to iterate through the cpio
50 * to find all files inside of a directory path.
52 * Return: &struct cpio_data containing the address, length and
53 * filename (with the directory path cut off) of the found file.
54 * If you search for a filename and not for files in a directory,
55 * pass the absolute path of the filename in the cpio and make sure
56 * the match returned an empty filename string.
59 struct cpio_data find_cpio_data(const char *path, void *data,
60 size_t len, long *nextoff)
62 const size_t cpio_header_len = 8*C_NFIELDS - 2;
63 struct cpio_data cd = { NULL, 0, "" };
64 const char *p, *dptr, *nptr;
65 unsigned int ch[C_NFIELDS], *chp, v;
67 size_t mypathsize = strlen(path);
72 while (len > cpio_header_len) {
74 /* All cpio headers need to be 4-byte aligned */
80 j = 6; /* The magic field is only 6 characters */
82 for (i = C_NFIELDS; i; i--) {
100 goto quit; /* Invalid hexadecimal */
103 j = 8; /* All other fields are 8 characters */
106 if ((ch[C_MAGIC] - 0x070701) > 1)
107 goto quit; /* Invalid magic */
109 len -= cpio_header_len;
111 dptr = PTR_ALIGN(p + ch[C_NAMESIZE], 4);
112 nptr = PTR_ALIGN(dptr + ch[C_FILESIZE], 4);
114 if (nptr > p + len || dptr < p || nptr < dptr)
115 goto quit; /* Buffer overrun */
117 if ((ch[C_MODE] & 0170000) == 0100000 &&
118 ch[C_NAMESIZE] >= mypathsize &&
119 !memcmp(p, path, mypathsize)) {
122 *nextoff = (long)nptr - (long)data;
124 if (ch[C_NAMESIZE] - mypathsize >= MAX_CPIO_FILE_NAME) {
126 "File %s exceeding MAX_CPIO_FILE_NAME [%d]\n",
127 p, MAX_CPIO_FILE_NAME);
129 strlcpy(cd.name, p + mypathsize, MAX_CPIO_FILE_NAME);
131 cd.data = (void *)dptr;
132 cd.size = ch[C_FILESIZE];
133 return cd; /* Found it! */