Skip to content
Snippets Groups Projects
Commit fe905ed1 authored by jD91mZM2's avatar jD91mZM2
Browse files

Merge branch 'calloc_overflow_check' into 'master'

add calloc integer overflow check

See merge request !188
parents 71f8fb32 7aa0fbdf
No related branches found
No related tags found
1 merge request!188add calloc integer overflow check
Pipeline #3077 passed with warnings
...@@ -186,12 +186,18 @@ pub unsafe extern "C" fn bsearch( ...@@ -186,12 +186,18 @@ pub unsafe extern "C" fn bsearch(
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn calloc(nelem: size_t, elsize: size_t) -> *mut c_void { pub unsafe extern "C" fn calloc(nelem: size_t, elsize: size_t) -> *mut c_void {
let size = nelem * elsize; //Handle possible integer overflow in size calculation
let ptr = malloc(size); let size_result = nelem.checked_mul(elsize);
if !ptr.is_null() { match size_result {
intrinsics::write_bytes(ptr as *mut u8, 0, size); Some(size) => {
let ptr = malloc(size);
if !ptr.is_null() {
intrinsics::write_bytes(ptr as *mut u8, 0, size);
}
ptr
},
None => core::ptr::null_mut()
} }
ptr
} }
#[repr(C)] #[repr(C)]
......
#include <malloc.h> #include <malloc.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdint.h> /* for SIZE_MAX */
int main(void) { int main(void) {
char * ptr = (char *)malloc(256); char * ptr = (char *)malloc(256);
...@@ -18,6 +19,10 @@ int main(void) { ...@@ -18,6 +19,10 @@ int main(void) {
} }
free(ptrc); free(ptrc);
char * ptrco = (char *)calloc(SIZE_MAX, SIZE_MAX);
printf("calloc (overflowing) %p\n", ptrco);
free(ptrco); /* clean up correctly even if overflow is not handled */
char * ptra = (char *)memalign(256, 256); char * ptra = (char *)memalign(256, 256);
printf("memalign %p\n", ptra); printf("memalign %p\n", ptra);
for(i = 0; i < 256; i++) { for(i = 0; i < 256; i++) {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment