xref: /openbmc/linux/arch/arm64/kernel/module-plts.c (revision 9b93eb47)
1 /*
2  * Copyright (C) 2014-2017 Linaro Ltd. <ard.biesheuvel@linaro.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  */
8 
9 #include <linux/elf.h>
10 #include <linux/kernel.h>
11 #include <linux/module.h>
12 #include <linux/sort.h>
13 
14 static struct plt_entry __get_adrp_add_pair(u64 dst, u64 pc,
15 					    enum aarch64_insn_register reg)
16 {
17 	u32 adrp, add;
18 
19 	adrp = aarch64_insn_gen_adr(pc, dst, reg, AARCH64_INSN_ADR_TYPE_ADRP);
20 	add = aarch64_insn_gen_add_sub_imm(reg, reg, dst % SZ_4K,
21 					   AARCH64_INSN_VARIANT_64BIT,
22 					   AARCH64_INSN_ADSB_ADD);
23 
24 	return (struct plt_entry){ cpu_to_le32(adrp), cpu_to_le32(add) };
25 }
26 
27 struct plt_entry get_plt_entry(u64 dst, void *pc)
28 {
29 	struct plt_entry plt;
30 	static u32 br;
31 
32 	if (!br)
33 		br = aarch64_insn_gen_branch_reg(AARCH64_INSN_REG_16,
34 						 AARCH64_INSN_BRANCH_NOLINK);
35 
36 	plt = __get_adrp_add_pair(dst, (u64)pc, AARCH64_INSN_REG_16);
37 	plt.br = cpu_to_le32(br);
38 
39 	return plt;
40 }
41 
42 bool plt_entries_equal(const struct plt_entry *a, const struct plt_entry *b)
43 {
44 	u64 p, q;
45 
46 	/*
47 	 * Check whether both entries refer to the same target:
48 	 * do the cheapest checks first.
49 	 * If the 'add' or 'br' opcodes are different, then the target
50 	 * cannot be the same.
51 	 */
52 	if (a->add != b->add || a->br != b->br)
53 		return false;
54 
55 	p = ALIGN_DOWN((u64)a, SZ_4K);
56 	q = ALIGN_DOWN((u64)b, SZ_4K);
57 
58 	/*
59 	 * If the 'adrp' opcodes are the same then we just need to check
60 	 * that they refer to the same 4k region.
61 	 */
62 	if (a->adrp == b->adrp && p == q)
63 		return true;
64 
65 	return (p + aarch64_insn_adrp_get_offset(le32_to_cpu(a->adrp))) ==
66 	       (q + aarch64_insn_adrp_get_offset(le32_to_cpu(b->adrp)));
67 }
68 
69 static bool in_init(const struct module *mod, void *loc)
70 {
71 	return (u64)loc - (u64)mod->init_layout.base < mod->init_layout.size;
72 }
73 
74 u64 module_emit_plt_entry(struct module *mod, Elf64_Shdr *sechdrs,
75 			  void *loc, const Elf64_Rela *rela,
76 			  Elf64_Sym *sym)
77 {
78 	struct mod_plt_sec *pltsec = !in_init(mod, loc) ? &mod->arch.core :
79 							  &mod->arch.init;
80 	struct plt_entry *plt = (struct plt_entry *)sechdrs[pltsec->plt_shndx].sh_addr;
81 	int i = pltsec->plt_num_entries;
82 	int j = i - 1;
83 	u64 val = sym->st_value + rela->r_addend;
84 
85 	if (is_forbidden_offset_for_adrp(&plt[i].adrp))
86 		i++;
87 
88 	plt[i] = get_plt_entry(val, &plt[i]);
89 
90 	/*
91 	 * Check if the entry we just created is a duplicate. Given that the
92 	 * relocations are sorted, this will be the last entry we allocated.
93 	 * (if one exists).
94 	 */
95 	if (j >= 0 && plt_entries_equal(plt + i, plt + j))
96 		return (u64)&plt[j];
97 
98 	pltsec->plt_num_entries += i - j;
99 	if (WARN_ON(pltsec->plt_num_entries > pltsec->plt_max_entries))
100 		return 0;
101 
102 	return (u64)&plt[i];
103 }
104 
105 #ifdef CONFIG_ARM64_ERRATUM_843419
106 u64 module_emit_veneer_for_adrp(struct module *mod, Elf64_Shdr *sechdrs,
107 				void *loc, u64 val)
108 {
109 	struct mod_plt_sec *pltsec = !in_init(mod, loc) ? &mod->arch.core :
110 							  &mod->arch.init;
111 	struct plt_entry *plt = (struct plt_entry *)sechdrs[pltsec->plt_shndx].sh_addr;
112 	int i = pltsec->plt_num_entries++;
113 	u32 br;
114 	int rd;
115 
116 	if (WARN_ON(pltsec->plt_num_entries > pltsec->plt_max_entries))
117 		return 0;
118 
119 	if (is_forbidden_offset_for_adrp(&plt[i].adrp))
120 		i = pltsec->plt_num_entries++;
121 
122 	/* get the destination register of the ADRP instruction */
123 	rd = aarch64_insn_decode_register(AARCH64_INSN_REGTYPE_RD,
124 					  le32_to_cpup((__le32 *)loc));
125 
126 	br = aarch64_insn_gen_branch_imm((u64)&plt[i].br, (u64)loc + 4,
127 					 AARCH64_INSN_BRANCH_NOLINK);
128 
129 	plt[i] = __get_adrp_add_pair(val, (u64)&plt[i], rd);
130 	plt[i].br = cpu_to_le32(br);
131 
132 	return (u64)&plt[i];
133 }
134 #endif
135 
136 #define cmp_3way(a,b)	((a) < (b) ? -1 : (a) > (b))
137 
138 static int cmp_rela(const void *a, const void *b)
139 {
140 	const Elf64_Rela *x = a, *y = b;
141 	int i;
142 
143 	/* sort by type, symbol index and addend */
144 	i = cmp_3way(ELF64_R_TYPE(x->r_info), ELF64_R_TYPE(y->r_info));
145 	if (i == 0)
146 		i = cmp_3way(ELF64_R_SYM(x->r_info), ELF64_R_SYM(y->r_info));
147 	if (i == 0)
148 		i = cmp_3way(x->r_addend, y->r_addend);
149 	return i;
150 }
151 
152 static bool duplicate_rel(const Elf64_Rela *rela, int num)
153 {
154 	/*
155 	 * Entries are sorted by type, symbol index and addend. That means
156 	 * that, if a duplicate entry exists, it must be in the preceding
157 	 * slot.
158 	 */
159 	return num > 0 && cmp_rela(rela + num, rela + num - 1) == 0;
160 }
161 
162 static unsigned int count_plts(Elf64_Sym *syms, Elf64_Rela *rela, int num,
163 			       Elf64_Word dstidx, Elf_Shdr *dstsec)
164 {
165 	unsigned int ret = 0;
166 	Elf64_Sym *s;
167 	int i;
168 
169 	for (i = 0; i < num; i++) {
170 		u64 min_align;
171 
172 		switch (ELF64_R_TYPE(rela[i].r_info)) {
173 		case R_AARCH64_JUMP26:
174 		case R_AARCH64_CALL26:
175 			if (!IS_ENABLED(CONFIG_RANDOMIZE_BASE))
176 				break;
177 
178 			/*
179 			 * We only have to consider branch targets that resolve
180 			 * to symbols that are defined in a different section.
181 			 * This is not simply a heuristic, it is a fundamental
182 			 * limitation, since there is no guaranteed way to emit
183 			 * PLT entries sufficiently close to the branch if the
184 			 * section size exceeds the range of a branch
185 			 * instruction. So ignore relocations against defined
186 			 * symbols if they live in the same section as the
187 			 * relocation target.
188 			 */
189 			s = syms + ELF64_R_SYM(rela[i].r_info);
190 			if (s->st_shndx == dstidx)
191 				break;
192 
193 			/*
194 			 * Jump relocations with non-zero addends against
195 			 * undefined symbols are supported by the ELF spec, but
196 			 * do not occur in practice (e.g., 'jump n bytes past
197 			 * the entry point of undefined function symbol f').
198 			 * So we need to support them, but there is no need to
199 			 * take them into consideration when trying to optimize
200 			 * this code. So let's only check for duplicates when
201 			 * the addend is zero: this allows us to record the PLT
202 			 * entry address in the symbol table itself, rather than
203 			 * having to search the list for duplicates each time we
204 			 * emit one.
205 			 */
206 			if (rela[i].r_addend != 0 || !duplicate_rel(rela, i))
207 				ret++;
208 			break;
209 		case R_AARCH64_ADR_PREL_PG_HI21_NC:
210 		case R_AARCH64_ADR_PREL_PG_HI21:
211 			if (!IS_ENABLED(CONFIG_ARM64_ERRATUM_843419) ||
212 			    !cpus_have_const_cap(ARM64_WORKAROUND_843419))
213 				break;
214 
215 			/*
216 			 * Determine the minimal safe alignment for this ADRP
217 			 * instruction: the section alignment at which it is
218 			 * guaranteed not to appear at a vulnerable offset.
219 			 *
220 			 * This comes down to finding the least significant zero
221 			 * bit in bits [11:3] of the section offset, and
222 			 * increasing the section's alignment so that the
223 			 * resulting address of this instruction is guaranteed
224 			 * to equal the offset in that particular bit (as well
225 			 * as all less signficant bits). This ensures that the
226 			 * address modulo 4 KB != 0xfff8 or 0xfffc (which would
227 			 * have all ones in bits [11:3])
228 			 */
229 			min_align = 2ULL << ffz(rela[i].r_offset | 0x7);
230 
231 			/*
232 			 * Allocate veneer space for each ADRP that may appear
233 			 * at a vulnerable offset nonetheless. At relocation
234 			 * time, some of these will remain unused since some
235 			 * ADRP instructions can be patched to ADR instructions
236 			 * instead.
237 			 */
238 			if (min_align > SZ_4K)
239 				ret++;
240 			else
241 				dstsec->sh_addralign = max(dstsec->sh_addralign,
242 							   min_align);
243 			break;
244 		}
245 	}
246 
247 	if (IS_ENABLED(CONFIG_ARM64_ERRATUM_843419) &&
248 	    cpus_have_const_cap(ARM64_WORKAROUND_843419))
249 		/*
250 		 * Add some slack so we can skip PLT slots that may trigger
251 		 * the erratum due to the placement of the ADRP instruction.
252 		 */
253 		ret += DIV_ROUND_UP(ret, (SZ_4K / sizeof(struct plt_entry)));
254 
255 	return ret;
256 }
257 
258 int module_frob_arch_sections(Elf_Ehdr *ehdr, Elf_Shdr *sechdrs,
259 			      char *secstrings, struct module *mod)
260 {
261 	unsigned long core_plts = 0;
262 	unsigned long init_plts = 0;
263 	Elf64_Sym *syms = NULL;
264 	Elf_Shdr *pltsec, *tramp = NULL;
265 	int i;
266 
267 	/*
268 	 * Find the empty .plt section so we can expand it to store the PLT
269 	 * entries. Record the symtab address as well.
270 	 */
271 	for (i = 0; i < ehdr->e_shnum; i++) {
272 		if (!strcmp(secstrings + sechdrs[i].sh_name, ".plt"))
273 			mod->arch.core.plt_shndx = i;
274 		else if (!strcmp(secstrings + sechdrs[i].sh_name, ".init.plt"))
275 			mod->arch.init.plt_shndx = i;
276 		else if (IS_ENABLED(CONFIG_DYNAMIC_FTRACE) &&
277 			 !strcmp(secstrings + sechdrs[i].sh_name,
278 				 ".text.ftrace_trampoline"))
279 			tramp = sechdrs + i;
280 		else if (sechdrs[i].sh_type == SHT_SYMTAB)
281 			syms = (Elf64_Sym *)sechdrs[i].sh_addr;
282 	}
283 
284 	if (!mod->arch.core.plt_shndx || !mod->arch.init.plt_shndx) {
285 		pr_err("%s: module PLT section(s) missing\n", mod->name);
286 		return -ENOEXEC;
287 	}
288 	if (!syms) {
289 		pr_err("%s: module symtab section missing\n", mod->name);
290 		return -ENOEXEC;
291 	}
292 
293 	for (i = 0; i < ehdr->e_shnum; i++) {
294 		Elf64_Rela *rels = (void *)ehdr + sechdrs[i].sh_offset;
295 		int numrels = sechdrs[i].sh_size / sizeof(Elf64_Rela);
296 		Elf64_Shdr *dstsec = sechdrs + sechdrs[i].sh_info;
297 
298 		if (sechdrs[i].sh_type != SHT_RELA)
299 			continue;
300 
301 		/* ignore relocations that operate on non-exec sections */
302 		if (!(dstsec->sh_flags & SHF_EXECINSTR))
303 			continue;
304 
305 		/* sort by type, symbol index and addend */
306 		sort(rels, numrels, sizeof(Elf64_Rela), cmp_rela, NULL);
307 
308 		if (strncmp(secstrings + dstsec->sh_name, ".init", 5) != 0)
309 			core_plts += count_plts(syms, rels, numrels,
310 						sechdrs[i].sh_info, dstsec);
311 		else
312 			init_plts += count_plts(syms, rels, numrels,
313 						sechdrs[i].sh_info, dstsec);
314 	}
315 
316 	pltsec = sechdrs + mod->arch.core.plt_shndx;
317 	pltsec->sh_type = SHT_NOBITS;
318 	pltsec->sh_flags = SHF_EXECINSTR | SHF_ALLOC;
319 	pltsec->sh_addralign = L1_CACHE_BYTES;
320 	pltsec->sh_size = (core_plts  + 1) * sizeof(struct plt_entry);
321 	mod->arch.core.plt_num_entries = 0;
322 	mod->arch.core.plt_max_entries = core_plts;
323 
324 	pltsec = sechdrs + mod->arch.init.plt_shndx;
325 	pltsec->sh_type = SHT_NOBITS;
326 	pltsec->sh_flags = SHF_EXECINSTR | SHF_ALLOC;
327 	pltsec->sh_addralign = L1_CACHE_BYTES;
328 	pltsec->sh_size = (init_plts + 1) * sizeof(struct plt_entry);
329 	mod->arch.init.plt_num_entries = 0;
330 	mod->arch.init.plt_max_entries = init_plts;
331 
332 	if (tramp) {
333 		tramp->sh_type = SHT_NOBITS;
334 		tramp->sh_flags = SHF_EXECINSTR | SHF_ALLOC;
335 		tramp->sh_addralign = __alignof__(struct plt_entry);
336 		tramp->sh_size = sizeof(struct plt_entry);
337 	}
338 
339 	return 0;
340 }
341