github.com/bytedance/mockey@v1.2.10/internal/monkey/mem/prot/protect_windows.go (about) 1 /* 2 * Copyright 2022 ByteDance Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package prot 18 19 import ( 20 "reflect" 21 "syscall" 22 23 "github.com/bytedance/mockey/internal/monkey/common" 24 ) 25 26 const ( 27 protectRWX = 0x40 28 ) 29 30 var procVirtualProtect = syscall.NewLazyDLL("kernel32.dll").NewProc("VirtualProtect") 31 32 func MProtectRWX(addr uintptr) error { 33 return mProtectPage(common.PageOf(addr), protectRWX) 34 } 35 36 func mProtectRX(b []byte) error { 37 return MProtectRWX(common.PtrOf(b)) 38 } 39 40 func mProtectPage(page, prot uintptr) error { 41 var ori uint 42 return virtualProtect(page, common.PageSize(), uint32(prot), common.PtrAt(reflect.ValueOf(&ori))) 43 } 44 45 func virtualProtect(lpAddress uintptr, dwSize int, flNewProtect uint32, lpflOldProtect uintptr) error { 46 ret, _, _ := procVirtualProtect.Call(lpAddress, uintptr(dwSize), uintptr(flNewProtect), lpflOldProtect) 47 if ret == 0 { 48 return syscall.GetLastError() 49 } 50 return nil 51 }