File: memcall_windows.go

package info (click to toggle)
golang-github-awnumar-memcall 0.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 148 kB
  • sloc: makefile: 2
file content (88 lines) | stat: -rw-r--r-- 2,363 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//go:build windows

package memcall

import (
	"errors"
	"fmt"

	"golang.org/x/sys/windows"
)

// Lock is a wrapper for windows.VirtualLock()
func Lock(b []byte) error {
	if err := windows.VirtualLock(_getPtr(b), uintptr(len(b))); err != nil {
		return fmt.Errorf("<memcall> could not acquire lock on %p, limit reached? [Err: %s]", _getStartPtr(b), err)
	}

	return nil
}

// Unlock is a wrapper for windows.VirtualUnlock()
func Unlock(b []byte) error {
	if err := windows.VirtualUnlock(_getPtr(b), uintptr(len(b))); err != nil {
		return fmt.Errorf("<memcall> could not free lock on %p [Err: %s]", _getStartPtr(b), err)
	}

	return nil
}

// Alloc allocates a byte slice of length n and returns it.
func Alloc(n int) ([]byte, error) {
	// Allocate the memory.
	ptr, err := windows.VirtualAlloc(_zero, uintptr(n), 0x1000|0x2000, 0x4)
	if err != nil {
		return nil, fmt.Errorf("<memcall> could not allocate [Err: %s]", err)
	}

	// Convert this pointer to a slice.
	b := _getBytes(ptr, n, n)

	// Wipe it just in case there is some remnant data.
	wipe(b)

	// Return the allocated memory.
	return b, nil
}

// Free deallocates the byte slice specified.
func Free(b []byte) error {
	// Make the memory region readable and writable.
	if err := Protect(b, ReadWrite()); err != nil {
		return err
	}

	// Wipe the memory region in case of remnant data.
	wipe(b)

	// Free the memory back to the kernel.
	if err := windows.VirtualFree(_getPtr(b), uintptr(0), 0x8000); err != nil {
		return fmt.Errorf("<memcall> could not deallocate %p [Err: %s]", _getStartPtr(b), err)
	}

	return nil
}

// Protect modifies the memory protection flags for a specified byte slice.
func Protect(b []byte, mpf MemoryProtectionFlag) error {
	var prot int
	if mpf.flag == ReadWrite().flag {
		prot = 0x4 // PAGE_READWRITE
	} else if mpf.flag == ReadOnly().flag {
		prot = 0x2 // PAGE_READ
	} else if mpf.flag == NoAccess().flag {
		prot = 0x1 // PAGE_NOACCESS
	} else {
		return errors.New(ErrInvalidFlag)
	}

	var oldProtect uint32
	if err := windows.VirtualProtect(_getPtr(b), uintptr(len(b)), uint32(prot), &oldProtect); err != nil {
		return fmt.Errorf("<memcall> could not set %d on %p [Err: %s]", prot, _getStartPtr(b), err)
	}

	return nil
}

// DisableCoreDumps is included for compatibility reasons. On windows it is a no-op function.
func DisableCoreDumps() error { return nil }