Skip to content

Commit ac5100f

Browse files
committed
modpost: add read_text_file() and get_line() helpers
modpost uses grab_file() to open a file, but it is not suitable for a text file because the mmap'ed file is not terminated by null byte. Actually, I see some issues for the use of grab_file(). The new helper, read_text_file() loads the whole file content into a malloc'ed buffer, and appends a null byte. Then, get_line() reads each line. To handle text files, I intend to replace as follows: grab_file() -> read_text_file() get_new_line() -> get_line() Signed-off-by: Masahiro Yamada <[email protected]>
1 parent 4ddea2f commit ac5100f

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

scripts/mod/modpost.c

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,55 @@ void *do_nofail(void *ptr, const char *expr)
112112
return ptr;
113113
}
114114

115+
char *read_text_file(const char *filename)
116+
{
117+
struct stat st;
118+
size_t nbytes;
119+
int fd;
120+
char *buf;
121+
122+
fd = open(filename, O_RDONLY);
123+
if (fd < 0) {
124+
perror(filename);
125+
exit(1);
126+
}
127+
128+
if (fstat(fd, &st) < 0) {
129+
perror(filename);
130+
exit(1);
131+
}
132+
133+
buf = NOFAIL(malloc(st.st_size + 1));
134+
135+
nbytes = st.st_size;
136+
137+
while (nbytes) {
138+
ssize_t bytes_read;
139+
140+
bytes_read = read(fd, buf, nbytes);
141+
if (bytes_read < 0) {
142+
perror(filename);
143+
exit(1);
144+
}
145+
146+
nbytes -= bytes_read;
147+
}
148+
buf[st.st_size] = '\0';
149+
150+
close(fd);
151+
152+
return buf;
153+
}
154+
155+
char *get_line(char **stringp)
156+
{
157+
/* do not return the unwanted extra line at EOF */
158+
if (*stringp && **stringp == '\0')
159+
return NULL;
160+
161+
return strsep(stringp, "\n");
162+
}
163+
115164
/* A list of all modules we processed */
116165
static struct module *modules;
117166

scripts/mod/modpost.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,8 @@ void add_moddevtable(struct buffer *buf, struct module *mod);
191191
void get_src_version(const char *modname, char sum[], unsigned sumlen);
192192

193193
/* from modpost.c */
194+
char *read_text_file(const char *filename);
195+
char *get_line(char **stringp);
194196
void *grab_file(const char *filename, unsigned long *size);
195197
char* get_next_line(unsigned long *pos, void *file, unsigned long size);
196198
void release_file(void *file, unsigned long size);

0 commit comments

Comments
 (0)