1 /*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <time.h>
17 #include <fcntl.h>
18 #include <unistd.h>
19 #include <stdbool.h>
20 #include <time.h>
21 #include "malloc_random.h"
22
23 #ifdef MALLOC_FREELIST_HARDENED
get_random(uint64_t * x)24 static bool get_random(uint64_t *x)
25 {
26 int fd = open("/dev/urandom", O_RDONLY);
27 if (fd < 0) {
28 return false;
29 }
30 int ret = read(fd, x, sizeof(uint64_t));
31 if (ret < 0) {
32 close(fd);
33 return false;
34 }
35
36 close(fd);
37 return true;
38 }
39
next_key()40 void* next_key()
41 {
42 uint64_t x = 0;
43 struct timespec ts;
44 /* Try to use urandom to get the random number first */
45 if (!get_random(&x)) {
46 /* Can't get random number from /dev/urandom, generate from addr based on ASLR and time */
47 (void)clock_gettime(CLOCK_REALTIME, &ts);
48 x = (((uint64_t)get_random) << 32) ^ (uint64_t)next_key ^ ts.tv_nsec;
49 }
50 /* Return an odd key, make sure that the xor pointer being odd */
51 return (void *)(x | 1);
52 }
53
encode_ptr(void * ptr,void * key)54 void* encode_ptr(void *ptr, void *key)
55 {
56 return (void *)((uintptr_t)ptr ^ (uintptr_t)key);
57 }
58
59 #else // MALLOC_FREELIST_HARDENED
encode_ptr(void * ptr,void * key)60 void* encode_ptr(void *ptr, void *key)
61 {
62 (void)key;
63 return ptr;
64 }
65 #endif // MALLOC_FREELIST_HARDENED
66