X Tutup
Skip to content

Commit 2adcf6f

Browse files
authored
Merge pull request systemd#19662 from yuwata/memdup
util: make memdup() or friends safer
2 parents ed056c5 + 550721c commit 2adcf6f

File tree

3 files changed

+8
-9
lines changed

3 files changed

+8
-9
lines changed

src/basic/alloc-util.c

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,7 @@ void* memdup(const void *p, size_t l) {
1717
if (!ret)
1818
return NULL;
1919

20-
memcpy(ret, p, l);
21-
return ret;
20+
return memcpy_safe(ret, p, l);
2221
}
2322

2423
void* memdup_suffix0(const void *p, size_t l) {
@@ -35,8 +34,8 @@ void* memdup_suffix0(const void *p, size_t l) {
3534
if (!ret)
3635
return NULL;
3736

38-
*((uint8_t*) mempcpy(ret, p, l)) = 0;
39-
return ret;
37+
((uint8_t*) ret)[l] = 0;
38+
return memcpy_safe(ret, p, l);
4039
}
4140

4241
void* greedy_realloc(

src/basic/alloc-util.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ void* memdup_suffix0(const void *p, size_t l); /* We can't use _alloc_() here, s
6666
size_t _l_ = l; \
6767
assert(_l_ <= ALLOCA_MAX); \
6868
_q_ = alloca(_l_ ?: 1); \
69-
memcpy(_q_, p, _l_); \
69+
memcpy_safe(_q_, p, _l_); \
7070
})
7171

7272
#define memdupa_suffix0(p, l) \
@@ -76,7 +76,7 @@ void* memdup_suffix0(const void *p, size_t l); /* We can't use _alloc_() here, s
7676
assert(_l_ <= ALLOCA_MAX); \
7777
_q_ = alloca(_l_ + 1); \
7878
((uint8_t*) _q_)[_l_] = 0; \
79-
memcpy(_q_, p, _l_); \
79+
memcpy_safe(_q_, p, _l_); \
8080
})
8181

8282
static inline void freep(void *p) {

src/basic/memory-util.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@ size_t page_size(void) _pure_;
1616
#define PAGE_OFFSET(l) ((l) & (page_size() - 1))
1717

1818
/* Normal memcpy requires src to be nonnull. We do nothing if n is 0. */
19-
static inline void memcpy_safe(void *dst, const void *src, size_t n) {
19+
static inline void *memcpy_safe(void *dst, const void *src, size_t n) {
2020
if (n == 0)
21-
return;
21+
return dst;
2222
assert(src);
23-
memcpy(dst, src, n);
23+
return memcpy(dst, src, n);
2424
}
2525

2626
/* Normal memcmp requires s1 and s2 to be nonnull. We do nothing if n is 0. */

0 commit comments

Comments
 (0)
X Tutup