@matheusbsbs / matheus-bagliano / commits / cc96fd092a
Fork 0

git-apply: Do not free the wrong buffer when we convert the data for writeout

When we write out the result of patch application, we sometimes need to munge the data (e.g. under core.autocrlf). After doing so, what we should free is the temporary buffer that holds the converted data returned from convert_to_working_tree(), not the original one. This patch also moves the call to open() up in the function, as the caller expects us to fail cheaply if leading directories need to be created (and then the caller creates them and calls us again). For that calling pattern, attempting conversion before opening the file adds unnecessary overhead. Acked-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Junio C Hamano <junkio@cox.net>

Junio C Hamano committed Mar 22, 2007 at 17:32 UTC cc96fd092a55a7a8685f0dee1e287ded70bc08b7
1 file changed +10 -7
builtin-apply.c
+10 -7
@@ -2355,7 +2355,7 @@ static void add_index_file(const char *path, unsigned mode, void *buf, unsigned
2355
2356 static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
2357 {
2358 - int fd;
2358 + int fd, converted;
2359 char *nbuf;
2360 unsigned long nsize;
2361
@@ -2364,17 +2364,18 @@ static int try_create_file(const char *path, unsigned int mode, const char *buf,
2364 * terminated.
2365 */
2366 return symlink(buf, path);
2367 +
2368 + fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
2369 + if (fd < 0)
2370 + return -1;
2371 +
2372 nsize = size;
2373 nbuf = (char *) buf;
2369 - if (convert_to_working_tree(path, &nbuf, &nsize)) {
2370 - free((char *) buf);
2374 + converted = convert_to_working_tree(path, &nbuf, &nsize);
2375 + if (converted) {
2376 buf = nbuf;
2377 size = nsize;
2378 }
2374 -
2375 - fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
2376 - if (fd < 0)
2377 - return -1;
2379 while (size) {
2380 int written = xwrite(fd, buf, size);
2381 if (written < 0)
@@ -2386,6 +2387,8 @@ static int try_create_file(const char *path, unsigned int mode, const char *buf,
2387 }
2388 if (close(fd) < 0)
2389 die("closing file %s: %s", path, strerror(errno));
2390 + if (converted)
2391 + free(nbuf);
2392 return 0;
2393 }
2394