mmap_windows.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //go:build windows
  2. // +build windows
  3. // build
  4. /*
  5. * Copyright 2021 ByteDance Inc.
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. */
  19. package loader
  20. import (
  21. `syscall`
  22. `unsafe`
  23. )
  24. const (
  25. MEM_COMMIT = 0x00001000
  26. MEM_RESERVE = 0x00002000
  27. )
  28. var (
  29. libKernel32 = syscall.NewLazyDLL("KERNEL32.DLL")
  30. libKernel32_VirtualAlloc = libKernel32.NewProc("VirtualAlloc")
  31. libKernel32_VirtualProtect = libKernel32.NewProc("VirtualProtect")
  32. )
  33. func mmap(nb int) uintptr {
  34. addr, err := winapi_VirtualAlloc(0, nb, MEM_COMMIT|MEM_RESERVE, syscall.PAGE_READWRITE)
  35. if err != nil {
  36. panic(err)
  37. }
  38. return addr
  39. }
  40. func mprotect(p uintptr, nb int) (oldProtect int) {
  41. err := winapi_VirtualProtect(p, nb, syscall.PAGE_EXECUTE_READ, &oldProtect)
  42. if err != nil {
  43. panic(err)
  44. }
  45. return
  46. }
  47. // winapi_VirtualAlloc allocate memory
  48. // Doc: https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc
  49. func winapi_VirtualAlloc(lpAddr uintptr, dwSize int, flAllocationType int, flProtect int) (uintptr, error) {
  50. r1, _, err := libKernel32_VirtualAlloc.Call(
  51. lpAddr,
  52. uintptr(dwSize),
  53. uintptr(flAllocationType),
  54. uintptr(flProtect),
  55. )
  56. if r1 == 0 {
  57. return 0, err
  58. }
  59. return r1, nil
  60. }
  61. // winapi_VirtualProtect change memory protection
  62. // Doc: https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect
  63. func winapi_VirtualProtect(lpAddr uintptr, dwSize int, flNewProtect int, lpflOldProtect *int) error {
  64. r1, _, err := libKernel32_VirtualProtect.Call(
  65. lpAddr,
  66. uintptr(dwSize),
  67. uintptr(flNewProtect),
  68. uintptr(unsafe.Pointer(lpflOldProtect)),
  69. )
  70. if r1 == 0 {
  71. return err
  72. }
  73. return nil
  74. }