prune-packed: use strbuf to avoid having to worry about PATH_MAX
A/very/long/path/to/.git that becomes exactly PATH_MAX bytes long after suffixed with /objects/??/??38-hex??, would have overflown the on-stack pathname[] buffer. Noticed-by: Michael Haggerty <mhagger@alum.mit.edu> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Junio C Hamano committed
Dec 17, 2013 at 10:43 UTC
c235d960cb32ddca352d12c3f8dc053ddfd421dd
1 file changed
+21
-17
builtin/prune-packed.c
+21
-17
@@ -10,58 +10,62 @@ static const char * const prune_packed_usage[] = {
10
11
static struct progress *progress;
12
13
-static void prune_dir(int i, DIR *dir, char *pathname, int len, int opts)
13
+static void prune_dir(int i, DIR *dir, struct strbuf *pathname, int opts)
14
{
15
struct dirent *de;
16
char hex[40];
17
+ int top_len = pathname->len;
18
19
sprintf(hex, "%02x", i);
20
while ((de = readdir(dir)) != NULL) {
21
unsigned char sha1[20];
22
if (strlen(de->d_name) != 38)
23
continue;
23
- memcpy(hex+2, de->d_name, 38);
24
+ memcpy(hex + 2, de->d_name, 38);
25
if (get_sha1_hex(hex, sha1))
26
continue;
27
if (!has_sha1_pack(sha1))
28
continue;
28
- memcpy(pathname + len, de->d_name, 38);
29
+
30
+ strbuf_add(pathname, de->d_name, 38);
31
if (opts & PRUNE_PACKED_DRY_RUN)
30
- printf("rm -f %s\n", pathname);
32
+ printf("rm -f %s\n", pathname->buf);
33
else
32
- unlink_or_warn(pathname);
34
+ unlink_or_warn(pathname->buf);
35
display_progress(progress, i + 1);
36
+ strbuf_setlen(pathname, top_len);
37
}
38
}
39
40
void prune_packed_objects(int opts)
41
{
42
int i;
40
- static char pathname[PATH_MAX];
43
const char *dir = get_object_directory();
42
- int len = strlen(dir);
44
+ struct strbuf pathname = STRBUF_INIT;
45
+ int top_len;
46
47
+ strbuf_addstr(&pathname, dir);
48
if (opts & PRUNE_PACKED_VERBOSE)
49
progress = start_progress_delay("Removing duplicate objects",
50
256, 95, 2);
51
48
- if (len > PATH_MAX - 42)
49
- die("impossible object directory");
50
- memcpy(pathname, dir, len);
51
- if (len && pathname[len-1] != '/')
52
- pathname[len++] = '/';
52
+ if (pathname.len && pathname.buf[pathname.len - 1] != '/')
53
+ strbuf_addch(&pathname, '/');
54
+
55
+ top_len = pathname.len;
56
for (i = 0; i < 256; i++) {
57
DIR *d;
58
59
display_progress(progress, i + 1);
57
- sprintf(pathname + len, "%02x/", i);
58
- d = opendir(pathname);
60
+ strbuf_setlen(&pathname, top_len);
61
+ strbuf_addf(&pathname, "%02x/", i);
62
+ d = opendir(pathname.buf);
63
if (!d)
64
continue;
61
- prune_dir(i, d, pathname, len + 3, opts);
65
+ prune_dir(i, d, &pathname, opts);
66
closedir(d);
63
- pathname[len + 2] = '\0';
64
- rmdir(pathname);
67
+ strbuf_setlen(&pathname, top_len + 2);
68
+ rmdir(pathname.buf);
69
}
70
stop_progress(&progress);
71
}