]> git.proxmox.com Git - mirror_edk2.git/blob - MdePkg/Library/BaseLib/X86PatchInstruction.c
MdePkg/BaseLib: Add bit field population calculating methods
[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 This program and the accompanying materials are licensed and made available
8 under the terms and conditions of the BSD License which accompanies this
9 distribution. The full text of the license may be found at
10 http://opensource.org/licenses/bsd-license.php.
11
12 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT
13 WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
14 **/
15
16 #include "BaseLibInternals.h"
17
18 /**
19 Patch the immediate operand of an IA32 or X64 instruction such that the byte,
20 word, dword or qword operand is encoded at the end of the instruction's
21 binary representation.
22
23 This function should be used to update object code that was compiled with
24 NASM from assembly source code. Example:
25
26 NASM source code:
27
28 mov eax, strict dword 0 ; the imm32 zero operand will be patched
29 ASM_PFX(gPatchCr3):
30 mov cr3, eax
31
32 C source code:
33
34 X86_ASSEMBLY_PATCH_LABEL gPatchCr3;
35 PatchInstructionX86 (gPatchCr3, AsmReadCr3 (), 4);
36
37 @param[out] InstructionEnd Pointer right past the instruction to patch. The
38 immediate operand to patch is expected to
39 comprise the trailing bytes of the instruction.
40 If InstructionEnd is closer to address 0 than
41 ValueSize permits, then ASSERT().
42
43 @param[in] PatchValue The constant to write to the immediate operand.
44 The caller is responsible for ensuring that
45 PatchValue can be represented in the byte, word,
46 dword or qword operand (as indicated through
47 ValueSize); otherwise ASSERT().
48
49 @param[in] ValueSize The size of the operand in bytes; must be 1, 2,
50 4, or 8. ASSERT() otherwise.
51 **/
52 VOID
53 EFIAPI
54 PatchInstructionX86 (
55 OUT X86_ASSEMBLY_PATCH_LABEL *InstructionEnd,
56 IN UINT64 PatchValue,
57 IN UINTN ValueSize
58 )
59 {
60 //
61 // The equality ((UINTN)InstructionEnd == ValueSize) would assume a zero-size
62 // instruction at address 0; forbid it.
63 //
64 ASSERT ((UINTN)InstructionEnd > ValueSize);
65
66 switch (ValueSize) {
67 case 1:
68 ASSERT (PatchValue <= MAX_UINT8);
69 *((UINT8 *)(UINTN)InstructionEnd - 1) = (UINT8)PatchValue;
70 break;
71
72 case 2:
73 ASSERT (PatchValue <= MAX_UINT16);
74 WriteUnaligned16 ((UINT16 *)(UINTN)InstructionEnd - 1, (UINT16)PatchValue);
75 break;
76
77 case 4:
78 ASSERT (PatchValue <= MAX_UINT32);
79 WriteUnaligned32 ((UINT32 *)(UINTN)InstructionEnd - 1, (UINT32)PatchValue);
80 break;
81
82 case 8:
83 WriteUnaligned64 ((UINT64 *)(UINTN)InstructionEnd - 1, PatchValue);
84 break;
85
86 default:
87 ASSERT (FALSE);
88 }
89 }