*: fix places where we were still using malloc/realloc
[oweals/busybox.git] / editors / patch.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  *  busybox patch applet to handle the unified diff format.
4  *  Copyright (C) 2003 Glenn McGrath
5  *
6  *  Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
7  *
8  *  This applet is written to work with patches generated by GNU diff,
9  *  where there is equivalent functionality busybox patch shall behave
10  *  as per GNU patch.
11  *
12  *  There is a SUSv3 specification for patch, however it looks to be
13  *  incomplete, it doesnt even mention unified diff format.
14  *  http://www.opengroup.org/onlinepubs/007904975/utilities/patch.html
15  *
16  *  Issues
17  *   - Non-interactive
18  *   - Patches must apply cleanly or patch (not just one hunk) will fail.
19  *   - Reject file isnt saved
20  */
21
22 #include "libbb.h"
23
24 static unsigned copy_lines(FILE *src_stream, FILE *dst_stream, unsigned lines_count)
25 {
26         while (src_stream && lines_count) {
27                 char *line;
28                 line = xmalloc_fgets(src_stream);
29                 if (line == NULL) {
30                         break;
31                 }
32                 if (fputs(line, dst_stream) == EOF) {
33                         bb_perror_msg_and_die("error writing to new file");
34                 }
35                 free(line);
36                 lines_count--;
37         }
38         return lines_count;
39 }
40
41 /* If patch_level is -1 it will remove all directory names
42  * char *line must be greater than 4 chars
43  * returns NULL if the file doesnt exist or error
44  * returns malloc'ed filename
45  * NB: frees 1st argument!
46  */
47 static char *extract_filename(char *line, int patch_level, const char *pat)
48 {
49         char *temp = NULL, *filename_start_ptr = line + 4;
50
51         if (strncmp(line, pat, 4) == 0) {
52                 /* Terminate string at end of source filename */
53                 line[strcspn(line, "\t\n\r")] = '\0';
54
55                 /* Skip over (patch_level) number of leading directories */
56                 while (patch_level--) {
57                         temp = strchr(filename_start_ptr, '/');
58                         if (!temp)
59                                 break;
60                         filename_start_ptr = temp + 1;
61                 }
62                 temp = xstrdup(filename_start_ptr);
63         }
64         free(line);
65         return temp;
66 }
67
68 int patch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
69 int patch_main(int argc UNUSED_PARAM, char **argv)
70 {
71         struct stat saved_stat;
72         char *patch_line;
73         FILE *patch_file;
74         int patch_level;
75         int ret = 0;
76         char plus = '+';
77         unsigned opt;
78         enum {
79                 OPT_R = (1 << 2),
80                 OPT_N = (1 << 3),
81                 OPT_dry_run = (1 << 4) * ENABLE_LONG_OPTS,
82         };
83
84         xfunc_error_retval = 2;
85         {
86                 const char *p = "-1";
87                 const char *i = "-"; /* compat */
88 #if ENABLE_LONG_OPTS
89                 static const char patch_longopts[] ALIGN1 =
90                         "strip\0"   Required_argument "p"
91                         "input\0"   Required_argument "i"
92                         "reverse\0" No_argument       "R"
93                         "forward\0" No_argument       "N"
94                         "dry-run\0" No_argument       "\xff"
95                         ;
96                 applet_long_options = patch_longopts;
97 #endif
98                 opt = getopt32(argv, "p:i:RN", &p, &i);
99                 if (opt & OPT_R)
100                         plus = '-';
101                 patch_level = xatoi(p); /* can be negative! */
102                 patch_file = xfopen_stdin(i);
103         }
104
105         patch_line = xmalloc_fgetline(patch_file);
106         while (patch_line) {
107                 FILE *src_stream;
108                 FILE *dst_stream;
109                 //char *old_filename;
110                 char *new_filename;
111                 char *backup_filename = NULL;
112                 unsigned src_cur_line = 1;
113                 unsigned dst_cur_line = 0;
114                 unsigned dst_beg_line;
115                 unsigned bad_hunk_count = 0;
116                 unsigned hunk_count = 0;
117                 smallint copy_trailing_lines_flag = 0;
118
119                 /* Skip everything upto the "---" marker
120                  * No need to parse the lines "Only in <dir>", and "diff <args>"
121                  */
122                 do {
123                         /* Extract the filename used before the patch was generated */
124                         new_filename = extract_filename(patch_line, patch_level, "--- ");
125                         // was old_filename above
126                         patch_line = xmalloc_fgetline(patch_file);
127                         if (!patch_line) goto quit;
128                 } while (!new_filename);
129                 free(new_filename); // "source" filename is irrelevant
130
131                 new_filename = extract_filename(patch_line, patch_level, "+++ ");
132                 if (!new_filename) {
133                         bb_error_msg_and_die("invalid patch");
134                 }
135
136                 /* Get access rights from the file to be patched */
137                 if (stat(new_filename, &saved_stat) != 0) {
138                         char *slash = strrchr(new_filename, '/');
139                         if (slash) {
140                                 /* Create leading directories */
141                                 *slash = '\0';
142                                 bb_make_directory(new_filename, -1, FILEUTILS_RECUR);
143                                 *slash = '/';
144                         }
145                         src_stream = NULL;
146                         saved_stat.st_mode = 0644;
147                 } else if (!(opt & OPT_dry_run)) {
148                         backup_filename = xasprintf("%s.orig", new_filename);
149                         xrename(new_filename, backup_filename);
150                         src_stream = xfopen_for_read(backup_filename);
151                 } else
152                         src_stream = xfopen_for_read(new_filename);
153
154                 if (opt & OPT_dry_run) {
155                         dst_stream = xfopen_for_write("/dev/null");
156                 } else {
157                         dst_stream = xfopen_for_write(new_filename);
158                         fchmod(fileno(dst_stream), saved_stat.st_mode);
159                 }
160
161                 printf("patching file %s\n", new_filename);
162
163                 /* Handle all hunks for this file */
164                 patch_line = xmalloc_fgets(patch_file);
165                 while (patch_line) {
166                         unsigned count;
167                         unsigned src_beg_line;
168                         unsigned hunk_offset_start;
169                         unsigned src_last_line = 1;
170                         unsigned dst_last_line = 1;
171
172                         if ((sscanf(patch_line, "@@ -%d,%d +%d,%d", &src_beg_line, &src_last_line, &dst_beg_line, &dst_last_line) < 3)
173                          && (sscanf(patch_line, "@@ -%d +%d,%d", &src_beg_line, &dst_beg_line, &dst_last_line) < 2)
174                         ) {
175                                 /* No more hunks for this file */
176                                 break;
177                         }
178                         if (plus != '+') {
179                                 /* reverse patch */
180                                 unsigned tmp = src_last_line;
181                                 src_last_line = dst_last_line;
182                                 dst_last_line = tmp;
183                                 tmp = src_beg_line;
184                                 src_beg_line = dst_beg_line;
185                                 dst_beg_line = tmp;
186                         }
187                         hunk_count++;
188
189                         if (src_beg_line && dst_beg_line) {
190                                 /* Copy unmodified lines upto start of hunk */
191                                 /* src_beg_line will be 0 if it's a new file */
192                                 count = src_beg_line - src_cur_line;
193                                 if (copy_lines(src_stream, dst_stream, count)) {
194                                         bb_error_msg_and_die("bad src file");
195                                 }
196                                 src_cur_line += count;
197                                 dst_cur_line += count;
198                                 copy_trailing_lines_flag = 1;
199                         }
200                         src_last_line += hunk_offset_start = src_cur_line;
201                         dst_last_line += dst_cur_line;
202
203                         while (1) {
204                                 free(patch_line);
205                                 patch_line = xmalloc_fgets(patch_file);
206                                 if (patch_line == NULL)
207                                         break; /* EOF */
208                                 if (!*patch_line) {
209                                         /* whitespace-damaged patch with "" lines */
210                                         free(patch_line);
211                                         patch_line = xstrdup(" ");
212                                 }
213                                 if ((*patch_line != '-') && (*patch_line != '+')
214                                  && (*patch_line != ' ')
215                                 ) {
216                                         break; /* End of hunk */
217                                 }
218                                 if (*patch_line != plus) { /* '-' or ' ' */
219                                         char *src_line = NULL;
220                                         if (src_cur_line == src_last_line)
221                                                 break;
222                                         if (src_stream) {
223                                                 src_line = xmalloc_fgets(src_stream);
224                                                 if (src_line) {
225                                                         int diff = strcmp(src_line, patch_line + 1);
226                                                         src_cur_line++;
227                                                         free(src_line);
228                                                         if (diff)
229                                                                 src_line = NULL;
230                                                 }
231                                         }
232                                         /* Do not patch an already patched hunk with -N */
233                                         if (src_line == 0 && (opt & OPT_N)) {
234                                                 continue;
235                                         }
236                                         if (!src_line) {
237                                                 bb_error_msg("hunk #%u FAILED at %u", hunk_count, hunk_offset_start);
238                                                 bad_hunk_count++;
239                                                 break;
240                                         }
241                                         if (*patch_line != ' ') { /* '-' */
242                                                 continue;
243                                         }
244                                 }
245                                 if (dst_cur_line == dst_last_line)
246                                         break;
247                                 fputs(patch_line + 1, dst_stream);
248                                 dst_cur_line++;
249                         } /* end of while loop handling one hunk */
250                 } /* end of while loop handling one file */
251
252                 /* Cleanup last patched file */
253                 if (copy_trailing_lines_flag) {
254                         copy_lines(src_stream, dst_stream, (unsigned)(-1));
255                 }
256                 if (src_stream) {
257                         fclose(src_stream);
258                 }
259                 fclose(dst_stream);
260                 if (bad_hunk_count) {
261                         ret = 1;
262                         bb_error_msg("%u out of %u hunk FAILED", bad_hunk_count, hunk_count);
263                 } else {
264                         /* It worked, we can remove the backup */
265                         if (backup_filename) {
266                                 unlink(backup_filename);
267                         }
268                         if (!(opt & OPT_dry_run)
269                          && ((dst_cur_line == 0) || (dst_beg_line == 0))
270                         ) {
271                                 /* The new patched file is empty, remove it */
272                                 xunlink(new_filename);
273                                 // /* old_filename and new_filename may be the same file */
274                                 // unlink(old_filename);
275                         }
276                 }
277                 free(backup_filename);
278                 //free(old_filename);
279                 free(new_filename);
280         } /* end of "while there are patch lines" */
281  quit:
282         /* 0 = SUCCESS
283          * 1 = Some hunks failed
284          * 2 = More serious problems (exited earlier)
285          */
286         return ret;
287 }