]> git.proxmox.com Git - mirror_edk2.git/blob - MdePkg/Library/BaseLib/X86PatchInstruction.c
UefiCpuPkg: Move AsmRelocateApLoopStart from Mpfuncs.nasm to AmdSev.nasm
[mirror_edk2.git] / MdePkg / Library / BaseLib / X86PatchInstruction.c
1 /** @file
2 IA-32/x64 PatchInstructionX86()
3
4 Copyright (C) 2018, Intel Corporation. All rights reserved.<BR>
5 Copyright (C) 2018, Red Hat, Inc.
6
7 SPDX-License-Identifier: BSD-2-Clause-Patent
8 **/
9
10 #include "BaseLibInternals.h"
11
12 /**
13 Patch the immediate operand of an IA32 or X64 instruction such that the byte,
14 word, dword or qword operand is encoded at the end of the instruction's
15 binary representation.
16
17 This function should be used to update object code that was compiled with
18 NASM from assembly source code. Example:
19
20 NASM source code:
21
22 mov eax, strict dword 0 ; the imm32 zero operand will be patched
23 ASM_PFX(gPatchCr3):
24 mov cr3, eax
25
26 C source code:
27
28 X86_ASSEMBLY_PATCH_LABEL gPatchCr3;
29 PatchInstructionX86 (gPatchCr3, AsmReadCr3 (), 4);
30
31 @param[out] InstructionEnd Pointer right past the instruction to patch. The
32 immediate operand to patch is expected to
33 comprise the trailing bytes of the instruction.
34 If InstructionEnd is closer to address 0 than
35 ValueSize permits, then ASSERT().
36
37 @param[in] PatchValue The constant to write to the immediate operand.
38 The caller is responsible for ensuring that
39 PatchValue can be represented in the byte, word,
40 dword or qword operand (as indicated through
41 ValueSize); otherwise ASSERT().
42
43 @param[in] ValueSize The size of the operand in bytes; must be 1, 2,
44 4, or 8. ASSERT() otherwise.
45 **/
46 VOID
47 EFIAPI
48 PatchInstructionX86 (
49 OUT X86_ASSEMBLY_PATCH_LABEL *InstructionEnd,
50 IN UINT64 PatchValue,
51 IN UINTN ValueSize
52 )
53 {
54 //
55 // The equality ((UINTN)InstructionEnd == ValueSize) would assume a zero-size
56 // instruction at address 0; forbid it.
57 //
58 ASSERT ((UINTN)InstructionEnd > ValueSize);
59
60 switch (ValueSize) {
61 case 1:
62 ASSERT (PatchValue <= MAX_UINT8);
63 *((UINT8 *)(UINTN)InstructionEnd - 1) = (UINT8)PatchValue;
64 break;
65
66 case 2:
67 ASSERT (PatchValue <= MAX_UINT16);
68 WriteUnaligned16 ((UINT16 *)(UINTN)InstructionEnd - 1, (UINT16)PatchValue);
69 break;
70
71 case 4:
72 ASSERT (PatchValue <= MAX_UINT32);
73 WriteUnaligned32 ((UINT32 *)(UINTN)InstructionEnd - 1, (UINT32)PatchValue);
74 break;
75
76 case 8:
77 WriteUnaligned64 ((UINT64 *)(UINTN)InstructionEnd - 1, PatchValue);
78 break;
79
80 default:
81 ASSERT (FALSE);
82 }
83 }