1/*-
2 * Copyright (c) 2018 The FreeBSD Foundation
3 *
4 * This software was developed by Konstantin Belousov <kib@FreeBSD.org>
5 * under sponsorship from the FreeBSD Foundation.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD$");
31
32#include <machine/specialreg.h>
33#include <machine/cpufunc.h>
34
35static void
36crt1_handle_rel(const Elf_Rel *r)
37{
38	Elf_Addr *where, target;
39	u_int cpuid_supported, p[4];
40	uint32_t cpu_feature, cpu_feature2;
41	uint32_t cpu_stdext_feature, cpu_stdext_feature2;
42
43	__asm __volatile(
44	    "	pushfl\n"
45	    "	popl	%%eax\n"
46	    "	movl    %%eax,%%ecx\n"
47	    "	xorl    $0x200000,%%eax\n"
48	    "	pushl	%%eax\n"
49	    "	popfl\n"
50	    "	pushfl\n"
51	    "	popl    %%eax\n"
52	    "	xorl    %%eax,%%ecx\n"
53	    "	je	1f\n"
54	    "	movl	$1,%0\n"
55	    "	jmp	2f\n"
56	    "1:	movl	$0,%0\n"
57	    "2:\n"
58	    : "=r" (cpuid_supported) : : "eax", "ecx", "cc");
59	if (cpuid_supported) {
60		do_cpuid(1, p);
61		cpu_feature = p[3];
62		cpu_feature2 = p[2];
63		do_cpuid(0, p);
64		if (p[0] >= 7) {
65			cpuid_count(7, 0, p);
66			cpu_stdext_feature = p[1];
67			cpu_stdext_feature2 = p[2];
68		} else {
69			cpu_stdext_feature = 0;
70			cpu_stdext_feature2 = 0;
71		}
72	} else {
73		cpu_feature = 0;
74		cpu_feature2 = 0;
75		cpu_stdext_feature = 0;
76		cpu_stdext_feature2 = 0;
77	}
78
79	switch (ELF_R_TYPE(r->r_info)) {
80	case R_386_IRELATIVE:
81		where = (Elf_Addr *)r->r_offset;
82		target = ((Elf_Addr (*)(uint32_t, uint32_t, uint32_t,
83		    uint32_t))*where)(cpu_feature, cpu_feature2,
84		    cpu_stdext_feature, cpu_stdext_feature2);
85		*where = target;
86		break;
87	}
88}
89