File: memcall_test.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 (90 lines) | stat: -rw-r--r-- 2,029 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
89
90
package memcall

import (
	"fmt"
	"strings"
	"testing"
)

func TestCycle(t *testing.T) {
	buffer, err := Alloc(32)
	if err != nil {
		t.Error(err)
	}

	if len(buffer) != 32 || cap(buffer) != 32 {
		t.Error("allocation has invalid size")
	}
	for i := range buffer {
		if buffer[i] != 0 {
			t.Error("allocated memory not zeroed:", buffer)
		}
	}

	if err := Lock(buffer); err != nil {
		t.Error(err)
	}

	for i := range buffer {
		buffer[i] = 1
		if buffer[i] != 1 {
			t.Error("read back data different to what was written")
		}
	}

	if err := Unlock(buffer); err != nil {
		t.Error(err)
	}
	if err := Free(buffer); err != nil {
		t.Error(err)
	}
	if err := DisableCoreDumps(); err != nil {
		t.Error(err)
	}
}

func TestProtect(t *testing.T) {
	buffer, _ := Alloc(32)
	if err := Protect(buffer, ReadWrite()); err != nil {
		t.Error(err)
	}
	if err := Protect(buffer, ReadOnly()); err != nil {
		t.Error(err)
	}
	if err := Protect(buffer, NoAccess()); err != nil {
		t.Error(err)
	}
	if err := Protect(buffer, MemoryProtectionFlag{4}); err.Error() != ErrInvalidFlag {
		t.Error("expected error")
	}
	Free(buffer)
}

func TestProtFlags(t *testing.T) {
	if NoAccess().flag != 1 {
		t.Error("NoAccess value is", NoAccess().flag)
	}
	if ReadOnly().flag != 2 {
		t.Error("ReadOnly value is", ReadOnly().flag)
	}
	if ReadWrite().flag != 6 {
		t.Error("ReadWrite value is", ReadWrite().flag)
	}
}

func TestGetStartPtr(t *testing.T) {
	str := fmt.Sprintf("<memcall> could not deallocate %p", _getStartPtr(nil))
	if !strings.HasPrefix(str, "<memcall> could not deallocate") {
		t.Error("Formatted start pointer error is", str)
	}

	str = fmt.Sprintf("<memcall> could not deallocate %p", _getStartPtr([]byte{}))
	if !strings.HasPrefix(str, "<memcall> could not deallocate") {
		t.Error("Formatted start pointer error is", str)
	}

	str = fmt.Sprintf("<memcall> could not deallocate %p", _getStartPtr([]byte{1, 2, 3}))
	if !strings.HasPrefix(str, "<memcall> could not deallocate") {
		t.Error("Formatted start pointer error is", str)
	}
}