1 /*
2 * Copyright (c) 2020 Google Inc. All rights reserved
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining
5 * a copy of this software and associated documentation files
6 * (the "Software"), to deal in the Software without restriction,
7 * including without limitation the rights to use, copy, modify, merge,
8 * publish, distribute, sublicense, and/or sell copies of the Software,
9 * and to permit persons to whom the Software is furnished to do so,
10 * subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be
13 * included in all copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23
24 #include <arch/defines.h>
25 #include <arch/mmu.h>
26 #include <assert.h>
27 #include <endian.h>
28 #include <inttypes.h>
29 #include <kernel/vm.h>
30 #include <lib/rand/rand.h>
31 #include <trace.h>
32
33 #define LOCAL_TRACE 0
34
aslr_randomize_kernel_base(vaddr_t kernel_base)35 vaddr_t aslr_randomize_kernel_base(vaddr_t kernel_base) {
36 STATIC_ASSERT(!(KERNEL_ASPACE_BASE & (PAGE_SIZE - 1)));
37 STATIC_ASSERT(!(KERNEL_ASPACE_SIZE & (PAGE_SIZE - 1)));
38
39 struct mmu_initial_mapping* second_mapping = &mmu_initial_mappings[1];
40 if (second_mapping->size) {
41 LTRACEF("non-kernel mapping phys:0x%" PRIxPADDR " virt:0x%" PRIxVADDR
42 " size:%zu\n",
43 second_mapping->phys, second_mapping->virt,
44 second_mapping->size);
45 return kernel_base;
46 }
47
48 struct mmu_initial_mapping* kernel_mapping = mmu_initial_mappings;
49 kernel_base -= KERNEL_LOAD_OFFSET;
50 ASSERT(kernel_mapping->virt == kernel_base);
51 ASSERT(kernel_mapping->size);
52 ASSERT(!(kernel_mapping->size & (PAGE_SIZE - 1)));
53
54 const size_t aspace_pages = KERNEL_ASPACE_SIZE / PAGE_SIZE;
55 size_t kernel_pages = kernel_mapping->size / PAGE_SIZE;
56 /* Include 2 guard pages for the kernel */
57 kernel_pages += 2;
58 ASSERT(kernel_pages <= aspace_pages);
59
60 size_t pick = rand_get_size(aspace_pages - kernel_pages);
61 kernel_mapping->virt = KERNEL_ASPACE_BASE + ((1 + pick) * PAGE_SIZE);
62 return kernel_mapping->virt + KERNEL_LOAD_OFFSET;
63 }
64