ADAPT-Chase commited on
Commit
96c56c2
·
verified ·
1 Parent(s): 96302ab

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +6 -0
  2. platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/export_test.go +11 -0
  3. platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/key.go +168 -0
  4. platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/mksyscall.go +9 -0
  5. platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/registry_test.go +666 -0
  6. platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/syscall.go +27 -0
  7. platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/value.go +369 -0
  8. platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/zsyscall_windows.go +107 -0
  9. platform/dbops/binaries/go/go/src/internal/syscall/windows/syscall_windows.go +445 -0
  10. platform/dbops/binaries/go/go/src/internal/syscall/windows/sysdll/sysdll.go +30 -0
  11. platform/dbops/binaries/go/go/src/internal/syscall/windows/zsyscall_windows.go +436 -0
  12. platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_10_good +0 -0
  13. platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_11_good +0 -0
  14. platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_19_good +0 -0
  15. platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_21_good +0 -0
  16. platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_5_good +0 -0
  17. platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_7_good +0 -0
  18. platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_9_good +0 -0
  19. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_10_good +3 -0
  20. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_11_good +3 -0
  21. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_19_good +3 -0
  22. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_21_good +3 -0
  23. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_5_good +0 -0
  24. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_5_unordered +0 -0
  25. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_7_good +3 -0
  26. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_9_good +3 -0
  27. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_10_good +0 -0
  28. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_11_good +0 -0
  29. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_19_good +0 -0
  30. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_21_good +0 -0
  31. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_5_good +0 -0
  32. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_7_good +0 -0
  33. platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_9_good +0 -0
  34. platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_11_good +0 -0
  35. platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_19_good +0 -0
  36. platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_21_good +0 -0
  37. platform/dbops/binaries/go/go/src/internal/trace/traceviewer/emitter.go +813 -0
  38. platform/dbops/binaries/go/go/src/internal/trace/traceviewer/format/format.go +79 -0
  39. platform/dbops/binaries/go/go/src/internal/trace/traceviewer/histogram.go +86 -0
  40. platform/dbops/binaries/go/go/src/internal/trace/traceviewer/http.go +422 -0
  41. platform/dbops/binaries/go/go/src/internal/trace/traceviewer/mmu.go +414 -0
  42. platform/dbops/binaries/go/go/src/internal/trace/traceviewer/pprof.go +150 -0
  43. platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/README.md +106 -0
  44. platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/trace_viewer_full.html +0 -0
  45. platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/webcomponents.min.js +0 -0
  46. platform/dbops/binaries/go/go/src/internal/trace/v2/base.go +261 -0
  47. platform/dbops/binaries/go/go/src/internal/trace/v2/batch.go +97 -0
  48. platform/dbops/binaries/go/go/src/internal/trace/v2/batchcursor.go +174 -0
  49. platform/dbops/binaries/go/go/src/internal/trace/v2/batchcursor_test.go +126 -0
  50. platform/dbops/binaries/go/go/src/internal/trace/v2/event.go +780 -0
.gitattributes CHANGED
@@ -3156,3 +3156,9 @@ platform/dbops/binaries/go/go/src/cmd/compile/default.pgo filter=lfs diff=lfs me
3156
  platform/dbops/binaries/go/go/src/crypto/internal/boring/syso/goboringcrypto_linux_amd64.syso filter=lfs diff=lfs merge=lfs -text
3157
  platform/dbops/binaries/go/go/src/crypto/internal/boring/syso/goboringcrypto_linux_arm64.syso filter=lfs diff=lfs merge=lfs -text
3158
  platform/dbops/binaries/go/go/src/debug/pe/testdata/gcc-amd64-mingw-exec filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
3156
  platform/dbops/binaries/go/go/src/crypto/internal/boring/syso/goboringcrypto_linux_amd64.syso filter=lfs diff=lfs merge=lfs -text
3157
  platform/dbops/binaries/go/go/src/crypto/internal/boring/syso/goboringcrypto_linux_arm64.syso filter=lfs diff=lfs merge=lfs -text
3158
  platform/dbops/binaries/go/go/src/debug/pe/testdata/gcc-amd64-mingw-exec filter=lfs diff=lfs merge=lfs -text
3159
+ platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_10_good filter=lfs diff=lfs merge=lfs -text
3160
+ platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_11_good filter=lfs diff=lfs merge=lfs -text
3161
+ platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_19_good filter=lfs diff=lfs merge=lfs -text
3162
+ platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_21_good filter=lfs diff=lfs merge=lfs -text
3163
+ platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_7_good filter=lfs diff=lfs merge=lfs -text
3164
+ platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_9_good filter=lfs diff=lfs merge=lfs -text
platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/export_test.go ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build windows
6
+
7
+ package registry
8
+
9
+ func (k Key) SetValue(name string, valtype uint32, data []byte) error {
10
+ return k.setValue(name, valtype, data)
11
+ }
platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/key.go ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build windows
6
+
7
+ // Package registry provides access to the Windows registry.
8
+ //
9
+ // Here is a simple example, opening a registry key and reading a string value from it.
10
+ //
11
+ // k, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion`, registry.QUERY_VALUE)
12
+ // if err != nil {
13
+ // log.Fatal(err)
14
+ // }
15
+ // defer k.Close()
16
+ //
17
+ // s, _, err := k.GetStringValue("SystemRoot")
18
+ // if err != nil {
19
+ // log.Fatal(err)
20
+ // }
21
+ // fmt.Printf("Windows system root is %q\n", s)
22
+ //
23
+ // NOTE: This package is a copy of golang.org/x/sys/windows/registry
24
+ // with KeyInfo.ModTime removed to prevent dependency cycles.
25
+ package registry
26
+
27
+ import (
28
+ "runtime"
29
+ "syscall"
30
+ )
31
+
32
+ const (
33
+ // Registry key security and access rights.
34
+ // See https://learn.microsoft.com/en-us/windows/win32/sysinfo/registry-key-security-and-access-rights
35
+ // for details.
36
+ ALL_ACCESS = 0xf003f
37
+ CREATE_LINK = 0x00020
38
+ CREATE_SUB_KEY = 0x00004
39
+ ENUMERATE_SUB_KEYS = 0x00008
40
+ EXECUTE = 0x20019
41
+ NOTIFY = 0x00010
42
+ QUERY_VALUE = 0x00001
43
+ READ = 0x20019
44
+ SET_VALUE = 0x00002
45
+ WOW64_32KEY = 0x00200
46
+ WOW64_64KEY = 0x00100
47
+ WRITE = 0x20006
48
+ )
49
+
50
+ // Key is a handle to an open Windows registry key.
51
+ // Keys can be obtained by calling OpenKey; there are
52
+ // also some predefined root keys such as CURRENT_USER.
53
+ // Keys can be used directly in the Windows API.
54
+ type Key syscall.Handle
55
+
56
+ const (
57
+ // Windows defines some predefined root keys that are always open.
58
+ // An application can use these keys as entry points to the registry.
59
+ // Normally these keys are used in OpenKey to open new keys,
60
+ // but they can also be used anywhere a Key is required.
61
+ CLASSES_ROOT = Key(syscall.HKEY_CLASSES_ROOT)
62
+ CURRENT_USER = Key(syscall.HKEY_CURRENT_USER)
63
+ LOCAL_MACHINE = Key(syscall.HKEY_LOCAL_MACHINE)
64
+ USERS = Key(syscall.HKEY_USERS)
65
+ CURRENT_CONFIG = Key(syscall.HKEY_CURRENT_CONFIG)
66
+ )
67
+
68
+ // Close closes open key k.
69
+ func (k Key) Close() error {
70
+ return syscall.RegCloseKey(syscall.Handle(k))
71
+ }
72
+
73
+ // OpenKey opens a new key with path name relative to key k.
74
+ // It accepts any open key, including CURRENT_USER and others,
75
+ // and returns the new key and an error.
76
+ // The access parameter specifies desired access rights to the
77
+ // key to be opened.
78
+ func OpenKey(k Key, path string, access uint32) (Key, error) {
79
+ p, err := syscall.UTF16PtrFromString(path)
80
+ if err != nil {
81
+ return 0, err
82
+ }
83
+ var subkey syscall.Handle
84
+ err = syscall.RegOpenKeyEx(syscall.Handle(k), p, 0, access, &subkey)
85
+ if err != nil {
86
+ return 0, err
87
+ }
88
+ return Key(subkey), nil
89
+ }
90
+
91
+ // ReadSubKeyNames returns the names of subkeys of key k.
92
+ func (k Key) ReadSubKeyNames() ([]string, error) {
93
+ // RegEnumKeyEx must be called repeatedly and to completion.
94
+ // During this time, this goroutine cannot migrate away from
95
+ // its current thread. See #49320.
96
+ runtime.LockOSThread()
97
+ defer runtime.UnlockOSThread()
98
+
99
+ names := make([]string, 0)
100
+ // Registry key size limit is 255 bytes and described there:
101
+ // https://learn.microsoft.com/en-us/windows/win32/sysinfo/registry-element-size-limits
102
+ buf := make([]uint16, 256) //plus extra room for terminating zero byte
103
+ loopItems:
104
+ for i := uint32(0); ; i++ {
105
+ l := uint32(len(buf))
106
+ for {
107
+ err := syscall.RegEnumKeyEx(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil)
108
+ if err == nil {
109
+ break
110
+ }
111
+ if err == syscall.ERROR_MORE_DATA {
112
+ // Double buffer size and try again.
113
+ l = uint32(2 * len(buf))
114
+ buf = make([]uint16, l)
115
+ continue
116
+ }
117
+ if err == _ERROR_NO_MORE_ITEMS {
118
+ break loopItems
119
+ }
120
+ return names, err
121
+ }
122
+ names = append(names, syscall.UTF16ToString(buf[:l]))
123
+ }
124
+ return names, nil
125
+ }
126
+
127
+ // CreateKey creates a key named path under open key k.
128
+ // CreateKey returns the new key and a boolean flag that reports
129
+ // whether the key already existed.
130
+ // The access parameter specifies the access rights for the key
131
+ // to be created.
132
+ func CreateKey(k Key, path string, access uint32) (newk Key, openedExisting bool, err error) {
133
+ var h syscall.Handle
134
+ var d uint32
135
+ err = regCreateKeyEx(syscall.Handle(k), syscall.StringToUTF16Ptr(path),
136
+ 0, nil, _REG_OPTION_NON_VOLATILE, access, nil, &h, &d)
137
+ if err != nil {
138
+ return 0, false, err
139
+ }
140
+ return Key(h), d == _REG_OPENED_EXISTING_KEY, nil
141
+ }
142
+
143
+ // DeleteKey deletes the subkey path of key k and its values.
144
+ func DeleteKey(k Key, path string) error {
145
+ return regDeleteKey(syscall.Handle(k), syscall.StringToUTF16Ptr(path))
146
+ }
147
+
148
+ // A KeyInfo describes the statistics of a key. It is returned by Stat.
149
+ type KeyInfo struct {
150
+ SubKeyCount uint32
151
+ MaxSubKeyLen uint32 // size of the key's subkey with the longest name, in Unicode characters, not including the terminating zero byte
152
+ ValueCount uint32
153
+ MaxValueNameLen uint32 // size of the key's longest value name, in Unicode characters, not including the terminating zero byte
154
+ MaxValueLen uint32 // longest data component among the key's values, in bytes
155
+ lastWriteTime syscall.Filetime
156
+ }
157
+
158
+ // Stat retrieves information about the open key k.
159
+ func (k Key) Stat() (*KeyInfo, error) {
160
+ var ki KeyInfo
161
+ err := syscall.RegQueryInfoKey(syscall.Handle(k), nil, nil, nil,
162
+ &ki.SubKeyCount, &ki.MaxSubKeyLen, nil, &ki.ValueCount,
163
+ &ki.MaxValueNameLen, &ki.MaxValueLen, nil, &ki.lastWriteTime)
164
+ if err != nil {
165
+ return nil, err
166
+ }
167
+ return &ki, nil
168
+ }
platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/mksyscall.go ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build generate
6
+
7
+ package registry
8
+
9
+ //go:generate go run ../../../../syscall/mksyscall_windows.go -output zsyscall_windows.go syscall.go
platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/registry_test.go ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build windows
6
+
7
+ package registry_test
8
+
9
+ import (
10
+ "bytes"
11
+ "crypto/rand"
12
+ "os"
13
+ "syscall"
14
+ "testing"
15
+ "unsafe"
16
+
17
+ "internal/syscall/windows/registry"
18
+ )
19
+
20
+ func randKeyName(prefix string) string {
21
+ const numbers = "0123456789"
22
+ buf := make([]byte, 10)
23
+ rand.Read(buf)
24
+ for i, b := range buf {
25
+ buf[i] = numbers[b%byte(len(numbers))]
26
+ }
27
+ return prefix + string(buf)
28
+ }
29
+
30
+ func TestReadSubKeyNames(t *testing.T) {
31
+ k, err := registry.OpenKey(registry.CLASSES_ROOT, "TypeLib", registry.ENUMERATE_SUB_KEYS)
32
+ if err != nil {
33
+ t.Fatal(err)
34
+ }
35
+ defer k.Close()
36
+
37
+ names, err := k.ReadSubKeyNames()
38
+ if err != nil {
39
+ t.Fatal(err)
40
+ }
41
+ var foundStdOle bool
42
+ for _, name := range names {
43
+ // Every PC has "stdole 2.0 OLE Automation" library installed.
44
+ if name == "{00020430-0000-0000-C000-000000000046}" {
45
+ foundStdOle = true
46
+ }
47
+ }
48
+ if !foundStdOle {
49
+ t.Fatal("could not find stdole 2.0 OLE Automation")
50
+ }
51
+ }
52
+
53
+ func TestCreateOpenDeleteKey(t *testing.T) {
54
+ k, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE)
55
+ if err != nil {
56
+ t.Fatal(err)
57
+ }
58
+ defer k.Close()
59
+
60
+ testKName := randKeyName("TestCreateOpenDeleteKey_")
61
+
62
+ testK, exist, err := registry.CreateKey(k, testKName, registry.CREATE_SUB_KEY)
63
+ if err != nil {
64
+ t.Fatal(err)
65
+ }
66
+ defer testK.Close()
67
+
68
+ if exist {
69
+ t.Fatalf("key %q already exists", testKName)
70
+ }
71
+
72
+ testKAgain, exist, err := registry.CreateKey(k, testKName, registry.CREATE_SUB_KEY)
73
+ if err != nil {
74
+ t.Fatal(err)
75
+ }
76
+ defer testKAgain.Close()
77
+
78
+ if !exist {
79
+ t.Fatalf("key %q should already exist", testKName)
80
+ }
81
+
82
+ testKOpened, err := registry.OpenKey(k, testKName, registry.ENUMERATE_SUB_KEYS)
83
+ if err != nil {
84
+ t.Fatal(err)
85
+ }
86
+ defer testKOpened.Close()
87
+
88
+ err = registry.DeleteKey(k, testKName)
89
+ if err != nil {
90
+ t.Fatal(err)
91
+ }
92
+
93
+ testKOpenedAgain, err := registry.OpenKey(k, testKName, registry.ENUMERATE_SUB_KEYS)
94
+ if err == nil {
95
+ defer testKOpenedAgain.Close()
96
+ t.Fatalf("key %q should already been deleted", testKName)
97
+ }
98
+ if err != registry.ErrNotExist {
99
+ t.Fatalf(`unexpected error ("not exist" expected): %v`, err)
100
+ }
101
+ }
102
+
103
+ func equalStringSlice(a, b []string) bool {
104
+ if len(a) != len(b) {
105
+ return false
106
+ }
107
+ if a == nil {
108
+ return true
109
+ }
110
+ for i := range a {
111
+ if a[i] != b[i] {
112
+ return false
113
+ }
114
+ }
115
+ return true
116
+ }
117
+
118
+ type ValueTest struct {
119
+ Type uint32
120
+ Name string
121
+ Value any
122
+ WillFail bool
123
+ }
124
+
125
+ var ValueTests = []ValueTest{
126
+ {Type: registry.SZ, Name: "String1", Value: ""},
127
+ {Type: registry.SZ, Name: "String2", Value: "\000", WillFail: true},
128
+ {Type: registry.SZ, Name: "String3", Value: "Hello World"},
129
+ {Type: registry.SZ, Name: "String4", Value: "Hello World\000", WillFail: true},
130
+ {Type: registry.EXPAND_SZ, Name: "ExpString1", Value: ""},
131
+ {Type: registry.EXPAND_SZ, Name: "ExpString2", Value: "\000", WillFail: true},
132
+ {Type: registry.EXPAND_SZ, Name: "ExpString3", Value: "Hello World"},
133
+ {Type: registry.EXPAND_SZ, Name: "ExpString4", Value: "Hello\000World", WillFail: true},
134
+ {Type: registry.EXPAND_SZ, Name: "ExpString5", Value: "%PATH%"},
135
+ {Type: registry.EXPAND_SZ, Name: "ExpString6", Value: "%NO_SUCH_VARIABLE%"},
136
+ {Type: registry.EXPAND_SZ, Name: "ExpString7", Value: "%PATH%;."},
137
+ {Type: registry.BINARY, Name: "Binary1", Value: []byte{}},
138
+ {Type: registry.BINARY, Name: "Binary2", Value: []byte{1, 2, 3}},
139
+ {Type: registry.BINARY, Name: "Binary3", Value: []byte{3, 2, 1, 0, 1, 2, 3}},
140
+ {Type: registry.DWORD, Name: "Dword1", Value: uint64(0)},
141
+ {Type: registry.DWORD, Name: "Dword2", Value: uint64(1)},
142
+ {Type: registry.DWORD, Name: "Dword3", Value: uint64(0xff)},
143
+ {Type: registry.DWORD, Name: "Dword4", Value: uint64(0xffff)},
144
+ {Type: registry.QWORD, Name: "Qword1", Value: uint64(0)},
145
+ {Type: registry.QWORD, Name: "Qword2", Value: uint64(1)},
146
+ {Type: registry.QWORD, Name: "Qword3", Value: uint64(0xff)},
147
+ {Type: registry.QWORD, Name: "Qword4", Value: uint64(0xffff)},
148
+ {Type: registry.QWORD, Name: "Qword5", Value: uint64(0xffffff)},
149
+ {Type: registry.QWORD, Name: "Qword6", Value: uint64(0xffffffff)},
150
+ {Type: registry.MULTI_SZ, Name: "MultiString1", Value: []string{"a", "b", "c"}},
151
+ {Type: registry.MULTI_SZ, Name: "MultiString2", Value: []string{"abc", "", "cba"}},
152
+ {Type: registry.MULTI_SZ, Name: "MultiString3", Value: []string{""}},
153
+ {Type: registry.MULTI_SZ, Name: "MultiString4", Value: []string{"abcdef"}},
154
+ {Type: registry.MULTI_SZ, Name: "MultiString5", Value: []string{"\000"}, WillFail: true},
155
+ {Type: registry.MULTI_SZ, Name: "MultiString6", Value: []string{"a\000b"}, WillFail: true},
156
+ {Type: registry.MULTI_SZ, Name: "MultiString7", Value: []string{"ab", "\000", "cd"}, WillFail: true},
157
+ {Type: registry.MULTI_SZ, Name: "MultiString8", Value: []string{"\000", "cd"}, WillFail: true},
158
+ {Type: registry.MULTI_SZ, Name: "MultiString9", Value: []string{"ab", "\000"}, WillFail: true},
159
+ }
160
+
161
+ func setValues(t *testing.T, k registry.Key) {
162
+ for _, test := range ValueTests {
163
+ var err error
164
+ switch test.Type {
165
+ case registry.SZ:
166
+ err = k.SetStringValue(test.Name, test.Value.(string))
167
+ case registry.EXPAND_SZ:
168
+ err = k.SetExpandStringValue(test.Name, test.Value.(string))
169
+ case registry.MULTI_SZ:
170
+ err = k.SetStringsValue(test.Name, test.Value.([]string))
171
+ case registry.BINARY:
172
+ err = k.SetBinaryValue(test.Name, test.Value.([]byte))
173
+ case registry.DWORD:
174
+ err = k.SetDWordValue(test.Name, uint32(test.Value.(uint64)))
175
+ case registry.QWORD:
176
+ err = k.SetQWordValue(test.Name, test.Value.(uint64))
177
+ default:
178
+ t.Fatalf("unsupported type %d for %s value", test.Type, test.Name)
179
+ }
180
+ if test.WillFail {
181
+ if err == nil {
182
+ t.Fatalf("setting %s value %q should fail, but succeeded", test.Name, test.Value)
183
+ }
184
+ } else {
185
+ if err != nil {
186
+ t.Fatal(err)
187
+ }
188
+ }
189
+ }
190
+ }
191
+
192
+ func enumerateValues(t *testing.T, k registry.Key) {
193
+ names, err := k.ReadValueNames()
194
+ if err != nil {
195
+ t.Error(err)
196
+ return
197
+ }
198
+ haveNames := make(map[string]bool)
199
+ for _, n := range names {
200
+ haveNames[n] = false
201
+ }
202
+ for _, test := range ValueTests {
203
+ wantFound := !test.WillFail
204
+ _, haveFound := haveNames[test.Name]
205
+ if wantFound && !haveFound {
206
+ t.Errorf("value %s is not found while enumerating", test.Name)
207
+ }
208
+ if haveFound && !wantFound {
209
+ t.Errorf("value %s is found while enumerating, but expected to fail", test.Name)
210
+ }
211
+ if haveFound {
212
+ delete(haveNames, test.Name)
213
+ }
214
+ }
215
+ for n, v := range haveNames {
216
+ t.Errorf("value %s (%v) is found while enumerating, but has not been created", n, v)
217
+ }
218
+ }
219
+
220
+ func testErrNotExist(t *testing.T, name string, err error) {
221
+ if err == nil {
222
+ t.Errorf("%s value should not exist", name)
223
+ return
224
+ }
225
+ if err != registry.ErrNotExist {
226
+ t.Errorf("reading %s value should return 'not exist' error, but got: %s", name, err)
227
+ return
228
+ }
229
+ }
230
+
231
+ func testErrUnexpectedType(t *testing.T, test ValueTest, gottype uint32, err error) {
232
+ if err == nil {
233
+ t.Errorf("GetXValue(%q) should not succeed", test.Name)
234
+ return
235
+ }
236
+ if err != registry.ErrUnexpectedType {
237
+ t.Errorf("reading %s value should return 'unexpected key value type' error, but got: %s", test.Name, err)
238
+ return
239
+ }
240
+ if gottype != test.Type {
241
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
242
+ return
243
+ }
244
+ }
245
+
246
+ func testGetStringValue(t *testing.T, k registry.Key, test ValueTest) {
247
+ got, gottype, err := k.GetStringValue(test.Name)
248
+ if err != nil {
249
+ t.Errorf("GetStringValue(%s) failed: %v", test.Name, err)
250
+ return
251
+ }
252
+ if got != test.Value {
253
+ t.Errorf("want %s value %q, got %q", test.Name, test.Value, got)
254
+ return
255
+ }
256
+ if gottype != test.Type {
257
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
258
+ return
259
+ }
260
+ if gottype == registry.EXPAND_SZ {
261
+ _, err = registry.ExpandString(got)
262
+ if err != nil {
263
+ t.Errorf("ExpandString(%s) failed: %v", got, err)
264
+ return
265
+ }
266
+ }
267
+ }
268
+
269
+ func testGetIntegerValue(t *testing.T, k registry.Key, test ValueTest) {
270
+ got, gottype, err := k.GetIntegerValue(test.Name)
271
+ if err != nil {
272
+ t.Errorf("GetIntegerValue(%s) failed: %v", test.Name, err)
273
+ return
274
+ }
275
+ if got != test.Value.(uint64) {
276
+ t.Errorf("want %s value %v, got %v", test.Name, test.Value, got)
277
+ return
278
+ }
279
+ if gottype != test.Type {
280
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
281
+ return
282
+ }
283
+ }
284
+
285
+ func testGetBinaryValue(t *testing.T, k registry.Key, test ValueTest) {
286
+ got, gottype, err := k.GetBinaryValue(test.Name)
287
+ if err != nil {
288
+ t.Errorf("GetBinaryValue(%s) failed: %v", test.Name, err)
289
+ return
290
+ }
291
+ if !bytes.Equal(got, test.Value.([]byte)) {
292
+ t.Errorf("want %s value %v, got %v", test.Name, test.Value, got)
293
+ return
294
+ }
295
+ if gottype != test.Type {
296
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
297
+ return
298
+ }
299
+ }
300
+
301
+ func testGetStringsValue(t *testing.T, k registry.Key, test ValueTest) {
302
+ got, gottype, err := k.GetStringsValue(test.Name)
303
+ if err != nil {
304
+ t.Errorf("GetStringsValue(%s) failed: %v", test.Name, err)
305
+ return
306
+ }
307
+ if !equalStringSlice(got, test.Value.([]string)) {
308
+ t.Errorf("want %s value %#v, got %#v", test.Name, test.Value, got)
309
+ return
310
+ }
311
+ if gottype != test.Type {
312
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
313
+ return
314
+ }
315
+ }
316
+
317
+ func testGetValue(t *testing.T, k registry.Key, test ValueTest, size int) {
318
+ if size <= 0 {
319
+ return
320
+ }
321
+ // read data with no buffer
322
+ gotsize, gottype, err := k.GetValue(test.Name, nil)
323
+ if err != nil {
324
+ t.Errorf("GetValue(%s, [%d]byte) failed: %v", test.Name, size, err)
325
+ return
326
+ }
327
+ if gotsize != size {
328
+ t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize)
329
+ return
330
+ }
331
+ if gottype != test.Type {
332
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
333
+ return
334
+ }
335
+ // read data with short buffer
336
+ gotsize, gottype, err = k.GetValue(test.Name, make([]byte, size-1))
337
+ if err == nil {
338
+ t.Errorf("GetValue(%s, [%d]byte) should fail, but succeeded", test.Name, size-1)
339
+ return
340
+ }
341
+ if err != registry.ErrShortBuffer {
342
+ t.Errorf("reading %s value should return 'short buffer' error, but got: %s", test.Name, err)
343
+ return
344
+ }
345
+ if gotsize != size {
346
+ t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize)
347
+ return
348
+ }
349
+ if gottype != test.Type {
350
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
351
+ return
352
+ }
353
+ // read full data
354
+ gotsize, gottype, err = k.GetValue(test.Name, make([]byte, size))
355
+ if err != nil {
356
+ t.Errorf("GetValue(%s, [%d]byte) failed: %v", test.Name, size, err)
357
+ return
358
+ }
359
+ if gotsize != size {
360
+ t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize)
361
+ return
362
+ }
363
+ if gottype != test.Type {
364
+ t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype)
365
+ return
366
+ }
367
+ // check GetValue returns ErrNotExist as required
368
+ _, _, err = k.GetValue(test.Name+"_not_there", make([]byte, size))
369
+ if err == nil {
370
+ t.Errorf("GetValue(%q) should not succeed", test.Name)
371
+ return
372
+ }
373
+ if err != registry.ErrNotExist {
374
+ t.Errorf("GetValue(%q) should return 'not exist' error, but got: %s", test.Name, err)
375
+ return
376
+ }
377
+ }
378
+
379
+ func testValues(t *testing.T, k registry.Key) {
380
+ for _, test := range ValueTests {
381
+ switch test.Type {
382
+ case registry.SZ, registry.EXPAND_SZ:
383
+ if test.WillFail {
384
+ _, _, err := k.GetStringValue(test.Name)
385
+ testErrNotExist(t, test.Name, err)
386
+ } else {
387
+ testGetStringValue(t, k, test)
388
+ _, gottype, err := k.GetIntegerValue(test.Name)
389
+ testErrUnexpectedType(t, test, gottype, err)
390
+ // Size of utf16 string in bytes is not perfect,
391
+ // but correct for current test values.
392
+ // Size also includes terminating 0.
393
+ testGetValue(t, k, test, (len(test.Value.(string))+1)*2)
394
+ }
395
+ _, _, err := k.GetStringValue(test.Name + "_string_not_created")
396
+ testErrNotExist(t, test.Name+"_string_not_created", err)
397
+ case registry.DWORD, registry.QWORD:
398
+ testGetIntegerValue(t, k, test)
399
+ _, gottype, err := k.GetBinaryValue(test.Name)
400
+ testErrUnexpectedType(t, test, gottype, err)
401
+ _, _, err = k.GetIntegerValue(test.Name + "_int_not_created")
402
+ testErrNotExist(t, test.Name+"_int_not_created", err)
403
+ size := 8
404
+ if test.Type == registry.DWORD {
405
+ size = 4
406
+ }
407
+ testGetValue(t, k, test, size)
408
+ case registry.BINARY:
409
+ testGetBinaryValue(t, k, test)
410
+ _, gottype, err := k.GetStringsValue(test.Name)
411
+ testErrUnexpectedType(t, test, gottype, err)
412
+ _, _, err = k.GetBinaryValue(test.Name + "_byte_not_created")
413
+ testErrNotExist(t, test.Name+"_byte_not_created", err)
414
+ testGetValue(t, k, test, len(test.Value.([]byte)))
415
+ case registry.MULTI_SZ:
416
+ if test.WillFail {
417
+ _, _, err := k.GetStringsValue(test.Name)
418
+ testErrNotExist(t, test.Name, err)
419
+ } else {
420
+ testGetStringsValue(t, k, test)
421
+ _, gottype, err := k.GetStringValue(test.Name)
422
+ testErrUnexpectedType(t, test, gottype, err)
423
+ size := 0
424
+ for _, s := range test.Value.([]string) {
425
+ size += len(s) + 1 // nil terminated
426
+ }
427
+ size += 1 // extra nil at the end
428
+ size *= 2 // count bytes, not uint16
429
+ testGetValue(t, k, test, size)
430
+ }
431
+ _, _, err := k.GetStringsValue(test.Name + "_strings_not_created")
432
+ testErrNotExist(t, test.Name+"_strings_not_created", err)
433
+ default:
434
+ t.Errorf("unsupported type %d for %s value", test.Type, test.Name)
435
+ continue
436
+ }
437
+ }
438
+ }
439
+
440
+ func testStat(t *testing.T, k registry.Key) {
441
+ subk, _, err := registry.CreateKey(k, "subkey", registry.CREATE_SUB_KEY)
442
+ if err != nil {
443
+ t.Error(err)
444
+ return
445
+ }
446
+ defer subk.Close()
447
+
448
+ defer registry.DeleteKey(k, "subkey")
449
+
450
+ ki, err := k.Stat()
451
+ if err != nil {
452
+ t.Error(err)
453
+ return
454
+ }
455
+ if ki.SubKeyCount != 1 {
456
+ t.Error("key must have 1 subkey")
457
+ }
458
+ if ki.MaxSubKeyLen != 6 {
459
+ t.Error("key max subkey name length must be 6")
460
+ }
461
+ if ki.ValueCount != 24 {
462
+ t.Errorf("key must have 24 values, but is %d", ki.ValueCount)
463
+ }
464
+ if ki.MaxValueNameLen != 12 {
465
+ t.Errorf("key max value name length must be 10, but is %d", ki.MaxValueNameLen)
466
+ }
467
+ if ki.MaxValueLen != 38 {
468
+ t.Errorf("key max value length must be 38, but is %d", ki.MaxValueLen)
469
+ }
470
+ }
471
+
472
+ func deleteValues(t *testing.T, k registry.Key) {
473
+ for _, test := range ValueTests {
474
+ if test.WillFail {
475
+ continue
476
+ }
477
+ err := k.DeleteValue(test.Name)
478
+ if err != nil {
479
+ t.Error(err)
480
+ continue
481
+ }
482
+ }
483
+ names, err := k.ReadValueNames()
484
+ if err != nil {
485
+ t.Error(err)
486
+ return
487
+ }
488
+ if len(names) != 0 {
489
+ t.Errorf("some values remain after deletion: %v", names)
490
+ }
491
+ }
492
+
493
+ func TestValues(t *testing.T) {
494
+ softwareK, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE)
495
+ if err != nil {
496
+ t.Fatal(err)
497
+ }
498
+ defer softwareK.Close()
499
+
500
+ testKName := randKeyName("TestValues_")
501
+
502
+ k, exist, err := registry.CreateKey(softwareK, testKName, registry.CREATE_SUB_KEY|registry.QUERY_VALUE|registry.SET_VALUE)
503
+ if err != nil {
504
+ t.Fatal(err)
505
+ }
506
+ defer k.Close()
507
+
508
+ if exist {
509
+ t.Fatalf("key %q already exists", testKName)
510
+ }
511
+
512
+ defer registry.DeleteKey(softwareK, testKName)
513
+
514
+ setValues(t, k)
515
+
516
+ enumerateValues(t, k)
517
+
518
+ testValues(t, k)
519
+
520
+ testStat(t, k)
521
+
522
+ deleteValues(t, k)
523
+ }
524
+
525
+ func TestExpandString(t *testing.T) {
526
+ got, err := registry.ExpandString("%PATH%")
527
+ if err != nil {
528
+ t.Fatal(err)
529
+ }
530
+ want := os.Getenv("PATH")
531
+ if got != want {
532
+ t.Errorf("want %q string expanded, got %q", want, got)
533
+ }
534
+ }
535
+
536
+ func TestInvalidValues(t *testing.T) {
537
+ softwareK, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE)
538
+ if err != nil {
539
+ t.Fatal(err)
540
+ }
541
+ defer softwareK.Close()
542
+
543
+ testKName := randKeyName("TestInvalidValues_")
544
+
545
+ k, exist, err := registry.CreateKey(softwareK, testKName, registry.CREATE_SUB_KEY|registry.QUERY_VALUE|registry.SET_VALUE)
546
+ if err != nil {
547
+ t.Fatal(err)
548
+ }
549
+ defer k.Close()
550
+
551
+ if exist {
552
+ t.Fatalf("key %q already exists", testKName)
553
+ }
554
+
555
+ defer registry.DeleteKey(softwareK, testKName)
556
+
557
+ var tests = []struct {
558
+ Type uint32
559
+ Name string
560
+ Data []byte
561
+ }{
562
+ {registry.DWORD, "Dword1", nil},
563
+ {registry.DWORD, "Dword2", []byte{1, 2, 3}},
564
+ {registry.QWORD, "Qword1", nil},
565
+ {registry.QWORD, "Qword2", []byte{1, 2, 3}},
566
+ {registry.QWORD, "Qword3", []byte{1, 2, 3, 4, 5, 6, 7}},
567
+ {registry.MULTI_SZ, "MultiString1", nil},
568
+ {registry.MULTI_SZ, "MultiString2", []byte{0}},
569
+ {registry.MULTI_SZ, "MultiString3", []byte{'a', 'b', 0}},
570
+ {registry.MULTI_SZ, "MultiString4", []byte{'a', 0, 0, 'b', 0}},
571
+ {registry.MULTI_SZ, "MultiString5", []byte{'a', 0, 0}},
572
+ }
573
+
574
+ for _, test := range tests {
575
+ err := k.SetValue(test.Name, test.Type, test.Data)
576
+ if err != nil {
577
+ t.Fatalf("SetValue for %q failed: %v", test.Name, err)
578
+ }
579
+ }
580
+
581
+ for _, test := range tests {
582
+ switch test.Type {
583
+ case registry.DWORD, registry.QWORD:
584
+ value, valType, err := k.GetIntegerValue(test.Name)
585
+ if err == nil {
586
+ t.Errorf("GetIntegerValue(%q) succeeded. Returns type=%d value=%v", test.Name, valType, value)
587
+ }
588
+ case registry.MULTI_SZ:
589
+ value, valType, err := k.GetStringsValue(test.Name)
590
+ if err == nil {
591
+ if len(value) != 0 {
592
+ t.Errorf("GetStringsValue(%q) succeeded. Returns type=%d value=%v", test.Name, valType, value)
593
+ }
594
+ }
595
+ default:
596
+ t.Errorf("unsupported type %d for %s value", test.Type, test.Name)
597
+ }
598
+ }
599
+ }
600
+
601
+ func TestGetMUIStringValue(t *testing.T) {
602
+ var dtzi DynamicTimezoneinformation
603
+ if _, err := GetDynamicTimeZoneInformation(&dtzi); err != nil {
604
+ t.Fatal(err)
605
+ }
606
+ tzKeyName := syscall.UTF16ToString(dtzi.TimeZoneKeyName[:])
607
+ timezoneK, err := registry.OpenKey(registry.LOCAL_MACHINE,
608
+ `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\`+tzKeyName, registry.READ)
609
+ if err != nil {
610
+ t.Fatal(err)
611
+ }
612
+ defer timezoneK.Close()
613
+
614
+ type testType struct {
615
+ name string
616
+ want string
617
+ }
618
+ var tests = []testType{
619
+ {"MUI_Std", syscall.UTF16ToString(dtzi.StandardName[:])},
620
+ }
621
+ if dtzi.DynamicDaylightTimeDisabled == 0 {
622
+ tests = append(tests, testType{"MUI_Dlt", syscall.UTF16ToString(dtzi.DaylightName[:])})
623
+ }
624
+
625
+ for _, test := range tests {
626
+ got, err := timezoneK.GetMUIStringValue(test.name)
627
+ if err != nil {
628
+ t.Error("GetMUIStringValue:", err)
629
+ }
630
+
631
+ if got != test.want {
632
+ t.Errorf("GetMUIStringValue: %s: Got %q, want %q", test.name, got, test.want)
633
+ }
634
+ }
635
+ }
636
+
637
+ type DynamicTimezoneinformation struct {
638
+ Bias int32
639
+ StandardName [32]uint16
640
+ StandardDate syscall.Systemtime
641
+ StandardBias int32
642
+ DaylightName [32]uint16
643
+ DaylightDate syscall.Systemtime
644
+ DaylightBias int32
645
+ TimeZoneKeyName [128]uint16
646
+ DynamicDaylightTimeDisabled uint8
647
+ }
648
+
649
+ var (
650
+ kernel32DLL = syscall.NewLazyDLL("kernel32")
651
+
652
+ procGetDynamicTimeZoneInformation = kernel32DLL.NewProc("GetDynamicTimeZoneInformation")
653
+ )
654
+
655
+ func GetDynamicTimeZoneInformation(dtzi *DynamicTimezoneinformation) (rc uint32, err error) {
656
+ r0, _, e1 := syscall.Syscall(procGetDynamicTimeZoneInformation.Addr(), 1, uintptr(unsafe.Pointer(dtzi)), 0, 0)
657
+ rc = uint32(r0)
658
+ if rc == 0xffffffff {
659
+ if e1 != 0 {
660
+ err = error(e1)
661
+ } else {
662
+ err = syscall.EINVAL
663
+ }
664
+ }
665
+ return
666
+ }
platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/syscall.go ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build windows
6
+
7
+ package registry
8
+
9
+ import "syscall"
10
+
11
+ const (
12
+ _REG_OPTION_NON_VOLATILE = 0
13
+
14
+ _REG_CREATED_NEW_KEY = 1
15
+ _REG_OPENED_EXISTING_KEY = 2
16
+
17
+ _ERROR_NO_MORE_ITEMS syscall.Errno = 259
18
+ )
19
+
20
+ //sys regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) = advapi32.RegCreateKeyExW
21
+ //sys regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) = advapi32.RegDeleteKeyW
22
+ //sys regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) = advapi32.RegSetValueExW
23
+ //sys regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) = advapi32.RegEnumValueW
24
+ //sys regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) = advapi32.RegDeleteValueW
25
+ //sys regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) = advapi32.RegLoadMUIStringW
26
+
27
+ //sys expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW
platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/value.go ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2015 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build windows
6
+
7
+ package registry
8
+
9
+ import (
10
+ "errors"
11
+ "syscall"
12
+ "unicode/utf16"
13
+ "unsafe"
14
+ )
15
+
16
+ const (
17
+ // Registry value types.
18
+ NONE = 0
19
+ SZ = 1
20
+ EXPAND_SZ = 2
21
+ BINARY = 3
22
+ DWORD = 4
23
+ DWORD_BIG_ENDIAN = 5
24
+ LINK = 6
25
+ MULTI_SZ = 7
26
+ RESOURCE_LIST = 8
27
+ FULL_RESOURCE_DESCRIPTOR = 9
28
+ RESOURCE_REQUIREMENTS_LIST = 10
29
+ QWORD = 11
30
+ )
31
+
32
+ var (
33
+ // ErrShortBuffer is returned when the buffer was too short for the operation.
34
+ ErrShortBuffer = syscall.ERROR_MORE_DATA
35
+
36
+ // ErrNotExist is returned when a registry key or value does not exist.
37
+ ErrNotExist = syscall.ERROR_FILE_NOT_FOUND
38
+
39
+ // ErrUnexpectedType is returned by Get*Value when the value's type was unexpected.
40
+ ErrUnexpectedType = errors.New("unexpected key value type")
41
+ )
42
+
43
+ // GetValue retrieves the type and data for the specified value associated
44
+ // with an open key k. It fills up buffer buf and returns the retrieved
45
+ // byte count n. If buf is too small to fit the stored value it returns
46
+ // ErrShortBuffer error along with the required buffer size n.
47
+ // If no buffer is provided, it returns true and actual buffer size n.
48
+ // If no buffer is provided, GetValue returns the value's type only.
49
+ // If the value does not exist, the error returned is ErrNotExist.
50
+ //
51
+ // GetValue is a low level function. If value's type is known, use the appropriate
52
+ // Get*Value function instead.
53
+ func (k Key) GetValue(name string, buf []byte) (n int, valtype uint32, err error) {
54
+ pname, err := syscall.UTF16PtrFromString(name)
55
+ if err != nil {
56
+ return 0, 0, err
57
+ }
58
+ var pbuf *byte
59
+ if len(buf) > 0 {
60
+ pbuf = (*byte)(unsafe.Pointer(&buf[0]))
61
+ }
62
+ l := uint32(len(buf))
63
+ err = syscall.RegQueryValueEx(syscall.Handle(k), pname, nil, &valtype, pbuf, &l)
64
+ if err != nil {
65
+ return int(l), valtype, err
66
+ }
67
+ return int(l), valtype, nil
68
+ }
69
+
70
+ func (k Key) getValue(name string, buf []byte) (date []byte, valtype uint32, err error) {
71
+ p, err := syscall.UTF16PtrFromString(name)
72
+ if err != nil {
73
+ return nil, 0, err
74
+ }
75
+ var t uint32
76
+ n := uint32(len(buf))
77
+ for {
78
+ err = syscall.RegQueryValueEx(syscall.Handle(k), p, nil, &t, (*byte)(unsafe.Pointer(&buf[0])), &n)
79
+ if err == nil {
80
+ return buf[:n], t, nil
81
+ }
82
+ if err != syscall.ERROR_MORE_DATA {
83
+ return nil, 0, err
84
+ }
85
+ if n <= uint32(len(buf)) {
86
+ return nil, 0, err
87
+ }
88
+ buf = make([]byte, n)
89
+ }
90
+ }
91
+
92
+ // GetStringValue retrieves the string value for the specified
93
+ // value name associated with an open key k. It also returns the value's type.
94
+ // If value does not exist, GetStringValue returns ErrNotExist.
95
+ // If value is not SZ or EXPAND_SZ, it will return the correct value
96
+ // type and ErrUnexpectedType.
97
+ func (k Key) GetStringValue(name string) (val string, valtype uint32, err error) {
98
+ data, typ, err2 := k.getValue(name, make([]byte, 64))
99
+ if err2 != nil {
100
+ return "", typ, err2
101
+ }
102
+ switch typ {
103
+ case SZ, EXPAND_SZ:
104
+ default:
105
+ return "", typ, ErrUnexpectedType
106
+ }
107
+ if len(data) == 0 {
108
+ return "", typ, nil
109
+ }
110
+ u := (*[1 << 29]uint16)(unsafe.Pointer(&data[0]))[: len(data)/2 : len(data)/2]
111
+ return syscall.UTF16ToString(u), typ, nil
112
+ }
113
+
114
+ // GetMUIStringValue retrieves the localized string value for
115
+ // the specified value name associated with an open key k.
116
+ // If the value name doesn't exist or the localized string value
117
+ // can't be resolved, GetMUIStringValue returns ErrNotExist.
118
+ func (k Key) GetMUIStringValue(name string) (string, error) {
119
+ pname, err := syscall.UTF16PtrFromString(name)
120
+ if err != nil {
121
+ return "", err
122
+ }
123
+
124
+ buf := make([]uint16, 1024)
125
+ var buflen uint32
126
+ var pdir *uint16
127
+
128
+ err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir)
129
+ if err == syscall.ERROR_FILE_NOT_FOUND { // Try fallback path
130
+
131
+ // Try to resolve the string value using the system directory as
132
+ // a DLL search path; this assumes the string value is of the form
133
+ // @[path]\dllname,-strID but with no path given, e.g. @tzres.dll,-320.
134
+
135
+ // This approach works with tzres.dll but may have to be revised
136
+ // in the future to allow callers to provide custom search paths.
137
+
138
+ var s string
139
+ s, err = ExpandString("%SystemRoot%\\system32\\")
140
+ if err != nil {
141
+ return "", err
142
+ }
143
+ pdir, err = syscall.UTF16PtrFromString(s)
144
+ if err != nil {
145
+ return "", err
146
+ }
147
+
148
+ err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir)
149
+ }
150
+
151
+ for err == syscall.ERROR_MORE_DATA { // Grow buffer if needed
152
+ if buflen <= uint32(len(buf)) {
153
+ break // Buffer not growing, assume race; break
154
+ }
155
+ buf = make([]uint16, buflen)
156
+ err = regLoadMUIString(syscall.Handle(k), pname, &buf[0], uint32(len(buf)), &buflen, 0, pdir)
157
+ }
158
+
159
+ if err != nil {
160
+ return "", err
161
+ }
162
+
163
+ return syscall.UTF16ToString(buf), nil
164
+ }
165
+
166
+ // ExpandString expands environment-variable strings and replaces
167
+ // them with the values defined for the current user.
168
+ // Use ExpandString to expand EXPAND_SZ strings.
169
+ func ExpandString(value string) (string, error) {
170
+ if value == "" {
171
+ return "", nil
172
+ }
173
+ p, err := syscall.UTF16PtrFromString(value)
174
+ if err != nil {
175
+ return "", err
176
+ }
177
+ r := make([]uint16, 100)
178
+ for {
179
+ n, err := expandEnvironmentStrings(p, &r[0], uint32(len(r)))
180
+ if err != nil {
181
+ return "", err
182
+ }
183
+ if n <= uint32(len(r)) {
184
+ return syscall.UTF16ToString(r[:n]), nil
185
+ }
186
+ r = make([]uint16, n)
187
+ }
188
+ }
189
+
190
+ // GetStringsValue retrieves the []string value for the specified
191
+ // value name associated with an open key k. It also returns the value's type.
192
+ // If value does not exist, GetStringsValue returns ErrNotExist.
193
+ // If value is not MULTI_SZ, it will return the correct value
194
+ // type and ErrUnexpectedType.
195
+ func (k Key) GetStringsValue(name string) (val []string, valtype uint32, err error) {
196
+ data, typ, err2 := k.getValue(name, make([]byte, 64))
197
+ if err2 != nil {
198
+ return nil, typ, err2
199
+ }
200
+ if typ != MULTI_SZ {
201
+ return nil, typ, ErrUnexpectedType
202
+ }
203
+ if len(data) == 0 {
204
+ return nil, typ, nil
205
+ }
206
+ p := (*[1 << 29]uint16)(unsafe.Pointer(&data[0]))[: len(data)/2 : len(data)/2]
207
+ if len(p) == 0 {
208
+ return nil, typ, nil
209
+ }
210
+ if p[len(p)-1] == 0 {
211
+ p = p[:len(p)-1] // remove terminating null
212
+ }
213
+ val = make([]string, 0, 5)
214
+ from := 0
215
+ for i, c := range p {
216
+ if c == 0 {
217
+ val = append(val, syscall.UTF16ToString(p[from:i]))
218
+ from = i + 1
219
+ }
220
+ }
221
+ return val, typ, nil
222
+ }
223
+
224
+ // GetIntegerValue retrieves the integer value for the specified
225
+ // value name associated with an open key k. It also returns the value's type.
226
+ // If value does not exist, GetIntegerValue returns ErrNotExist.
227
+ // If value is not DWORD or QWORD, it will return the correct value
228
+ // type and ErrUnexpectedType.
229
+ func (k Key) GetIntegerValue(name string) (val uint64, valtype uint32, err error) {
230
+ data, typ, err2 := k.getValue(name, make([]byte, 8))
231
+ if err2 != nil {
232
+ return 0, typ, err2
233
+ }
234
+ switch typ {
235
+ case DWORD:
236
+ if len(data) != 4 {
237
+ return 0, typ, errors.New("DWORD value is not 4 bytes long")
238
+ }
239
+ return uint64(*(*uint32)(unsafe.Pointer(&data[0]))), DWORD, nil
240
+ case QWORD:
241
+ if len(data) != 8 {
242
+ return 0, typ, errors.New("QWORD value is not 8 bytes long")
243
+ }
244
+ return *(*uint64)(unsafe.Pointer(&data[0])), QWORD, nil
245
+ default:
246
+ return 0, typ, ErrUnexpectedType
247
+ }
248
+ }
249
+
250
+ // GetBinaryValue retrieves the binary value for the specified
251
+ // value name associated with an open key k. It also returns the value's type.
252
+ // If value does not exist, GetBinaryValue returns ErrNotExist.
253
+ // If value is not BINARY, it will return the correct value
254
+ // type and ErrUnexpectedType.
255
+ func (k Key) GetBinaryValue(name string) (val []byte, valtype uint32, err error) {
256
+ data, typ, err2 := k.getValue(name, make([]byte, 64))
257
+ if err2 != nil {
258
+ return nil, typ, err2
259
+ }
260
+ if typ != BINARY {
261
+ return nil, typ, ErrUnexpectedType
262
+ }
263
+ return data, typ, nil
264
+ }
265
+
266
+ func (k Key) setValue(name string, valtype uint32, data []byte) error {
267
+ p, err := syscall.UTF16PtrFromString(name)
268
+ if err != nil {
269
+ return err
270
+ }
271
+ if len(data) == 0 {
272
+ return regSetValueEx(syscall.Handle(k), p, 0, valtype, nil, 0)
273
+ }
274
+ return regSetValueEx(syscall.Handle(k), p, 0, valtype, &data[0], uint32(len(data)))
275
+ }
276
+
277
+ // SetDWordValue sets the data and type of a name value
278
+ // under key k to value and DWORD.
279
+ func (k Key) SetDWordValue(name string, value uint32) error {
280
+ return k.setValue(name, DWORD, (*[4]byte)(unsafe.Pointer(&value))[:])
281
+ }
282
+
283
+ // SetQWordValue sets the data and type of a name value
284
+ // under key k to value and QWORD.
285
+ func (k Key) SetQWordValue(name string, value uint64) error {
286
+ return k.setValue(name, QWORD, (*[8]byte)(unsafe.Pointer(&value))[:])
287
+ }
288
+
289
+ func (k Key) setStringValue(name string, valtype uint32, value string) error {
290
+ v, err := syscall.UTF16FromString(value)
291
+ if err != nil {
292
+ return err
293
+ }
294
+ buf := (*[1 << 29]byte)(unsafe.Pointer(&v[0]))[: len(v)*2 : len(v)*2]
295
+ return k.setValue(name, valtype, buf)
296
+ }
297
+
298
+ // SetStringValue sets the data and type of a name value
299
+ // under key k to value and SZ. The value must not contain a zero byte.
300
+ func (k Key) SetStringValue(name, value string) error {
301
+ return k.setStringValue(name, SZ, value)
302
+ }
303
+
304
+ // SetExpandStringValue sets the data and type of a name value
305
+ // under key k to value and EXPAND_SZ. The value must not contain a zero byte.
306
+ func (k Key) SetExpandStringValue(name, value string) error {
307
+ return k.setStringValue(name, EXPAND_SZ, value)
308
+ }
309
+
310
+ // SetStringsValue sets the data and type of a name value
311
+ // under key k to value and MULTI_SZ. The value strings
312
+ // must not contain a zero byte.
313
+ func (k Key) SetStringsValue(name string, value []string) error {
314
+ ss := ""
315
+ for _, s := range value {
316
+ for i := 0; i < len(s); i++ {
317
+ if s[i] == 0 {
318
+ return errors.New("string cannot have 0 inside")
319
+ }
320
+ }
321
+ ss += s + "\x00"
322
+ }
323
+ v := utf16.Encode([]rune(ss + "\x00"))
324
+ buf := (*[1 << 29]byte)(unsafe.Pointer(&v[0]))[: len(v)*2 : len(v)*2]
325
+ return k.setValue(name, MULTI_SZ, buf)
326
+ }
327
+
328
+ // SetBinaryValue sets the data and type of a name value
329
+ // under key k to value and BINARY.
330
+ func (k Key) SetBinaryValue(name string, value []byte) error {
331
+ return k.setValue(name, BINARY, value)
332
+ }
333
+
334
+ // DeleteValue removes a named value from the key k.
335
+ func (k Key) DeleteValue(name string) error {
336
+ return regDeleteValue(syscall.Handle(k), syscall.StringToUTF16Ptr(name))
337
+ }
338
+
339
+ // ReadValueNames returns the value names of key k.
340
+ func (k Key) ReadValueNames() ([]string, error) {
341
+ ki, err := k.Stat()
342
+ if err != nil {
343
+ return nil, err
344
+ }
345
+ names := make([]string, 0, ki.ValueCount)
346
+ buf := make([]uint16, ki.MaxValueNameLen+1) // extra room for terminating null character
347
+ loopItems:
348
+ for i := uint32(0); ; i++ {
349
+ l := uint32(len(buf))
350
+ for {
351
+ err := regEnumValue(syscall.Handle(k), i, &buf[0], &l, nil, nil, nil, nil)
352
+ if err == nil {
353
+ break
354
+ }
355
+ if err == syscall.ERROR_MORE_DATA {
356
+ // Double buffer size and try again.
357
+ l = uint32(2 * len(buf))
358
+ buf = make([]uint16, l)
359
+ continue
360
+ }
361
+ if err == _ERROR_NO_MORE_ITEMS {
362
+ break loopItems
363
+ }
364
+ return names, err
365
+ }
366
+ names = append(names, syscall.UTF16ToString(buf[:l]))
367
+ }
368
+ return names, nil
369
+ }
platform/dbops/binaries/go/go/src/internal/syscall/windows/registry/zsyscall_windows.go ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Code generated by 'go generate'; DO NOT EDIT.
2
+
3
+ package registry
4
+
5
+ import (
6
+ "internal/syscall/windows/sysdll"
7
+ "syscall"
8
+ "unsafe"
9
+ )
10
+
11
+ var _ unsafe.Pointer
12
+
13
+ // Do the interface allocations only once for common
14
+ // Errno values.
15
+ const (
16
+ errnoERROR_IO_PENDING = 997
17
+ )
18
+
19
+ var (
20
+ errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
21
+ errERROR_EINVAL error = syscall.EINVAL
22
+ )
23
+
24
+ // errnoErr returns common boxed Errno values, to prevent
25
+ // allocations at runtime.
26
+ func errnoErr(e syscall.Errno) error {
27
+ switch e {
28
+ case 0:
29
+ return errERROR_EINVAL
30
+ case errnoERROR_IO_PENDING:
31
+ return errERROR_IO_PENDING
32
+ }
33
+ // TODO: add more here, after collecting data on the common
34
+ // error values see on Windows. (perhaps when running
35
+ // all.bat?)
36
+ return e
37
+ }
38
+
39
+ var (
40
+ modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
41
+ modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
42
+
43
+ procRegCreateKeyExW = modadvapi32.NewProc("RegCreateKeyExW")
44
+ procRegDeleteKeyW = modadvapi32.NewProc("RegDeleteKeyW")
45
+ procRegDeleteValueW = modadvapi32.NewProc("RegDeleteValueW")
46
+ procRegEnumValueW = modadvapi32.NewProc("RegEnumValueW")
47
+ procRegLoadMUIStringW = modadvapi32.NewProc("RegLoadMUIStringW")
48
+ procRegSetValueExW = modadvapi32.NewProc("RegSetValueExW")
49
+ procExpandEnvironmentStringsW = modkernel32.NewProc("ExpandEnvironmentStringsW")
50
+ )
51
+
52
+ func regCreateKeyEx(key syscall.Handle, subkey *uint16, reserved uint32, class *uint16, options uint32, desired uint32, sa *syscall.SecurityAttributes, result *syscall.Handle, disposition *uint32) (regerrno error) {
53
+ r0, _, _ := syscall.Syscall9(procRegCreateKeyExW.Addr(), 9, uintptr(key), uintptr(unsafe.Pointer(subkey)), uintptr(reserved), uintptr(unsafe.Pointer(class)), uintptr(options), uintptr(desired), uintptr(unsafe.Pointer(sa)), uintptr(unsafe.Pointer(result)), uintptr(unsafe.Pointer(disposition)))
54
+ if r0 != 0 {
55
+ regerrno = syscall.Errno(r0)
56
+ }
57
+ return
58
+ }
59
+
60
+ func regDeleteKey(key syscall.Handle, subkey *uint16) (regerrno error) {
61
+ r0, _, _ := syscall.Syscall(procRegDeleteKeyW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(subkey)), 0)
62
+ if r0 != 0 {
63
+ regerrno = syscall.Errno(r0)
64
+ }
65
+ return
66
+ }
67
+
68
+ func regDeleteValue(key syscall.Handle, name *uint16) (regerrno error) {
69
+ r0, _, _ := syscall.Syscall(procRegDeleteValueW.Addr(), 2, uintptr(key), uintptr(unsafe.Pointer(name)), 0)
70
+ if r0 != 0 {
71
+ regerrno = syscall.Errno(r0)
72
+ }
73
+ return
74
+ }
75
+
76
+ func regEnumValue(key syscall.Handle, index uint32, name *uint16, nameLen *uint32, reserved *uint32, valtype *uint32, buf *byte, buflen *uint32) (regerrno error) {
77
+ r0, _, _ := syscall.Syscall9(procRegEnumValueW.Addr(), 8, uintptr(key), uintptr(index), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(nameLen)), uintptr(unsafe.Pointer(reserved)), uintptr(unsafe.Pointer(valtype)), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(buflen)), 0)
78
+ if r0 != 0 {
79
+ regerrno = syscall.Errno(r0)
80
+ }
81
+ return
82
+ }
83
+
84
+ func regLoadMUIString(key syscall.Handle, name *uint16, buf *uint16, buflen uint32, buflenCopied *uint32, flags uint32, dir *uint16) (regerrno error) {
85
+ r0, _, _ := syscall.Syscall9(procRegLoadMUIStringW.Addr(), 7, uintptr(key), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buf)), uintptr(buflen), uintptr(unsafe.Pointer(buflenCopied)), uintptr(flags), uintptr(unsafe.Pointer(dir)), 0, 0)
86
+ if r0 != 0 {
87
+ regerrno = syscall.Errno(r0)
88
+ }
89
+ return
90
+ }
91
+
92
+ func regSetValueEx(key syscall.Handle, valueName *uint16, reserved uint32, vtype uint32, buf *byte, bufsize uint32) (regerrno error) {
93
+ r0, _, _ := syscall.Syscall6(procRegSetValueExW.Addr(), 6, uintptr(key), uintptr(unsafe.Pointer(valueName)), uintptr(reserved), uintptr(vtype), uintptr(unsafe.Pointer(buf)), uintptr(bufsize))
94
+ if r0 != 0 {
95
+ regerrno = syscall.Errno(r0)
96
+ }
97
+ return
98
+ }
99
+
100
+ func expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) {
101
+ r0, _, e1 := syscall.Syscall(procExpandEnvironmentStringsW.Addr(), 3, uintptr(unsafe.Pointer(src)), uintptr(unsafe.Pointer(dst)), uintptr(size))
102
+ n = uint32(r0)
103
+ if n == 0 {
104
+ err = errnoErr(e1)
105
+ }
106
+ return
107
+ }
platform/dbops/binaries/go/go/src/internal/syscall/windows/syscall_windows.go ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2014 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package windows
6
+
7
+ import (
8
+ "sync"
9
+ "syscall"
10
+ "unsafe"
11
+ )
12
+
13
+ // UTF16PtrToString is like UTF16ToString, but takes *uint16
14
+ // as a parameter instead of []uint16.
15
+ func UTF16PtrToString(p *uint16) string {
16
+ if p == nil {
17
+ return ""
18
+ }
19
+ end := unsafe.Pointer(p)
20
+ n := 0
21
+ for *(*uint16)(end) != 0 {
22
+ end = unsafe.Pointer(uintptr(end) + unsafe.Sizeof(*p))
23
+ n++
24
+ }
25
+ return syscall.UTF16ToString(unsafe.Slice(p, n))
26
+ }
27
+
28
+ const (
29
+ ERROR_BAD_LENGTH syscall.Errno = 24
30
+ ERROR_SHARING_VIOLATION syscall.Errno = 32
31
+ ERROR_LOCK_VIOLATION syscall.Errno = 33
32
+ ERROR_NOT_SUPPORTED syscall.Errno = 50
33
+ ERROR_CALL_NOT_IMPLEMENTED syscall.Errno = 120
34
+ ERROR_INVALID_NAME syscall.Errno = 123
35
+ ERROR_LOCK_FAILED syscall.Errno = 167
36
+ ERROR_NO_UNICODE_TRANSLATION syscall.Errno = 1113
37
+ )
38
+
39
+ const GAA_FLAG_INCLUDE_PREFIX = 0x00000010
40
+
41
+ const (
42
+ IF_TYPE_OTHER = 1
43
+ IF_TYPE_ETHERNET_CSMACD = 6
44
+ IF_TYPE_ISO88025_TOKENRING = 9
45
+ IF_TYPE_PPP = 23
46
+ IF_TYPE_SOFTWARE_LOOPBACK = 24
47
+ IF_TYPE_ATM = 37
48
+ IF_TYPE_IEEE80211 = 71
49
+ IF_TYPE_TUNNEL = 131
50
+ IF_TYPE_IEEE1394 = 144
51
+ )
52
+
53
+ type SocketAddress struct {
54
+ Sockaddr *syscall.RawSockaddrAny
55
+ SockaddrLength int32
56
+ }
57
+
58
+ type IpAdapterUnicastAddress struct {
59
+ Length uint32
60
+ Flags uint32
61
+ Next *IpAdapterUnicastAddress
62
+ Address SocketAddress
63
+ PrefixOrigin int32
64
+ SuffixOrigin int32
65
+ DadState int32
66
+ ValidLifetime uint32
67
+ PreferredLifetime uint32
68
+ LeaseLifetime uint32
69
+ OnLinkPrefixLength uint8
70
+ }
71
+
72
+ type IpAdapterAnycastAddress struct {
73
+ Length uint32
74
+ Flags uint32
75
+ Next *IpAdapterAnycastAddress
76
+ Address SocketAddress
77
+ }
78
+
79
+ type IpAdapterMulticastAddress struct {
80
+ Length uint32
81
+ Flags uint32
82
+ Next *IpAdapterMulticastAddress
83
+ Address SocketAddress
84
+ }
85
+
86
+ type IpAdapterDnsServerAdapter struct {
87
+ Length uint32
88
+ Reserved uint32
89
+ Next *IpAdapterDnsServerAdapter
90
+ Address SocketAddress
91
+ }
92
+
93
+ type IpAdapterPrefix struct {
94
+ Length uint32
95
+ Flags uint32
96
+ Next *IpAdapterPrefix
97
+ Address SocketAddress
98
+ PrefixLength uint32
99
+ }
100
+
101
+ type IpAdapterAddresses struct {
102
+ Length uint32
103
+ IfIndex uint32
104
+ Next *IpAdapterAddresses
105
+ AdapterName *byte
106
+ FirstUnicastAddress *IpAdapterUnicastAddress
107
+ FirstAnycastAddress *IpAdapterAnycastAddress
108
+ FirstMulticastAddress *IpAdapterMulticastAddress
109
+ FirstDnsServerAddress *IpAdapterDnsServerAdapter
110
+ DnsSuffix *uint16
111
+ Description *uint16
112
+ FriendlyName *uint16
113
+ PhysicalAddress [syscall.MAX_ADAPTER_ADDRESS_LENGTH]byte
114
+ PhysicalAddressLength uint32
115
+ Flags uint32
116
+ Mtu uint32
117
+ IfType uint32
118
+ OperStatus uint32
119
+ Ipv6IfIndex uint32
120
+ ZoneIndices [16]uint32
121
+ FirstPrefix *IpAdapterPrefix
122
+ /* more fields might be present here. */
123
+ }
124
+
125
+ type SecurityAttributes struct {
126
+ Length uint16
127
+ SecurityDescriptor uintptr
128
+ InheritHandle bool
129
+ }
130
+
131
+ type FILE_BASIC_INFO struct {
132
+ CreationTime int64
133
+ LastAccessTime int64
134
+ LastWriteTime int64
135
+ ChangedTime int64
136
+ FileAttributes uint32
137
+
138
+ // Pad out to 8-byte alignment.
139
+ //
140
+ // Without this padding, TestChmod fails due to an argument validation error
141
+ // in SetFileInformationByHandle on windows/386.
142
+ //
143
+ // https://learn.microsoft.com/en-us/cpp/build/reference/zp-struct-member-alignment?view=msvc-170
144
+ // says that “The C/C++ headers in the Windows SDK assume the platform's
145
+ // default alignment is used.” What we see here is padding rather than
146
+ // alignment, but maybe it is related.
147
+ _ uint32
148
+ }
149
+
150
+ const (
151
+ IfOperStatusUp = 1
152
+ IfOperStatusDown = 2
153
+ IfOperStatusTesting = 3
154
+ IfOperStatusUnknown = 4
155
+ IfOperStatusDormant = 5
156
+ IfOperStatusNotPresent = 6
157
+ IfOperStatusLowerLayerDown = 7
158
+ )
159
+
160
+ //sys GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) = iphlpapi.GetAdaptersAddresses
161
+ //sys GetComputerNameEx(nameformat uint32, buf *uint16, n *uint32) (err error) = GetComputerNameExW
162
+ //sys MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) = MoveFileExW
163
+ //sys GetModuleFileName(module syscall.Handle, fn *uint16, len uint32) (n uint32, err error) = kernel32.GetModuleFileNameW
164
+ //sys SetFileInformationByHandle(handle syscall.Handle, fileInformationClass uint32, buf unsafe.Pointer, bufsize uint32) (err error) = kernel32.SetFileInformationByHandle
165
+ //sys VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) = kernel32.VirtualQuery
166
+ //sys GetTempPath2(buflen uint32, buf *uint16) (n uint32, err error) = GetTempPath2W
167
+
168
+ const (
169
+ // flags for CreateToolhelp32Snapshot
170
+ TH32CS_SNAPMODULE = 0x08
171
+ TH32CS_SNAPMODULE32 = 0x10
172
+ )
173
+
174
+ const MAX_MODULE_NAME32 = 255
175
+
176
+ type ModuleEntry32 struct {
177
+ Size uint32
178
+ ModuleID uint32
179
+ ProcessID uint32
180
+ GlblcntUsage uint32
181
+ ProccntUsage uint32
182
+ ModBaseAddr uintptr
183
+ ModBaseSize uint32
184
+ ModuleHandle syscall.Handle
185
+ Module [MAX_MODULE_NAME32 + 1]uint16
186
+ ExePath [syscall.MAX_PATH]uint16
187
+ }
188
+
189
+ const SizeofModuleEntry32 = unsafe.Sizeof(ModuleEntry32{})
190
+
191
+ //sys Module32First(snapshot syscall.Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32FirstW
192
+ //sys Module32Next(snapshot syscall.Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32NextW
193
+
194
+ const (
195
+ WSA_FLAG_OVERLAPPED = 0x01
196
+ WSA_FLAG_NO_HANDLE_INHERIT = 0x80
197
+
198
+ WSAEMSGSIZE syscall.Errno = 10040
199
+
200
+ MSG_PEEK = 0x2
201
+ MSG_TRUNC = 0x0100
202
+ MSG_CTRUNC = 0x0200
203
+
204
+ socket_error = uintptr(^uint32(0))
205
+ )
206
+
207
+ var WSAID_WSASENDMSG = syscall.GUID{
208
+ Data1: 0xa441e712,
209
+ Data2: 0x754f,
210
+ Data3: 0x43ca,
211
+ Data4: [8]byte{0x84, 0xa7, 0x0d, 0xee, 0x44, 0xcf, 0x60, 0x6d},
212
+ }
213
+
214
+ var WSAID_WSARECVMSG = syscall.GUID{
215
+ Data1: 0xf689d7c8,
216
+ Data2: 0x6f1f,
217
+ Data3: 0x436b,
218
+ Data4: [8]byte{0x8a, 0x53, 0xe5, 0x4f, 0xe3, 0x51, 0xc3, 0x22},
219
+ }
220
+
221
+ var sendRecvMsgFunc struct {
222
+ once sync.Once
223
+ sendAddr uintptr
224
+ recvAddr uintptr
225
+ err error
226
+ }
227
+
228
+ type WSAMsg struct {
229
+ Name syscall.Pointer
230
+ Namelen int32
231
+ Buffers *syscall.WSABuf
232
+ BufferCount uint32
233
+ Control syscall.WSABuf
234
+ Flags uint32
235
+ }
236
+
237
+ //sys WSASocket(af int32, typ int32, protocol int32, protinfo *syscall.WSAProtocolInfo, group uint32, flags uint32) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = ws2_32.WSASocketW
238
+
239
+ func loadWSASendRecvMsg() error {
240
+ sendRecvMsgFunc.once.Do(func() {
241
+ var s syscall.Handle
242
+ s, sendRecvMsgFunc.err = syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_UDP)
243
+ if sendRecvMsgFunc.err != nil {
244
+ return
245
+ }
246
+ defer syscall.CloseHandle(s)
247
+ var n uint32
248
+ sendRecvMsgFunc.err = syscall.WSAIoctl(s,
249
+ syscall.SIO_GET_EXTENSION_FUNCTION_POINTER,
250
+ (*byte)(unsafe.Pointer(&WSAID_WSARECVMSG)),
251
+ uint32(unsafe.Sizeof(WSAID_WSARECVMSG)),
252
+ (*byte)(unsafe.Pointer(&sendRecvMsgFunc.recvAddr)),
253
+ uint32(unsafe.Sizeof(sendRecvMsgFunc.recvAddr)),
254
+ &n, nil, 0)
255
+ if sendRecvMsgFunc.err != nil {
256
+ return
257
+ }
258
+ sendRecvMsgFunc.err = syscall.WSAIoctl(s,
259
+ syscall.SIO_GET_EXTENSION_FUNCTION_POINTER,
260
+ (*byte)(unsafe.Pointer(&WSAID_WSASENDMSG)),
261
+ uint32(unsafe.Sizeof(WSAID_WSASENDMSG)),
262
+ (*byte)(unsafe.Pointer(&sendRecvMsgFunc.sendAddr)),
263
+ uint32(unsafe.Sizeof(sendRecvMsgFunc.sendAddr)),
264
+ &n, nil, 0)
265
+ })
266
+ return sendRecvMsgFunc.err
267
+ }
268
+
269
+ func WSASendMsg(fd syscall.Handle, msg *WSAMsg, flags uint32, bytesSent *uint32, overlapped *syscall.Overlapped, croutine *byte) error {
270
+ err := loadWSASendRecvMsg()
271
+ if err != nil {
272
+ return err
273
+ }
274
+ r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.sendAddr, 6, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(flags), uintptr(unsafe.Pointer(bytesSent)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)))
275
+ if r1 == socket_error {
276
+ if e1 != 0 {
277
+ err = errnoErr(e1)
278
+ } else {
279
+ err = syscall.EINVAL
280
+ }
281
+ }
282
+ return err
283
+ }
284
+
285
+ func WSARecvMsg(fd syscall.Handle, msg *WSAMsg, bytesReceived *uint32, overlapped *syscall.Overlapped, croutine *byte) error {
286
+ err := loadWSASendRecvMsg()
287
+ if err != nil {
288
+ return err
289
+ }
290
+ r1, _, e1 := syscall.Syscall6(sendRecvMsgFunc.recvAddr, 5, uintptr(fd), uintptr(unsafe.Pointer(msg)), uintptr(unsafe.Pointer(bytesReceived)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(croutine)), 0)
291
+ if r1 == socket_error {
292
+ if e1 != 0 {
293
+ err = errnoErr(e1)
294
+ } else {
295
+ err = syscall.EINVAL
296
+ }
297
+ }
298
+ return err
299
+ }
300
+
301
+ const (
302
+ ComputerNameNetBIOS = 0
303
+ ComputerNameDnsHostname = 1
304
+ ComputerNameDnsDomain = 2
305
+ ComputerNameDnsFullyQualified = 3
306
+ ComputerNamePhysicalNetBIOS = 4
307
+ ComputerNamePhysicalDnsHostname = 5
308
+ ComputerNamePhysicalDnsDomain = 6
309
+ ComputerNamePhysicalDnsFullyQualified = 7
310
+ ComputerNameMax = 8
311
+
312
+ MOVEFILE_REPLACE_EXISTING = 0x1
313
+ MOVEFILE_COPY_ALLOWED = 0x2
314
+ MOVEFILE_DELAY_UNTIL_REBOOT = 0x4
315
+ MOVEFILE_WRITE_THROUGH = 0x8
316
+ MOVEFILE_CREATE_HARDLINK = 0x10
317
+ MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20
318
+ )
319
+
320
+ func Rename(oldpath, newpath string) error {
321
+ from, err := syscall.UTF16PtrFromString(oldpath)
322
+ if err != nil {
323
+ return err
324
+ }
325
+ to, err := syscall.UTF16PtrFromString(newpath)
326
+ if err != nil {
327
+ return err
328
+ }
329
+ return MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING)
330
+ }
331
+
332
+ //sys LockFileEx(file syscall.Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *syscall.Overlapped) (err error) = kernel32.LockFileEx
333
+ //sys UnlockFileEx(file syscall.Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *syscall.Overlapped) (err error) = kernel32.UnlockFileEx
334
+
335
+ const (
336
+ LOCKFILE_FAIL_IMMEDIATELY = 0x00000001
337
+ LOCKFILE_EXCLUSIVE_LOCK = 0x00000002
338
+ )
339
+
340
+ const MB_ERR_INVALID_CHARS = 8
341
+
342
+ //sys GetACP() (acp uint32) = kernel32.GetACP
343
+ //sys GetConsoleCP() (ccp uint32) = kernel32.GetConsoleCP
344
+ //sys MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) = kernel32.MultiByteToWideChar
345
+ //sys GetCurrentThread() (pseudoHandle syscall.Handle, err error) = kernel32.GetCurrentThread
346
+
347
+ // Constants from lmshare.h
348
+ const (
349
+ STYPE_DISKTREE = 0x00
350
+ STYPE_TEMPORARY = 0x40000000
351
+ )
352
+
353
+ type SHARE_INFO_2 struct {
354
+ Netname *uint16
355
+ Type uint32
356
+ Remark *uint16
357
+ Permissions uint32
358
+ MaxUses uint32
359
+ CurrentUses uint32
360
+ Path *uint16
361
+ Passwd *uint16
362
+ }
363
+
364
+ //sys NetShareAdd(serverName *uint16, level uint32, buf *byte, parmErr *uint16) (neterr error) = netapi32.NetShareAdd
365
+ //sys NetShareDel(serverName *uint16, netName *uint16, reserved uint32) (neterr error) = netapi32.NetShareDel
366
+
367
+ const (
368
+ FILE_NAME_NORMALIZED = 0x0
369
+ FILE_NAME_OPENED = 0x8
370
+
371
+ VOLUME_NAME_DOS = 0x0
372
+ VOLUME_NAME_GUID = 0x1
373
+ VOLUME_NAME_NONE = 0x4
374
+ VOLUME_NAME_NT = 0x2
375
+ )
376
+
377
+ //sys GetFinalPathNameByHandle(file syscall.Handle, filePath *uint16, filePathSize uint32, flags uint32) (n uint32, err error) = kernel32.GetFinalPathNameByHandleW
378
+
379
+ func ErrorLoadingGetTempPath2() error {
380
+ return procGetTempPath2W.Find()
381
+ }
382
+
383
+ //sys CreateEnvironmentBlock(block **uint16, token syscall.Token, inheritExisting bool) (err error) = userenv.CreateEnvironmentBlock
384
+ //sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
385
+ //sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) = kernel32.CreateEventW
386
+
387
+ //sys ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
388
+
389
+ type FILE_ID_BOTH_DIR_INFO struct {
390
+ NextEntryOffset uint32
391
+ FileIndex uint32
392
+ CreationTime syscall.Filetime
393
+ LastAccessTime syscall.Filetime
394
+ LastWriteTime syscall.Filetime
395
+ ChangeTime syscall.Filetime
396
+ EndOfFile uint64
397
+ AllocationSize uint64
398
+ FileAttributes uint32
399
+ FileNameLength uint32
400
+ EaSize uint32
401
+ ShortNameLength uint32
402
+ ShortName [12]uint16
403
+ FileID uint64
404
+ FileName [1]uint16
405
+ }
406
+
407
+ type FILE_FULL_DIR_INFO struct {
408
+ NextEntryOffset uint32
409
+ FileIndex uint32
410
+ CreationTime syscall.Filetime
411
+ LastAccessTime syscall.Filetime
412
+ LastWriteTime syscall.Filetime
413
+ ChangeTime syscall.Filetime
414
+ EndOfFile uint64
415
+ AllocationSize uint64
416
+ FileAttributes uint32
417
+ FileNameLength uint32
418
+ EaSize uint32
419
+ FileName [1]uint16
420
+ }
421
+
422
+ //sys GetVolumeInformationByHandle(file syscall.Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationByHandleW
423
+ //sys GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) = GetVolumeNameForVolumeMountPointW
424
+
425
+ //sys RtlLookupFunctionEntry(pc uintptr, baseAddress *uintptr, table *byte) (ret uintptr) = kernel32.RtlLookupFunctionEntry
426
+ //sys RtlVirtualUnwind(handlerType uint32, baseAddress uintptr, pc uintptr, entry uintptr, ctxt uintptr, data *uintptr, frame *uintptr, ctxptrs *byte) (ret uintptr) = kernel32.RtlVirtualUnwind
427
+
428
+ type SERVICE_STATUS struct {
429
+ ServiceType uint32
430
+ CurrentState uint32
431
+ ControlsAccepted uint32
432
+ Win32ExitCode uint32
433
+ ServiceSpecificExitCode uint32
434
+ CheckPoint uint32
435
+ WaitHint uint32
436
+ }
437
+
438
+ const (
439
+ SERVICE_RUNNING = 4
440
+ SERVICE_QUERY_STATUS = 4
441
+ )
442
+
443
+ //sys OpenService(mgr syscall.Handle, serviceName *uint16, access uint32) (handle syscall.Handle, err error) = advapi32.OpenServiceW
444
+ //sys QueryServiceStatus(hService syscall.Handle, lpServiceStatus *SERVICE_STATUS) (err error) = advapi32.QueryServiceStatus
445
+ //sys OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle syscall.Handle, err error) [failretval==0] = advapi32.OpenSCManagerW
platform/dbops/binaries/go/go/src/internal/syscall/windows/sysdll/sysdll.go ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2016 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ //go:build windows
6
+
7
+ // Package sysdll is an internal leaf package that records and reports
8
+ // which Windows DLL names are used by Go itself. These DLLs are then
9
+ // only loaded from the System32 directory. See Issue 14959.
10
+ package sysdll
11
+
12
+ // IsSystemDLL reports whether the named dll key (a base name, like
13
+ // "foo.dll") is a system DLL which should only be loaded from the
14
+ // Windows SYSTEM32 directory.
15
+ //
16
+ // Filenames are case sensitive, but that doesn't matter because
17
+ // the case registered with Add is also the same case used with
18
+ // LoadDLL later.
19
+ //
20
+ // It has no associated mutex and should only be mutated serially
21
+ // (currently: during init), and not concurrent with DLL loading.
22
+ var IsSystemDLL = map[string]bool{}
23
+
24
+ // Add notes that dll is a system32 DLL which should only be loaded
25
+ // from the Windows SYSTEM32 directory. It returns its argument back,
26
+ // for ease of use in generated code.
27
+ func Add(dll string) string {
28
+ IsSystemDLL[dll] = true
29
+ return dll
30
+ }
platform/dbops/binaries/go/go/src/internal/syscall/windows/zsyscall_windows.go ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Code generated by 'go generate'; DO NOT EDIT.
2
+
3
+ package windows
4
+
5
+ import (
6
+ "internal/syscall/windows/sysdll"
7
+ "syscall"
8
+ "unsafe"
9
+ )
10
+
11
+ var _ unsafe.Pointer
12
+
13
+ // Do the interface allocations only once for common
14
+ // Errno values.
15
+ const (
16
+ errnoERROR_IO_PENDING = 997
17
+ )
18
+
19
+ var (
20
+ errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING)
21
+ errERROR_EINVAL error = syscall.EINVAL
22
+ )
23
+
24
+ // errnoErr returns common boxed Errno values, to prevent
25
+ // allocations at runtime.
26
+ func errnoErr(e syscall.Errno) error {
27
+ switch e {
28
+ case 0:
29
+ return errERROR_EINVAL
30
+ case errnoERROR_IO_PENDING:
31
+ return errERROR_IO_PENDING
32
+ }
33
+ // TODO: add more here, after collecting data on the common
34
+ // error values see on Windows. (perhaps when running
35
+ // all.bat?)
36
+ return e
37
+ }
38
+
39
+ var (
40
+ modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
41
+ modbcryptprimitives = syscall.NewLazyDLL(sysdll.Add("bcryptprimitives.dll"))
42
+ modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
43
+ modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
44
+ modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
45
+ modpsapi = syscall.NewLazyDLL(sysdll.Add("psapi.dll"))
46
+ moduserenv = syscall.NewLazyDLL(sysdll.Add("userenv.dll"))
47
+ modws2_32 = syscall.NewLazyDLL(sysdll.Add("ws2_32.dll"))
48
+
49
+ procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
50
+ procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx")
51
+ procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf")
52
+ procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW")
53
+ procOpenSCManagerW = modadvapi32.NewProc("OpenSCManagerW")
54
+ procOpenServiceW = modadvapi32.NewProc("OpenServiceW")
55
+ procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken")
56
+ procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
57
+ procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
58
+ procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
59
+ procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
60
+ procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
61
+ procCreateEventW = modkernel32.NewProc("CreateEventW")
62
+ procGetACP = modkernel32.NewProc("GetACP")
63
+ procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW")
64
+ procGetConsoleCP = modkernel32.NewProc("GetConsoleCP")
65
+ procGetCurrentThread = modkernel32.NewProc("GetCurrentThread")
66
+ procGetFileInformationByHandleEx = modkernel32.NewProc("GetFileInformationByHandleEx")
67
+ procGetFinalPathNameByHandleW = modkernel32.NewProc("GetFinalPathNameByHandleW")
68
+ procGetModuleFileNameW = modkernel32.NewProc("GetModuleFileNameW")
69
+ procGetTempPath2W = modkernel32.NewProc("GetTempPath2W")
70
+ procGetVolumeInformationByHandleW = modkernel32.NewProc("GetVolumeInformationByHandleW")
71
+ procGetVolumeNameForVolumeMountPointW = modkernel32.NewProc("GetVolumeNameForVolumeMountPointW")
72
+ procLockFileEx = modkernel32.NewProc("LockFileEx")
73
+ procModule32FirstW = modkernel32.NewProc("Module32FirstW")
74
+ procModule32NextW = modkernel32.NewProc("Module32NextW")
75
+ procMoveFileExW = modkernel32.NewProc("MoveFileExW")
76
+ procMultiByteToWideChar = modkernel32.NewProc("MultiByteToWideChar")
77
+ procRtlLookupFunctionEntry = modkernel32.NewProc("RtlLookupFunctionEntry")
78
+ procRtlVirtualUnwind = modkernel32.NewProc("RtlVirtualUnwind")
79
+ procSetFileInformationByHandle = modkernel32.NewProc("SetFileInformationByHandle")
80
+ procUnlockFileEx = modkernel32.NewProc("UnlockFileEx")
81
+ procVirtualQuery = modkernel32.NewProc("VirtualQuery")
82
+ procNetShareAdd = modnetapi32.NewProc("NetShareAdd")
83
+ procNetShareDel = modnetapi32.NewProc("NetShareDel")
84
+ procNetUserGetLocalGroups = modnetapi32.NewProc("NetUserGetLocalGroups")
85
+ procGetProcessMemoryInfo = modpsapi.NewProc("GetProcessMemoryInfo")
86
+ procCreateEnvironmentBlock = moduserenv.NewProc("CreateEnvironmentBlock")
87
+ procDestroyEnvironmentBlock = moduserenv.NewProc("DestroyEnvironmentBlock")
88
+ procGetProfilesDirectoryW = moduserenv.NewProc("GetProfilesDirectoryW")
89
+ procWSASocketW = modws2_32.NewProc("WSASocketW")
90
+ )
91
+
92
+ func adjustTokenPrivileges(token syscall.Token, disableAllPrivileges bool, newstate *TOKEN_PRIVILEGES, buflen uint32, prevstate *TOKEN_PRIVILEGES, returnlen *uint32) (ret uint32, err error) {
93
+ var _p0 uint32
94
+ if disableAllPrivileges {
95
+ _p0 = 1
96
+ }
97
+ r0, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6, uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(newstate)), uintptr(buflen), uintptr(unsafe.Pointer(prevstate)), uintptr(unsafe.Pointer(returnlen)))
98
+ ret = uint32(r0)
99
+ if true {
100
+ err = errnoErr(e1)
101
+ }
102
+ return
103
+ }
104
+
105
+ func DuplicateTokenEx(hExistingToken syscall.Token, dwDesiredAccess uint32, lpTokenAttributes *syscall.SecurityAttributes, impersonationLevel uint32, tokenType TokenType, phNewToken *syscall.Token) (err error) {
106
+ r1, _, e1 := syscall.Syscall6(procDuplicateTokenEx.Addr(), 6, uintptr(hExistingToken), uintptr(dwDesiredAccess), uintptr(unsafe.Pointer(lpTokenAttributes)), uintptr(impersonationLevel), uintptr(tokenType), uintptr(unsafe.Pointer(phNewToken)))
107
+ if r1 == 0 {
108
+ err = errnoErr(e1)
109
+ }
110
+ return
111
+ }
112
+
113
+ func ImpersonateSelf(impersonationlevel uint32) (err error) {
114
+ r1, _, e1 := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(impersonationlevel), 0, 0)
115
+ if r1 == 0 {
116
+ err = errnoErr(e1)
117
+ }
118
+ return
119
+ }
120
+
121
+ func LookupPrivilegeValue(systemname *uint16, name *uint16, luid *LUID) (err error) {
122
+ r1, _, e1 := syscall.Syscall(procLookupPrivilegeValueW.Addr(), 3, uintptr(unsafe.Pointer(systemname)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid)))
123
+ if r1 == 0 {
124
+ err = errnoErr(e1)
125
+ }
126
+ return
127
+ }
128
+
129
+ func OpenSCManager(machineName *uint16, databaseName *uint16, access uint32) (handle syscall.Handle, err error) {
130
+ r0, _, e1 := syscall.Syscall(procOpenSCManagerW.Addr(), 3, uintptr(unsafe.Pointer(machineName)), uintptr(unsafe.Pointer(databaseName)), uintptr(access))
131
+ handle = syscall.Handle(r0)
132
+ if handle == 0 {
133
+ err = errnoErr(e1)
134
+ }
135
+ return
136
+ }
137
+
138
+ func OpenService(mgr syscall.Handle, serviceName *uint16, access uint32) (handle syscall.Handle, err error) {
139
+ r0, _, e1 := syscall.Syscall(procOpenServiceW.Addr(), 3, uintptr(mgr), uintptr(unsafe.Pointer(serviceName)), uintptr(access))
140
+ handle = syscall.Handle(r0)
141
+ if handle == 0 {
142
+ err = errnoErr(e1)
143
+ }
144
+ return
145
+ }
146
+
147
+ func OpenThreadToken(h syscall.Handle, access uint32, openasself bool, token *syscall.Token) (err error) {
148
+ var _p0 uint32
149
+ if openasself {
150
+ _p0 = 1
151
+ }
152
+ r1, _, e1 := syscall.Syscall6(procOpenThreadToken.Addr(), 4, uintptr(h), uintptr(access), uintptr(_p0), uintptr(unsafe.Pointer(token)), 0, 0)
153
+ if r1 == 0 {
154
+ err = errnoErr(e1)
155
+ }
156
+ return
157
+ }
158
+
159
+ func QueryServiceStatus(hService syscall.Handle, lpServiceStatus *SERVICE_STATUS) (err error) {
160
+ r1, _, e1 := syscall.Syscall(procQueryServiceStatus.Addr(), 2, uintptr(hService), uintptr(unsafe.Pointer(lpServiceStatus)), 0)
161
+ if r1 == 0 {
162
+ err = errnoErr(e1)
163
+ }
164
+ return
165
+ }
166
+
167
+ func RevertToSelf() (err error) {
168
+ r1, _, e1 := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0)
169
+ if r1 == 0 {
170
+ err = errnoErr(e1)
171
+ }
172
+ return
173
+ }
174
+
175
+ func SetTokenInformation(tokenHandle syscall.Token, tokenInformationClass uint32, tokenInformation uintptr, tokenInformationLength uint32) (err error) {
176
+ r1, _, e1 := syscall.Syscall6(procSetTokenInformation.Addr(), 4, uintptr(tokenHandle), uintptr(tokenInformationClass), uintptr(tokenInformation), uintptr(tokenInformationLength), 0, 0)
177
+ if r1 == 0 {
178
+ err = errnoErr(e1)
179
+ }
180
+ return
181
+ }
182
+
183
+ func ProcessPrng(buf []byte) (err error) {
184
+ var _p0 *byte
185
+ if len(buf) > 0 {
186
+ _p0 = &buf[0]
187
+ }
188
+ r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
189
+ if r1 == 0 {
190
+ err = errnoErr(e1)
191
+ }
192
+ return
193
+ }
194
+
195
+ func GetAdaptersAddresses(family uint32, flags uint32, reserved uintptr, adapterAddresses *IpAdapterAddresses, sizePointer *uint32) (errcode error) {
196
+ r0, _, _ := syscall.Syscall6(procGetAdaptersAddresses.Addr(), 5, uintptr(family), uintptr(flags), uintptr(reserved), uintptr(unsafe.Pointer(adapterAddresses)), uintptr(unsafe.Pointer(sizePointer)), 0)
197
+ if r0 != 0 {
198
+ errcode = syscall.Errno(r0)
199
+ }
200
+ return
201
+ }
202
+
203
+ func CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) {
204
+ r0, _, e1 := syscall.Syscall6(procCreateEventW.Addr(), 4, uintptr(unsafe.Pointer(eventAttrs)), uintptr(manualReset), uintptr(initialState), uintptr(unsafe.Pointer(name)), 0, 0)
205
+ handle = syscall.Handle(r0)
206
+ if handle == 0 {
207
+ err = errnoErr(e1)
208
+ }
209
+ return
210
+ }
211
+
212
+ func GetACP() (acp uint32) {
213
+ r0, _, _ := syscall.Syscall(procGetACP.Addr(), 0, 0, 0, 0)
214
+ acp = uint32(r0)
215
+ return
216
+ }
217
+
218
+ func GetComputerNameEx(nameformat uint32, buf *uint16, n *uint32) (err error) {
219
+ r1, _, e1 := syscall.Syscall(procGetComputerNameExW.Addr(), 3, uintptr(nameformat), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(n)))
220
+ if r1 == 0 {
221
+ err = errnoErr(e1)
222
+ }
223
+ return
224
+ }
225
+
226
+ func GetConsoleCP() (ccp uint32) {
227
+ r0, _, _ := syscall.Syscall(procGetConsoleCP.Addr(), 0, 0, 0, 0)
228
+ ccp = uint32(r0)
229
+ return
230
+ }
231
+
232
+ func GetCurrentThread() (pseudoHandle syscall.Handle, err error) {
233
+ r0, _, e1 := syscall.Syscall(procGetCurrentThread.Addr(), 0, 0, 0, 0)
234
+ pseudoHandle = syscall.Handle(r0)
235
+ if pseudoHandle == 0 {
236
+ err = errnoErr(e1)
237
+ }
238
+ return
239
+ }
240
+
241
+ func GetFileInformationByHandleEx(handle syscall.Handle, class uint32, info *byte, bufsize uint32) (err error) {
242
+ r1, _, e1 := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), 4, uintptr(handle), uintptr(class), uintptr(unsafe.Pointer(info)), uintptr(bufsize), 0, 0)
243
+ if r1 == 0 {
244
+ err = errnoErr(e1)
245
+ }
246
+ return
247
+ }
248
+
249
+ func GetFinalPathNameByHandle(file syscall.Handle, filePath *uint16, filePathSize uint32, flags uint32) (n uint32, err error) {
250
+ r0, _, e1 := syscall.Syscall6(procGetFinalPathNameByHandleW.Addr(), 4, uintptr(file), uintptr(unsafe.Pointer(filePath)), uintptr(filePathSize), uintptr(flags), 0, 0)
251
+ n = uint32(r0)
252
+ if n == 0 {
253
+ err = errnoErr(e1)
254
+ }
255
+ return
256
+ }
257
+
258
+ func GetModuleFileName(module syscall.Handle, fn *uint16, len uint32) (n uint32, err error) {
259
+ r0, _, e1 := syscall.Syscall(procGetModuleFileNameW.Addr(), 3, uintptr(module), uintptr(unsafe.Pointer(fn)), uintptr(len))
260
+ n = uint32(r0)
261
+ if n == 0 {
262
+ err = errnoErr(e1)
263
+ }
264
+ return
265
+ }
266
+
267
+ func GetTempPath2(buflen uint32, buf *uint16) (n uint32, err error) {
268
+ r0, _, e1 := syscall.Syscall(procGetTempPath2W.Addr(), 2, uintptr(buflen), uintptr(unsafe.Pointer(buf)), 0)
269
+ n = uint32(r0)
270
+ if n == 0 {
271
+ err = errnoErr(e1)
272
+ }
273
+ return
274
+ }
275
+
276
+ func GetVolumeInformationByHandle(file syscall.Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) {
277
+ r1, _, e1 := syscall.Syscall9(procGetVolumeInformationByHandleW.Addr(), 8, uintptr(file), uintptr(unsafe.Pointer(volumeNameBuffer)), uintptr(volumeNameSize), uintptr(unsafe.Pointer(volumeNameSerialNumber)), uintptr(unsafe.Pointer(maximumComponentLength)), uintptr(unsafe.Pointer(fileSystemFlags)), uintptr(unsafe.Pointer(fileSystemNameBuffer)), uintptr(fileSystemNameSize), 0)
278
+ if r1 == 0 {
279
+ err = errnoErr(e1)
280
+ }
281
+ return
282
+ }
283
+
284
+ func GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) {
285
+ r1, _, e1 := syscall.Syscall(procGetVolumeNameForVolumeMountPointW.Addr(), 3, uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(unsafe.Pointer(volumeName)), uintptr(bufferlength))
286
+ if r1 == 0 {
287
+ err = errnoErr(e1)
288
+ }
289
+ return
290
+ }
291
+
292
+ func LockFileEx(file syscall.Handle, flags uint32, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *syscall.Overlapped) (err error) {
293
+ r1, _, e1 := syscall.Syscall6(procLockFileEx.Addr(), 6, uintptr(file), uintptr(flags), uintptr(reserved), uintptr(bytesLow), uintptr(bytesHigh), uintptr(unsafe.Pointer(overlapped)))
294
+ if r1 == 0 {
295
+ err = errnoErr(e1)
296
+ }
297
+ return
298
+ }
299
+
300
+ func Module32First(snapshot syscall.Handle, moduleEntry *ModuleEntry32) (err error) {
301
+ r1, _, e1 := syscall.Syscall(procModule32FirstW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(moduleEntry)), 0)
302
+ if r1 == 0 {
303
+ err = errnoErr(e1)
304
+ }
305
+ return
306
+ }
307
+
308
+ func Module32Next(snapshot syscall.Handle, moduleEntry *ModuleEntry32) (err error) {
309
+ r1, _, e1 := syscall.Syscall(procModule32NextW.Addr(), 2, uintptr(snapshot), uintptr(unsafe.Pointer(moduleEntry)), 0)
310
+ if r1 == 0 {
311
+ err = errnoErr(e1)
312
+ }
313
+ return
314
+ }
315
+
316
+ func MoveFileEx(from *uint16, to *uint16, flags uint32) (err error) {
317
+ r1, _, e1 := syscall.Syscall(procMoveFileExW.Addr(), 3, uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(to)), uintptr(flags))
318
+ if r1 == 0 {
319
+ err = errnoErr(e1)
320
+ }
321
+ return
322
+ }
323
+
324
+ func MultiByteToWideChar(codePage uint32, dwFlags uint32, str *byte, nstr int32, wchar *uint16, nwchar int32) (nwrite int32, err error) {
325
+ r0, _, e1 := syscall.Syscall6(procMultiByteToWideChar.Addr(), 6, uintptr(codePage), uintptr(dwFlags), uintptr(unsafe.Pointer(str)), uintptr(nstr), uintptr(unsafe.Pointer(wchar)), uintptr(nwchar))
326
+ nwrite = int32(r0)
327
+ if nwrite == 0 {
328
+ err = errnoErr(e1)
329
+ }
330
+ return
331
+ }
332
+
333
+ func RtlLookupFunctionEntry(pc uintptr, baseAddress *uintptr, table *byte) (ret uintptr) {
334
+ r0, _, _ := syscall.Syscall(procRtlLookupFunctionEntry.Addr(), 3, uintptr(pc), uintptr(unsafe.Pointer(baseAddress)), uintptr(unsafe.Pointer(table)))
335
+ ret = uintptr(r0)
336
+ return
337
+ }
338
+
339
+ func RtlVirtualUnwind(handlerType uint32, baseAddress uintptr, pc uintptr, entry uintptr, ctxt uintptr, data *uintptr, frame *uintptr, ctxptrs *byte) (ret uintptr) {
340
+ r0, _, _ := syscall.Syscall9(procRtlVirtualUnwind.Addr(), 8, uintptr(handlerType), uintptr(baseAddress), uintptr(pc), uintptr(entry), uintptr(ctxt), uintptr(unsafe.Pointer(data)), uintptr(unsafe.Pointer(frame)), uintptr(unsafe.Pointer(ctxptrs)), 0)
341
+ ret = uintptr(r0)
342
+ return
343
+ }
344
+
345
+ func SetFileInformationByHandle(handle syscall.Handle, fileInformationClass uint32, buf unsafe.Pointer, bufsize uint32) (err error) {
346
+ r1, _, e1 := syscall.Syscall6(procSetFileInformationByHandle.Addr(), 4, uintptr(handle), uintptr(fileInformationClass), uintptr(buf), uintptr(bufsize), 0, 0)
347
+ if r1 == 0 {
348
+ err = errnoErr(e1)
349
+ }
350
+ return
351
+ }
352
+
353
+ func UnlockFileEx(file syscall.Handle, reserved uint32, bytesLow uint32, bytesHigh uint32, overlapped *syscall.Overlapped) (err error) {
354
+ r1, _, e1 := syscall.Syscall6(procUnlockFileEx.Addr(), 5, uintptr(file), uintptr(reserved), uintptr(bytesLow), uintptr(bytesHigh), uintptr(unsafe.Pointer(overlapped)), 0)
355
+ if r1 == 0 {
356
+ err = errnoErr(e1)
357
+ }
358
+ return
359
+ }
360
+
361
+ func VirtualQuery(address uintptr, buffer *MemoryBasicInformation, length uintptr) (err error) {
362
+ r1, _, e1 := syscall.Syscall(procVirtualQuery.Addr(), 3, uintptr(address), uintptr(unsafe.Pointer(buffer)), uintptr(length))
363
+ if r1 == 0 {
364
+ err = errnoErr(e1)
365
+ }
366
+ return
367
+ }
368
+
369
+ func NetShareAdd(serverName *uint16, level uint32, buf *byte, parmErr *uint16) (neterr error) {
370
+ r0, _, _ := syscall.Syscall6(procNetShareAdd.Addr(), 4, uintptr(unsafe.Pointer(serverName)), uintptr(level), uintptr(unsafe.Pointer(buf)), uintptr(unsafe.Pointer(parmErr)), 0, 0)
371
+ if r0 != 0 {
372
+ neterr = syscall.Errno(r0)
373
+ }
374
+ return
375
+ }
376
+
377
+ func NetShareDel(serverName *uint16, netName *uint16, reserved uint32) (neterr error) {
378
+ r0, _, _ := syscall.Syscall(procNetShareDel.Addr(), 3, uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(netName)), uintptr(reserved))
379
+ if r0 != 0 {
380
+ neterr = syscall.Errno(r0)
381
+ }
382
+ return
383
+ }
384
+
385
+ func NetUserGetLocalGroups(serverName *uint16, userName *uint16, level uint32, flags uint32, buf **byte, prefMaxLen uint32, entriesRead *uint32, totalEntries *uint32) (neterr error) {
386
+ r0, _, _ := syscall.Syscall9(procNetUserGetLocalGroups.Addr(), 8, uintptr(unsafe.Pointer(serverName)), uintptr(unsafe.Pointer(userName)), uintptr(level), uintptr(flags), uintptr(unsafe.Pointer(buf)), uintptr(prefMaxLen), uintptr(unsafe.Pointer(entriesRead)), uintptr(unsafe.Pointer(totalEntries)), 0)
387
+ if r0 != 0 {
388
+ neterr = syscall.Errno(r0)
389
+ }
390
+ return
391
+ }
392
+
393
+ func GetProcessMemoryInfo(handle syscall.Handle, memCounters *PROCESS_MEMORY_COUNTERS, cb uint32) (err error) {
394
+ r1, _, e1 := syscall.Syscall(procGetProcessMemoryInfo.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(memCounters)), uintptr(cb))
395
+ if r1 == 0 {
396
+ err = errnoErr(e1)
397
+ }
398
+ return
399
+ }
400
+
401
+ func CreateEnvironmentBlock(block **uint16, token syscall.Token, inheritExisting bool) (err error) {
402
+ var _p0 uint32
403
+ if inheritExisting {
404
+ _p0 = 1
405
+ }
406
+ r1, _, e1 := syscall.Syscall(procCreateEnvironmentBlock.Addr(), 3, uintptr(unsafe.Pointer(block)), uintptr(token), uintptr(_p0))
407
+ if r1 == 0 {
408
+ err = errnoErr(e1)
409
+ }
410
+ return
411
+ }
412
+
413
+ func DestroyEnvironmentBlock(block *uint16) (err error) {
414
+ r1, _, e1 := syscall.Syscall(procDestroyEnvironmentBlock.Addr(), 1, uintptr(unsafe.Pointer(block)), 0, 0)
415
+ if r1 == 0 {
416
+ err = errnoErr(e1)
417
+ }
418
+ return
419
+ }
420
+
421
+ func GetProfilesDirectory(dir *uint16, dirLen *uint32) (err error) {
422
+ r1, _, e1 := syscall.Syscall(procGetProfilesDirectoryW.Addr(), 2, uintptr(unsafe.Pointer(dir)), uintptr(unsafe.Pointer(dirLen)), 0)
423
+ if r1 == 0 {
424
+ err = errnoErr(e1)
425
+ }
426
+ return
427
+ }
428
+
429
+ func WSASocket(af int32, typ int32, protocol int32, protinfo *syscall.WSAProtocolInfo, group uint32, flags uint32) (handle syscall.Handle, err error) {
430
+ r0, _, e1 := syscall.Syscall6(procWSASocketW.Addr(), 6, uintptr(af), uintptr(typ), uintptr(protocol), uintptr(unsafe.Pointer(protinfo)), uintptr(group), uintptr(flags))
431
+ handle = syscall.Handle(r0)
432
+ if handle == syscall.InvalidHandle {
433
+ err = errnoErr(e1)
434
+ }
435
+ return
436
+ }
platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_10_good ADDED
Binary file (2.2 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_11_good ADDED
Binary file (2.78 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_19_good ADDED
Binary file (28.2 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_21_good ADDED
Binary file (6.74 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_5_good ADDED
Binary file (42.2 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_7_good ADDED
Binary file (1.97 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/http_1_9_good ADDED
Binary file (2.19 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_10_good ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0608236a31dadbff8a3f91dcc3c94399a3429ceeb30d7007fd9dbd0e85a85614
3
+ size 370999
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_11_good ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9878383c755505fbd034e542490c7b9ce49e6d9c33432a725968a2df067a4f28
3
+ size 370129
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_19_good ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f2706ed5beddd2be37cca3c48108aaf683fc9d9ea2778329653b9518fc460268
3
+ size 322338
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_21_good ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c9077aadea706ca77a0044b5b350917db94cf7ed2da777f17e6cd7b2ca64f09
3
+ size 353725
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_5_good ADDED
Binary file (7.45 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_5_unordered ADDED
Binary file (8.19 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_7_good ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:50fb7e557d495520d95a97539716638ca74af88e1ed361d0e9823b2d5e34db54
3
+ size 396526
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_1_9_good ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:439de9dc3b154052f4d6b8d2c1c9fbde8b8964a8242342e99c224f461b91bf43
3
+ size 365129
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_10_good ADDED
Binary file (6.34 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_11_good ADDED
Binary file (4.88 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_19_good ADDED
Binary file (7.45 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_21_good ADDED
Binary file (5 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_5_good ADDED
Binary file (7 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_7_good ADDED
Binary file (2.06 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/stress_start_stop_1_9_good ADDED
Binary file (6.27 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_11_good ADDED
Binary file (2 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_19_good ADDED
Binary file (1.92 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/testdata/user_task_region_1_21_good ADDED
Binary file (2.4 kB). View file
 
platform/dbops/binaries/go/go/src/internal/trace/traceviewer/emitter.go ADDED
@@ -0,0 +1,813 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package traceviewer
6
+
7
+ import (
8
+ "encoding/json"
9
+ "fmt"
10
+ "internal/trace"
11
+ "internal/trace/traceviewer/format"
12
+ "io"
13
+ "strconv"
14
+ "time"
15
+ )
16
+
17
+ type TraceConsumer struct {
18
+ ConsumeTimeUnit func(unit string)
19
+ ConsumeViewerEvent func(v *format.Event, required bool)
20
+ ConsumeViewerFrame func(key string, f format.Frame)
21
+ Flush func()
22
+ }
23
+
24
+ // ViewerDataTraceConsumer returns a TraceConsumer that writes to w. The
25
+ // startIdx and endIdx are used for splitting large traces. They refer to
26
+ // indexes in the traceEvents output array, not the events in the trace input.
27
+ func ViewerDataTraceConsumer(w io.Writer, startIdx, endIdx int64) TraceConsumer {
28
+ allFrames := make(map[string]format.Frame)
29
+ requiredFrames := make(map[string]format.Frame)
30
+ enc := json.NewEncoder(w)
31
+ written := 0
32
+ index := int64(-1)
33
+
34
+ io.WriteString(w, "{")
35
+ return TraceConsumer{
36
+ ConsumeTimeUnit: func(unit string) {
37
+ io.WriteString(w, `"displayTimeUnit":`)
38
+ enc.Encode(unit)
39
+ io.WriteString(w, ",")
40
+ },
41
+ ConsumeViewerEvent: func(v *format.Event, required bool) {
42
+ index++
43
+ if !required && (index < startIdx || index > endIdx) {
44
+ // not in the range. Skip!
45
+ return
46
+ }
47
+ WalkStackFrames(allFrames, v.Stack, func(id int) {
48
+ s := strconv.Itoa(id)
49
+ requiredFrames[s] = allFrames[s]
50
+ })
51
+ WalkStackFrames(allFrames, v.EndStack, func(id int) {
52
+ s := strconv.Itoa(id)
53
+ requiredFrames[s] = allFrames[s]
54
+ })
55
+ if written == 0 {
56
+ io.WriteString(w, `"traceEvents": [`)
57
+ }
58
+ if written > 0 {
59
+ io.WriteString(w, ",")
60
+ }
61
+ enc.Encode(v)
62
+ // TODO(mknyszek): get rid of the extra \n inserted by enc.Encode.
63
+ // Same should be applied to splittingTraceConsumer.
64
+ written++
65
+ },
66
+ ConsumeViewerFrame: func(k string, v format.Frame) {
67
+ allFrames[k] = v
68
+ },
69
+ Flush: func() {
70
+ io.WriteString(w, `], "stackFrames":`)
71
+ enc.Encode(requiredFrames)
72
+ io.WriteString(w, `}`)
73
+ },
74
+ }
75
+ }
76
+
77
+ func SplittingTraceConsumer(max int) (*splitter, TraceConsumer) {
78
+ type eventSz struct {
79
+ Time float64
80
+ Sz int
81
+ Frames []int
82
+ }
83
+
84
+ var (
85
+ // data.Frames contains only the frames for required events.
86
+ data = format.Data{Frames: make(map[string]format.Frame)}
87
+
88
+ allFrames = make(map[string]format.Frame)
89
+
90
+ sizes []eventSz
91
+ cw countingWriter
92
+ )
93
+
94
+ s := new(splitter)
95
+
96
+ return s, TraceConsumer{
97
+ ConsumeTimeUnit: func(unit string) {
98
+ data.TimeUnit = unit
99
+ },
100
+ ConsumeViewerEvent: func(v *format.Event, required bool) {
101
+ if required {
102
+ // Store required events inside data so flush
103
+ // can include them in the required part of the
104
+ // trace.
105
+ data.Events = append(data.Events, v)
106
+ WalkStackFrames(allFrames, v.Stack, func(id int) {
107
+ s := strconv.Itoa(id)
108
+ data.Frames[s] = allFrames[s]
109
+ })
110
+ WalkStackFrames(allFrames, v.EndStack, func(id int) {
111
+ s := strconv.Itoa(id)
112
+ data.Frames[s] = allFrames[s]
113
+ })
114
+ return
115
+ }
116
+ enc := json.NewEncoder(&cw)
117
+ enc.Encode(v)
118
+ size := eventSz{Time: v.Time, Sz: cw.size + 1} // +1 for ",".
119
+ // Add referenced stack frames. Their size is computed
120
+ // in flush, where we can dedup across events.
121
+ WalkStackFrames(allFrames, v.Stack, func(id int) {
122
+ size.Frames = append(size.Frames, id)
123
+ })
124
+ WalkStackFrames(allFrames, v.EndStack, func(id int) {
125
+ size.Frames = append(size.Frames, id) // This may add duplicates. We'll dedup later.
126
+ })
127
+ sizes = append(sizes, size)
128
+ cw.size = 0
129
+ },
130
+ ConsumeViewerFrame: func(k string, v format.Frame) {
131
+ allFrames[k] = v
132
+ },
133
+ Flush: func() {
134
+ // Calculate size of the mandatory part of the trace.
135
+ // This includes thread names and stack frames for
136
+ // required events.
137
+ cw.size = 0
138
+ enc := json.NewEncoder(&cw)
139
+ enc.Encode(data)
140
+ requiredSize := cw.size
141
+
142
+ // Then calculate size of each individual event and
143
+ // their stack frames, grouping them into ranges. We
144
+ // only include stack frames relevant to the events in
145
+ // the range to reduce overhead.
146
+
147
+ var (
148
+ start = 0
149
+
150
+ eventsSize = 0
151
+
152
+ frames = make(map[string]format.Frame)
153
+ framesSize = 0
154
+ )
155
+ for i, ev := range sizes {
156
+ eventsSize += ev.Sz
157
+
158
+ // Add required stack frames. Note that they
159
+ // may already be in the map.
160
+ for _, id := range ev.Frames {
161
+ s := strconv.Itoa(id)
162
+ _, ok := frames[s]
163
+ if ok {
164
+ continue
165
+ }
166
+ f := allFrames[s]
167
+ frames[s] = f
168
+ framesSize += stackFrameEncodedSize(uint(id), f)
169
+ }
170
+
171
+ total := requiredSize + framesSize + eventsSize
172
+ if total < max {
173
+ continue
174
+ }
175
+
176
+ // Reached max size, commit this range and
177
+ // start a new range.
178
+ startTime := time.Duration(sizes[start].Time * 1000)
179
+ endTime := time.Duration(ev.Time * 1000)
180
+ s.Ranges = append(s.Ranges, Range{
181
+ Name: fmt.Sprintf("%v-%v", startTime, endTime),
182
+ Start: start,
183
+ End: i + 1,
184
+ StartTime: int64(startTime),
185
+ EndTime: int64(endTime),
186
+ })
187
+ start = i + 1
188
+ frames = make(map[string]format.Frame)
189
+ framesSize = 0
190
+ eventsSize = 0
191
+ }
192
+ if len(s.Ranges) <= 1 {
193
+ s.Ranges = nil
194
+ return
195
+ }
196
+
197
+ if end := len(sizes) - 1; start < end {
198
+ s.Ranges = append(s.Ranges, Range{
199
+ Name: fmt.Sprintf("%v-%v", time.Duration(sizes[start].Time*1000), time.Duration(sizes[end].Time*1000)),
200
+ Start: start,
201
+ End: end,
202
+ StartTime: int64(sizes[start].Time * 1000),
203
+ EndTime: int64(sizes[end].Time * 1000),
204
+ })
205
+ }
206
+ },
207
+ }
208
+ }
209
+
210
+ type splitter struct {
211
+ Ranges []Range
212
+ }
213
+
214
+ type countingWriter struct {
215
+ size int
216
+ }
217
+
218
+ func (cw *countingWriter) Write(data []byte) (int, error) {
219
+ cw.size += len(data)
220
+ return len(data), nil
221
+ }
222
+
223
+ func stackFrameEncodedSize(id uint, f format.Frame) int {
224
+ // We want to know the marginal size of traceviewer.Data.Frames for
225
+ // each event. Running full JSON encoding of the map for each event is
226
+ // far too slow.
227
+ //
228
+ // Since the format is fixed, we can easily compute the size without
229
+ // encoding.
230
+ //
231
+ // A single entry looks like one of the following:
232
+ //
233
+ // "1":{"name":"main.main:30"},
234
+ // "10":{"name":"pkg.NewSession:173","parent":9},
235
+ //
236
+ // The parent is omitted if 0. The trailing comma is omitted from the
237
+ // last entry, but we don't need that much precision.
238
+ const (
239
+ baseSize = len(`"`) + len(`":{"name":"`) + len(`"},`)
240
+
241
+ // Don't count the trailing quote on the name, as that is
242
+ // counted in baseSize.
243
+ parentBaseSize = len(`,"parent":`)
244
+ )
245
+
246
+ size := baseSize
247
+
248
+ size += len(f.Name)
249
+
250
+ // Bytes for id (always positive).
251
+ for id > 0 {
252
+ size += 1
253
+ id /= 10
254
+ }
255
+
256
+ if f.Parent > 0 {
257
+ size += parentBaseSize
258
+ // Bytes for parent (always positive).
259
+ for f.Parent > 0 {
260
+ size += 1
261
+ f.Parent /= 10
262
+ }
263
+ }
264
+
265
+ return size
266
+ }
267
+
268
+ // WalkStackFrames calls fn for id and all of its parent frames from allFrames.
269
+ func WalkStackFrames(allFrames map[string]format.Frame, id int, fn func(id int)) {
270
+ for id != 0 {
271
+ f, ok := allFrames[strconv.Itoa(id)]
272
+ if !ok {
273
+ break
274
+ }
275
+ fn(id)
276
+ id = f.Parent
277
+ }
278
+ }
279
+
280
+ type Mode int
281
+
282
+ const (
283
+ ModeGoroutineOriented Mode = 1 << iota
284
+ ModeTaskOriented
285
+ ModeThreadOriented // Mutually exclusive with ModeGoroutineOriented.
286
+ )
287
+
288
+ // NewEmitter returns a new Emitter that writes to c. The rangeStart and
289
+ // rangeEnd args are used for splitting large traces.
290
+ func NewEmitter(c TraceConsumer, rangeStart, rangeEnd time.Duration) *Emitter {
291
+ c.ConsumeTimeUnit("ns")
292
+
293
+ return &Emitter{
294
+ c: c,
295
+ rangeStart: rangeStart,
296
+ rangeEnd: rangeEnd,
297
+ frameTree: frameNode{children: make(map[uint64]frameNode)},
298
+ resources: make(map[uint64]string),
299
+ tasks: make(map[uint64]task),
300
+ }
301
+ }
302
+
303
+ type Emitter struct {
304
+ c TraceConsumer
305
+ rangeStart time.Duration
306
+ rangeEnd time.Duration
307
+
308
+ heapStats, prevHeapStats heapStats
309
+ gstates, prevGstates [gStateCount]int64
310
+ threadStats, prevThreadStats [threadStateCount]int64
311
+ gomaxprocs uint64
312
+ frameTree frameNode
313
+ frameSeq int
314
+ arrowSeq uint64
315
+ filter func(uint64) bool
316
+ resourceType string
317
+ resources map[uint64]string
318
+ focusResource uint64
319
+ tasks map[uint64]task
320
+ asyncSliceSeq uint64
321
+ }
322
+
323
+ type task struct {
324
+ name string
325
+ sortIndex int
326
+ }
327
+
328
+ func (e *Emitter) Gomaxprocs(v uint64) {
329
+ if v > e.gomaxprocs {
330
+ e.gomaxprocs = v
331
+ }
332
+ }
333
+
334
+ func (e *Emitter) Resource(id uint64, name string) {
335
+ if e.filter != nil && !e.filter(id) {
336
+ return
337
+ }
338
+ e.resources[id] = name
339
+ }
340
+
341
+ func (e *Emitter) SetResourceType(name string) {
342
+ e.resourceType = name
343
+ }
344
+
345
+ func (e *Emitter) SetResourceFilter(filter func(uint64) bool) {
346
+ e.filter = filter
347
+ }
348
+
349
+ func (e *Emitter) Task(id uint64, name string, sortIndex int) {
350
+ e.tasks[id] = task{name, sortIndex}
351
+ }
352
+
353
+ func (e *Emitter) Slice(s SliceEvent) {
354
+ if e.filter != nil && !e.filter(s.Resource) {
355
+ return
356
+ }
357
+ e.slice(s, format.ProcsSection, "")
358
+ }
359
+
360
+ func (e *Emitter) TaskSlice(s SliceEvent) {
361
+ e.slice(s, format.TasksSection, pickTaskColor(s.Resource))
362
+ }
363
+
364
+ func (e *Emitter) slice(s SliceEvent, sectionID uint64, cname string) {
365
+ if !e.tsWithinRange(s.Ts) && !e.tsWithinRange(s.Ts+s.Dur) {
366
+ return
367
+ }
368
+ e.OptionalEvent(&format.Event{
369
+ Name: s.Name,
370
+ Phase: "X",
371
+ Time: viewerTime(s.Ts),
372
+ Dur: viewerTime(s.Dur),
373
+ PID: sectionID,
374
+ TID: s.Resource,
375
+ Stack: s.Stack,
376
+ EndStack: s.EndStack,
377
+ Arg: s.Arg,
378
+ Cname: cname,
379
+ })
380
+ }
381
+
382
+ type SliceEvent struct {
383
+ Name string
384
+ Ts time.Duration
385
+ Dur time.Duration
386
+ Resource uint64
387
+ Stack int
388
+ EndStack int
389
+ Arg any
390
+ }
391
+
392
+ func (e *Emitter) AsyncSlice(s AsyncSliceEvent) {
393
+ if !e.tsWithinRange(s.Ts) && !e.tsWithinRange(s.Ts+s.Dur) {
394
+ return
395
+ }
396
+ if e.filter != nil && !e.filter(s.Resource) {
397
+ return
398
+ }
399
+ cname := ""
400
+ if s.TaskColorIndex != 0 {
401
+ cname = pickTaskColor(s.TaskColorIndex)
402
+ }
403
+ e.asyncSliceSeq++
404
+ e.OptionalEvent(&format.Event{
405
+ Category: s.Category,
406
+ Name: s.Name,
407
+ Phase: "b",
408
+ Time: viewerTime(s.Ts),
409
+ TID: s.Resource,
410
+ ID: e.asyncSliceSeq,
411
+ Scope: s.Scope,
412
+ Stack: s.Stack,
413
+ Cname: cname,
414
+ })
415
+ e.OptionalEvent(&format.Event{
416
+ Category: s.Category,
417
+ Name: s.Name,
418
+ Phase: "e",
419
+ Time: viewerTime(s.Ts + s.Dur),
420
+ TID: s.Resource,
421
+ ID: e.asyncSliceSeq,
422
+ Scope: s.Scope,
423
+ Stack: s.EndStack,
424
+ Arg: s.Arg,
425
+ Cname: cname,
426
+ })
427
+ }
428
+
429
+ type AsyncSliceEvent struct {
430
+ SliceEvent
431
+ Category string
432
+ Scope string
433
+ TaskColorIndex uint64 // Take on the same color as the task with this ID.
434
+ }
435
+
436
+ func (e *Emitter) Instant(i InstantEvent) {
437
+ if !e.tsWithinRange(i.Ts) {
438
+ return
439
+ }
440
+ if e.filter != nil && !e.filter(i.Resource) {
441
+ return
442
+ }
443
+ cname := ""
444
+ e.OptionalEvent(&format.Event{
445
+ Name: i.Name,
446
+ Category: i.Category,
447
+ Phase: "I",
448
+ Scope: "t",
449
+ Time: viewerTime(i.Ts),
450
+ PID: format.ProcsSection,
451
+ TID: i.Resource,
452
+ Stack: i.Stack,
453
+ Cname: cname,
454
+ Arg: i.Arg,
455
+ })
456
+ }
457
+
458
+ type InstantEvent struct {
459
+ Ts time.Duration
460
+ Name string
461
+ Category string
462
+ Resource uint64
463
+ Stack int
464
+ Arg any
465
+ }
466
+
467
+ func (e *Emitter) Arrow(a ArrowEvent) {
468
+ if e.filter != nil && (!e.filter(a.FromResource) || !e.filter(a.ToResource)) {
469
+ return
470
+ }
471
+ e.arrow(a, format.ProcsSection)
472
+ }
473
+
474
+ func (e *Emitter) TaskArrow(a ArrowEvent) {
475
+ e.arrow(a, format.TasksSection)
476
+ }
477
+
478
+ func (e *Emitter) arrow(a ArrowEvent, sectionID uint64) {
479
+ if !e.tsWithinRange(a.Start) || !e.tsWithinRange(a.End) {
480
+ return
481
+ }
482
+ e.arrowSeq++
483
+ e.OptionalEvent(&format.Event{
484
+ Name: a.Name,
485
+ Phase: "s",
486
+ TID: a.FromResource,
487
+ PID: sectionID,
488
+ ID: e.arrowSeq,
489
+ Time: viewerTime(a.Start),
490
+ Stack: a.FromStack,
491
+ })
492
+ e.OptionalEvent(&format.Event{
493
+ Name: a.Name,
494
+ Phase: "t",
495
+ TID: a.ToResource,
496
+ PID: sectionID,
497
+ ID: e.arrowSeq,
498
+ Time: viewerTime(a.End),
499
+ })
500
+ }
501
+
502
+ type ArrowEvent struct {
503
+ Name string
504
+ Start time.Duration
505
+ End time.Duration
506
+ FromResource uint64
507
+ FromStack int
508
+ ToResource uint64
509
+ }
510
+
511
+ func (e *Emitter) Event(ev *format.Event) {
512
+ e.c.ConsumeViewerEvent(ev, true)
513
+ }
514
+
515
+ func (e *Emitter) HeapAlloc(ts time.Duration, v uint64) {
516
+ e.heapStats.heapAlloc = v
517
+ e.emitHeapCounters(ts)
518
+ }
519
+
520
+ func (e *Emitter) Focus(id uint64) {
521
+ e.focusResource = id
522
+ }
523
+
524
+ func (e *Emitter) GoroutineTransition(ts time.Duration, from, to GState) {
525
+ e.gstates[from]--
526
+ e.gstates[to]++
527
+ if e.prevGstates == e.gstates {
528
+ return
529
+ }
530
+ if e.tsWithinRange(ts) {
531
+ e.OptionalEvent(&format.Event{
532
+ Name: "Goroutines",
533
+ Phase: "C",
534
+ Time: viewerTime(ts),
535
+ PID: 1,
536
+ Arg: &format.GoroutineCountersArg{
537
+ Running: uint64(e.gstates[GRunning]),
538
+ Runnable: uint64(e.gstates[GRunnable]),
539
+ GCWaiting: uint64(e.gstates[GWaitingGC]),
540
+ },
541
+ })
542
+ }
543
+ e.prevGstates = e.gstates
544
+ }
545
+
546
+ func (e *Emitter) IncThreadStateCount(ts time.Duration, state ThreadState, delta int64) {
547
+ e.threadStats[state] += delta
548
+ if e.prevThreadStats == e.threadStats {
549
+ return
550
+ }
551
+ if e.tsWithinRange(ts) {
552
+ e.OptionalEvent(&format.Event{
553
+ Name: "Threads",
554
+ Phase: "C",
555
+ Time: viewerTime(ts),
556
+ PID: 1,
557
+ Arg: &format.ThreadCountersArg{
558
+ Running: int64(e.threadStats[ThreadStateRunning]),
559
+ InSyscall: int64(e.threadStats[ThreadStateInSyscall]),
560
+ // TODO(mknyszek): Why is InSyscallRuntime not included here?
561
+ },
562
+ })
563
+ }
564
+ e.prevThreadStats = e.threadStats
565
+ }
566
+
567
+ func (e *Emitter) HeapGoal(ts time.Duration, v uint64) {
568
+ // This cutoff at 1 PiB is a Workaround for https://github.com/golang/go/issues/63864.
569
+ //
570
+ // TODO(mknyszek): Remove this once the problem has been fixed.
571
+ const PB = 1 << 50
572
+ if v > PB {
573
+ v = 0
574
+ }
575
+ e.heapStats.nextGC = v
576
+ e.emitHeapCounters(ts)
577
+ }
578
+
579
+ func (e *Emitter) emitHeapCounters(ts time.Duration) {
580
+ if e.prevHeapStats == e.heapStats {
581
+ return
582
+ }
583
+ diff := uint64(0)
584
+ if e.heapStats.nextGC > e.heapStats.heapAlloc {
585
+ diff = e.heapStats.nextGC - e.heapStats.heapAlloc
586
+ }
587
+ if e.tsWithinRange(ts) {
588
+ e.OptionalEvent(&format.Event{
589
+ Name: "Heap",
590
+ Phase: "C",
591
+ Time: viewerTime(ts),
592
+ PID: 1,
593
+ Arg: &format.HeapCountersArg{Allocated: e.heapStats.heapAlloc, NextGC: diff},
594
+ })
595
+ }
596
+ e.prevHeapStats = e.heapStats
597
+ }
598
+
599
+ // Err returns an error if the emitter is in an invalid state.
600
+ func (e *Emitter) Err() error {
601
+ if e.gstates[GRunnable] < 0 || e.gstates[GRunning] < 0 || e.threadStats[ThreadStateInSyscall] < 0 || e.threadStats[ThreadStateInSyscallRuntime] < 0 {
602
+ return fmt.Errorf(
603
+ "runnable=%d running=%d insyscall=%d insyscallRuntime=%d",
604
+ e.gstates[GRunnable],
605
+ e.gstates[GRunning],
606
+ e.threadStats[ThreadStateInSyscall],
607
+ e.threadStats[ThreadStateInSyscallRuntime],
608
+ )
609
+ }
610
+ return nil
611
+ }
612
+
613
+ func (e *Emitter) tsWithinRange(ts time.Duration) bool {
614
+ return e.rangeStart <= ts && ts <= e.rangeEnd
615
+ }
616
+
617
+ // OptionalEvent emits ev if it's within the time range of of the consumer, i.e.
618
+ // the selected trace split range.
619
+ func (e *Emitter) OptionalEvent(ev *format.Event) {
620
+ e.c.ConsumeViewerEvent(ev, false)
621
+ }
622
+
623
+ func (e *Emitter) Flush() {
624
+ e.processMeta(format.StatsSection, "STATS", 0)
625
+
626
+ if len(e.tasks) != 0 {
627
+ e.processMeta(format.TasksSection, "TASKS", 1)
628
+ }
629
+ for id, task := range e.tasks {
630
+ e.threadMeta(format.TasksSection, id, task.name, task.sortIndex)
631
+ }
632
+
633
+ e.processMeta(format.ProcsSection, e.resourceType, 2)
634
+
635
+ e.threadMeta(format.ProcsSection, trace.GCP, "GC", -6)
636
+ e.threadMeta(format.ProcsSection, trace.NetpollP, "Network", -5)
637
+ e.threadMeta(format.ProcsSection, trace.TimerP, "Timers", -4)
638
+ e.threadMeta(format.ProcsSection, trace.SyscallP, "Syscalls", -3)
639
+
640
+ for id, name := range e.resources {
641
+ priority := int(id)
642
+ if e.focusResource != 0 && id == e.focusResource {
643
+ // Put the focus goroutine on top.
644
+ priority = -2
645
+ }
646
+ e.threadMeta(format.ProcsSection, id, name, priority)
647
+ }
648
+
649
+ e.c.Flush()
650
+ }
651
+
652
+ func (e *Emitter) threadMeta(sectionID, tid uint64, name string, priority int) {
653
+ e.Event(&format.Event{
654
+ Name: "thread_name",
655
+ Phase: "M",
656
+ PID: sectionID,
657
+ TID: tid,
658
+ Arg: &format.NameArg{Name: name},
659
+ })
660
+ e.Event(&format.Event{
661
+ Name: "thread_sort_index",
662
+ Phase: "M",
663
+ PID: sectionID,
664
+ TID: tid,
665
+ Arg: &format.SortIndexArg{Index: priority},
666
+ })
667
+ }
668
+
669
+ func (e *Emitter) processMeta(sectionID uint64, name string, priority int) {
670
+ e.Event(&format.Event{
671
+ Name: "process_name",
672
+ Phase: "M",
673
+ PID: sectionID,
674
+ Arg: &format.NameArg{Name: name},
675
+ })
676
+ e.Event(&format.Event{
677
+ Name: "process_sort_index",
678
+ Phase: "M",
679
+ PID: sectionID,
680
+ Arg: &format.SortIndexArg{Index: priority},
681
+ })
682
+ }
683
+
684
+ // Stack emits the given frames and returns a unique id for the stack. No
685
+ // pointers to the given data are being retained beyond the call to Stack.
686
+ func (e *Emitter) Stack(stk []*trace.Frame) int {
687
+ return e.buildBranch(e.frameTree, stk)
688
+ }
689
+
690
+ // buildBranch builds one branch in the prefix tree rooted at ctx.frameTree.
691
+ func (e *Emitter) buildBranch(parent frameNode, stk []*trace.Frame) int {
692
+ if len(stk) == 0 {
693
+ return parent.id
694
+ }
695
+ last := len(stk) - 1
696
+ frame := stk[last]
697
+ stk = stk[:last]
698
+
699
+ node, ok := parent.children[frame.PC]
700
+ if !ok {
701
+ e.frameSeq++
702
+ node.id = e.frameSeq
703
+ node.children = make(map[uint64]frameNode)
704
+ parent.children[frame.PC] = node
705
+ e.c.ConsumeViewerFrame(strconv.Itoa(node.id), format.Frame{Name: fmt.Sprintf("%v:%v", frame.Fn, frame.Line), Parent: parent.id})
706
+ }
707
+ return e.buildBranch(node, stk)
708
+ }
709
+
710
+ type heapStats struct {
711
+ heapAlloc uint64
712
+ nextGC uint64
713
+ }
714
+
715
+ func viewerTime(t time.Duration) float64 {
716
+ return float64(t) / float64(time.Microsecond)
717
+ }
718
+
719
+ type GState int
720
+
721
+ const (
722
+ GDead GState = iota
723
+ GRunnable
724
+ GRunning
725
+ GWaiting
726
+ GWaitingGC
727
+
728
+ gStateCount
729
+ )
730
+
731
+ type ThreadState int
732
+
733
+ const (
734
+ ThreadStateInSyscall ThreadState = iota
735
+ ThreadStateInSyscallRuntime
736
+ ThreadStateRunning
737
+
738
+ threadStateCount
739
+ )
740
+
741
+ type frameNode struct {
742
+ id int
743
+ children map[uint64]frameNode
744
+ }
745
+
746
+ // Mapping from more reasonable color names to the reserved color names in
747
+ // https://github.com/catapult-project/catapult/blob/master/tracing/tracing/base/color_scheme.html#L50
748
+ // The chrome trace viewer allows only those as cname values.
749
+ const (
750
+ colorLightMauve = "thread_state_uninterruptible" // 182, 125, 143
751
+ colorOrange = "thread_state_iowait" // 255, 140, 0
752
+ colorSeafoamGreen = "thread_state_running" // 126, 200, 148
753
+ colorVistaBlue = "thread_state_runnable" // 133, 160, 210
754
+ colorTan = "thread_state_unknown" // 199, 155, 125
755
+ colorIrisBlue = "background_memory_dump" // 0, 180, 180
756
+ colorMidnightBlue = "light_memory_dump" // 0, 0, 180
757
+ colorDeepMagenta = "detailed_memory_dump" // 180, 0, 180
758
+ colorBlue = "vsync_highlight_color" // 0, 0, 255
759
+ colorGrey = "generic_work" // 125, 125, 125
760
+ colorGreen = "good" // 0, 125, 0
761
+ colorDarkGoldenrod = "bad" // 180, 125, 0
762
+ colorPeach = "terrible" // 180, 0, 0
763
+ colorBlack = "black" // 0, 0, 0
764
+ colorLightGrey = "grey" // 221, 221, 221
765
+ colorWhite = "white" // 255, 255, 255
766
+ colorYellow = "yellow" // 255, 255, 0
767
+ colorOlive = "olive" // 100, 100, 0
768
+ colorCornflowerBlue = "rail_response" // 67, 135, 253
769
+ colorSunsetOrange = "rail_animation" // 244, 74, 63
770
+ colorTangerine = "rail_idle" // 238, 142, 0
771
+ colorShamrockGreen = "rail_load" // 13, 168, 97
772
+ colorGreenishYellow = "startup" // 230, 230, 0
773
+ colorDarkGrey = "heap_dump_stack_frame" // 128, 128, 128
774
+ colorTawny = "heap_dump_child_node_arrow" // 204, 102, 0
775
+ colorLemon = "cq_build_running" // 255, 255, 119
776
+ colorLime = "cq_build_passed" // 153, 238, 102
777
+ colorPink = "cq_build_failed" // 238, 136, 136
778
+ colorSilver = "cq_build_abandoned" // 187, 187, 187
779
+ colorManzGreen = "cq_build_attempt_runnig" // 222, 222, 75
780
+ colorKellyGreen = "cq_build_attempt_passed" // 108, 218, 35
781
+ colorAnotherGrey = "cq_build_attempt_failed" // 187, 187, 187
782
+ )
783
+
784
+ var colorForTask = []string{
785
+ colorLightMauve,
786
+ colorOrange,
787
+ colorSeafoamGreen,
788
+ colorVistaBlue,
789
+ colorTan,
790
+ colorMidnightBlue,
791
+ colorIrisBlue,
792
+ colorDeepMagenta,
793
+ colorGreen,
794
+ colorDarkGoldenrod,
795
+ colorPeach,
796
+ colorOlive,
797
+ colorCornflowerBlue,
798
+ colorSunsetOrange,
799
+ colorTangerine,
800
+ colorShamrockGreen,
801
+ colorTawny,
802
+ colorLemon,
803
+ colorLime,
804
+ colorPink,
805
+ colorSilver,
806
+ colorManzGreen,
807
+ colorKellyGreen,
808
+ }
809
+
810
+ func pickTaskColor(id uint64) string {
811
+ idx := id % uint64(len(colorForTask))
812
+ return colorForTask[idx]
813
+ }
platform/dbops/binaries/go/go/src/internal/trace/traceviewer/format/format.go ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2020 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Package traceviewer provides definitions of the JSON data structures
6
+ // used by the Chrome trace viewer.
7
+ //
8
+ // The official description of the format is in this file:
9
+ // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
10
+ //
11
+ // Note: This can't be part of the parent traceviewer package as that would
12
+ // throw. go_bootstrap cannot depend on the cgo version of package net in ./make.bash.
13
+ package format
14
+
15
+ type Data struct {
16
+ Events []*Event `json:"traceEvents"`
17
+ Frames map[string]Frame `json:"stackFrames"`
18
+ TimeUnit string `json:"displayTimeUnit"`
19
+ }
20
+
21
+ type Event struct {
22
+ Name string `json:"name,omitempty"`
23
+ Phase string `json:"ph"`
24
+ Scope string `json:"s,omitempty"`
25
+ Time float64 `json:"ts"`
26
+ Dur float64 `json:"dur,omitempty"`
27
+ PID uint64 `json:"pid"`
28
+ TID uint64 `json:"tid"`
29
+ ID uint64 `json:"id,omitempty"`
30
+ BindPoint string `json:"bp,omitempty"`
31
+ Stack int `json:"sf,omitempty"`
32
+ EndStack int `json:"esf,omitempty"`
33
+ Arg any `json:"args,omitempty"`
34
+ Cname string `json:"cname,omitempty"`
35
+ Category string `json:"cat,omitempty"`
36
+ }
37
+
38
+ type Frame struct {
39
+ Name string `json:"name"`
40
+ Parent int `json:"parent,omitempty"`
41
+ }
42
+
43
+ type NameArg struct {
44
+ Name string `json:"name"`
45
+ }
46
+
47
+ type BlockedArg struct {
48
+ Blocked string `json:"blocked"`
49
+ }
50
+
51
+ type SortIndexArg struct {
52
+ Index int `json:"sort_index"`
53
+ }
54
+
55
+ type HeapCountersArg struct {
56
+ Allocated uint64
57
+ NextGC uint64
58
+ }
59
+
60
+ const (
61
+ ProcsSection = 0 // where Goroutines or per-P timelines are presented.
62
+ StatsSection = 1 // where counters are presented.
63
+ TasksSection = 2 // where Task hierarchy & timeline is presented.
64
+ )
65
+
66
+ type GoroutineCountersArg struct {
67
+ Running uint64
68
+ Runnable uint64
69
+ GCWaiting uint64
70
+ }
71
+
72
+ type ThreadCountersArg struct {
73
+ Running int64
74
+ InSyscall int64
75
+ }
76
+
77
+ type ThreadIDArg struct {
78
+ ThreadID uint64
79
+ }
platform/dbops/binaries/go/go/src/internal/trace/traceviewer/histogram.go ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package traceviewer
6
+
7
+ import (
8
+ "fmt"
9
+ "html/template"
10
+ "math"
11
+ "strings"
12
+ "time"
13
+ )
14
+
15
+ // TimeHistogram is an high-dynamic-range histogram for durations.
16
+ type TimeHistogram struct {
17
+ Count int
18
+ Buckets []int
19
+ MinBucket, MaxBucket int
20
+ }
21
+
22
+ // Five buckets for every power of 10.
23
+ var logDiv = math.Log(math.Pow(10, 1.0/5))
24
+
25
+ // Add adds a single sample to the histogram.
26
+ func (h *TimeHistogram) Add(d time.Duration) {
27
+ var bucket int
28
+ if d > 0 {
29
+ bucket = int(math.Log(float64(d)) / logDiv)
30
+ }
31
+ if len(h.Buckets) <= bucket {
32
+ h.Buckets = append(h.Buckets, make([]int, bucket-len(h.Buckets)+1)...)
33
+ h.Buckets = h.Buckets[:cap(h.Buckets)]
34
+ }
35
+ h.Buckets[bucket]++
36
+ if bucket < h.MinBucket || h.MaxBucket == 0 {
37
+ h.MinBucket = bucket
38
+ }
39
+ if bucket > h.MaxBucket {
40
+ h.MaxBucket = bucket
41
+ }
42
+ h.Count++
43
+ }
44
+
45
+ // BucketMin returns the minimum duration value for a provided bucket.
46
+ func (h *TimeHistogram) BucketMin(bucket int) time.Duration {
47
+ return time.Duration(math.Exp(float64(bucket) * logDiv))
48
+ }
49
+
50
+ // ToHTML renders the histogram as HTML.
51
+ func (h *TimeHistogram) ToHTML(urlmaker func(min, max time.Duration) string) template.HTML {
52
+ if h == nil || h.Count == 0 {
53
+ return template.HTML("")
54
+ }
55
+
56
+ const barWidth = 400
57
+
58
+ maxCount := 0
59
+ for _, count := range h.Buckets {
60
+ if count > maxCount {
61
+ maxCount = count
62
+ }
63
+ }
64
+
65
+ w := new(strings.Builder)
66
+ fmt.Fprintf(w, `<table>`)
67
+ for i := h.MinBucket; i <= h.MaxBucket; i++ {
68
+ // Tick label.
69
+ if h.Buckets[i] > 0 {
70
+ fmt.Fprintf(w, `<tr><td class="histoTime" align="right"><a href=%s>%s</a></td>`, urlmaker(h.BucketMin(i), h.BucketMin(i+1)), h.BucketMin(i))
71
+ } else {
72
+ fmt.Fprintf(w, `<tr><td class="histoTime" align="right">%s</td>`, h.BucketMin(i))
73
+ }
74
+ // Bucket bar.
75
+ width := h.Buckets[i] * barWidth / maxCount
76
+ fmt.Fprintf(w, `<td><div style="width:%dpx;background:blue;position:relative">&nbsp;</div></td>`, width)
77
+ // Bucket count.
78
+ fmt.Fprintf(w, `<td align="right"><div style="position:relative">%d</div></td>`, h.Buckets[i])
79
+ fmt.Fprintf(w, "</tr>\n")
80
+
81
+ }
82
+ // Final tick label.
83
+ fmt.Fprintf(w, `<tr><td align="right">%s</td></tr>`, h.BucketMin(h.MaxBucket+1))
84
+ fmt.Fprintf(w, `</table>`)
85
+ return template.HTML(w.String())
86
+ }
platform/dbops/binaries/go/go/src/internal/trace/traceviewer/http.go ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package traceviewer
6
+
7
+ import (
8
+ "embed"
9
+ "fmt"
10
+ "html/template"
11
+ "net/http"
12
+ "strings"
13
+ )
14
+
15
+ func MainHandler(views []View) http.Handler {
16
+ return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
17
+ if err := templMain.Execute(w, views); err != nil {
18
+ http.Error(w, err.Error(), http.StatusInternalServerError)
19
+ return
20
+ }
21
+ })
22
+ }
23
+
24
+ const CommonStyle = `
25
+ /* See https://github.com/golang/pkgsite/blob/master/static/shared/typography/typography.css */
26
+ body {
27
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji';
28
+ font-size: 1rem;
29
+ line-height: normal;
30
+ max-width: 9in;
31
+ margin: 1em;
32
+ }
33
+ h1 { font-size: 1.5rem; }
34
+ h2 { font-size: 1.375rem; }
35
+ h1,h2 {
36
+ font-weight: 600;
37
+ line-height: 1.25em;
38
+ word-break: break-word;
39
+ }
40
+ p { color: grey85; font-size:85%; }
41
+ code,
42
+ pre,
43
+ textarea.code {
44
+ font-family: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;
45
+ font-size: 0.875rem;
46
+ line-height: 1.5em;
47
+ }
48
+
49
+ pre,
50
+ textarea.code {
51
+ background-color: var(--color-background-accented);
52
+ border: var(--border);
53
+ border-radius: var(--border-radius);
54
+ color: var(--color-text);
55
+ overflow-x: auto;
56
+ padding: 0.625rem;
57
+ tab-size: 4;
58
+ white-space: pre;
59
+ }
60
+ `
61
+
62
+ var templMain = template.Must(template.New("").Parse(`
63
+ <html>
64
+ <style>` + CommonStyle + `</style>
65
+ <body>
66
+ <h1>cmd/trace: the Go trace event viewer</h1>
67
+ <p>
68
+ This web server provides various visualizations of an event log gathered during
69
+ the execution of a Go program that uses the <a href='https://pkg.go.dev/runtime/trace'>runtime/trace</a> package.
70
+ </p>
71
+
72
+ <h2>Event timelines for running goroutines</h2>
73
+ {{range $i, $view := $}}
74
+ {{if $view.Ranges}}
75
+ {{if eq $i 0}}
76
+ <p>
77
+ Large traces are split into multiple sections of equal data size
78
+ (not duration) to avoid overwhelming the visualizer.
79
+ </p>
80
+ {{end}}
81
+ <ul>
82
+ {{range $index, $e := $view.Ranges}}
83
+ <li><a href="{{$view.URL $index}}">View trace by {{$view.Type}} ({{$e.Name}})</a></li>
84
+ {{end}}
85
+ </ul>
86
+ {{else}}
87
+ <ul>
88
+ <li><a href="{{$view.URL -1}}">View trace by {{$view.Type}}</a></li>
89
+ </ul>
90
+ {{end}}
91
+ {{end}}
92
+ <p>
93
+ This view displays a series of timelines for a type of resource.
94
+ The "by proc" view consists of a timeline for each of the GOMAXPROCS
95
+ logical processors, showing which goroutine (if any) was running on that
96
+ logical processor at each moment.
97
+ The "by thread" view (if available) consists of a similar timeline for each
98
+ OS thread.
99
+
100
+ Each goroutine has an identifying number (e.g. G123), main function,
101
+ and color.
102
+
103
+ A colored bar represents an uninterrupted span of execution.
104
+
105
+ Execution of a goroutine may migrate from one logical processor to another,
106
+ causing a single colored bar to be horizontally continuous but
107
+ vertically displaced.
108
+ </p>
109
+ <p>
110
+ Clicking on a span reveals information about it, such as its
111
+ duration, its causal predecessors and successors, and the stack trace
112
+ at the final moment when it yielded the logical processor, for example
113
+ because it made a system call or tried to acquire a mutex.
114
+
115
+ Directly underneath each bar, a smaller bar or more commonly a fine
116
+ vertical line indicates an event occurring during its execution.
117
+ Some of these are related to garbage collection; most indicate that
118
+ a goroutine yielded its logical processor but then immediately resumed execution
119
+ on the same logical processor. Clicking on the event displays the stack trace
120
+ at the moment it occurred.
121
+ </p>
122
+ <p>
123
+ The causal relationships between spans of goroutine execution
124
+ can be displayed by clicking the Flow Events button at the top.
125
+ </p>
126
+ <p>
127
+ At the top ("STATS"), there are three additional timelines that
128
+ display statistical information.
129
+
130
+ "Goroutines" is a time series of the count of existing goroutines;
131
+ clicking on it displays their breakdown by state at that moment:
132
+ running, runnable, or waiting.
133
+
134
+ "Heap" is a time series of the amount of heap memory allocated (in orange)
135
+ and (in green) the allocation limit at which the next GC cycle will begin.
136
+
137
+ "Threads" shows the number of kernel threads in existence: there is
138
+ always one kernel thread per logical processor, and additional threads
139
+ are created for calls to non-Go code such as a system call or a
140
+ function written in C.
141
+ </p>
142
+ <p>
143
+ Above the event trace for the first logical processor are
144
+ traces for various runtime-internal events.
145
+
146
+ The "GC" bar shows when the garbage collector is running, and in which stage.
147
+ Garbage collection may temporarily affect all the logical processors
148
+ and the other metrics.
149
+
150
+ The "Network", "Timers", and "Syscalls" traces indicate events in
151
+ the runtime that cause goroutines to wake up.
152
+ </p>
153
+ <p>
154
+ The visualization allows you to navigate events at scales ranging from several
155
+ seconds to a handful of nanoseconds.
156
+
157
+ Consult the documentation for the Chromium <a href='https://www.chromium.org/developers/how-tos/trace-event-profiling-tool/'>Trace Event Profiling Tool<a/>
158
+ for help navigating the view.
159
+ </p>
160
+
161
+ <ul>
162
+ <li><a href="/goroutines">Goroutine analysis</a></li>
163
+ </ul>
164
+ <p>
165
+ This view displays information about each set of goroutines that
166
+ shares the same main function.
167
+
168
+ Clicking on a main function shows links to the four types of
169
+ blocking profile (see below) applied to that subset of goroutines.
170
+
171
+ It also shows a table of specific goroutine instances, with various
172
+ execution statistics and a link to the event timeline for each one.
173
+
174
+ The timeline displays only the selected goroutine and any others it
175
+ interacts with via block/unblock events. (The timeline is
176
+ goroutine-oriented rather than logical processor-oriented.)
177
+ </p>
178
+
179
+ <h2>Profiles</h2>
180
+ <p>
181
+ Each link below displays a global profile in zoomable graph form as
182
+ produced by <a href='https://go.dev/blog/pprof'>pprof</a>'s "web" command.
183
+
184
+ In addition there is a link to download the profile for offline
185
+ analysis with pprof.
186
+
187
+ All four profiles represent causes of delay that prevent a goroutine
188
+ from running on a logical processor: because it was waiting for the network,
189
+ for a synchronization operation on a mutex or channel, for a system call,
190
+ or for a logical processor to become available.
191
+ </p>
192
+ <ul>
193
+ <li><a href="/io">Network blocking profile</a> (<a href="/io?raw=1" download="io.profile">⬇</a>)</li>
194
+ <li><a href="/block">Synchronization blocking profile</a> (<a href="/block?raw=1" download="block.profile">⬇</a>)</li>
195
+ <li><a href="/syscall">Syscall profile</a> (<a href="/syscall?raw=1" download="syscall.profile">⬇</a>)</li>
196
+ <li><a href="/sched">Scheduler latency profile</a> (<a href="/sched?raw=1" download="sched.profile">⬇</a>)</li>
197
+ </ul>
198
+
199
+ <h2>User-defined tasks and regions</h2>
200
+ <p>
201
+ The trace API allows a target program to annotate a <a
202
+ href='https://pkg.go.dev/runtime/trace#Region'>region</a> of code
203
+ within a goroutine, such as a key function, so that its performance
204
+ can be analyzed.
205
+
206
+ <a href='https://pkg.go.dev/runtime/trace#Log'>Log events</a> may be
207
+ associated with a region to record progress and relevant values.
208
+
209
+ The API also allows annotation of higher-level
210
+ <a href='https://pkg.go.dev/runtime/trace#Task'>tasks</a>,
211
+ which may involve work across many goroutines.
212
+ </p>
213
+ <p>
214
+ The links below display, for each region and task, a histogram of its execution times.
215
+
216
+ Each histogram bucket contains a sample trace that records the
217
+ sequence of events such as goroutine creations, log events, and
218
+ subregion start/end times.
219
+
220
+ For each task, you can click through to a logical-processor or
221
+ goroutine-oriented view showing the tasks and regions on the
222
+ timeline.
223
+
224
+ Such information may help uncover which steps in a region are
225
+ unexpectedly slow, or reveal relationships between the data values
226
+ logged in a request and its running time.
227
+ </p>
228
+ <ul>
229
+ <li><a href="/usertasks">User-defined tasks</a></li>
230
+ <li><a href="/userregions">User-defined regions</a></li>
231
+ </ul>
232
+
233
+ <h2>Garbage collection metrics</h2>
234
+ <ul>
235
+ <li><a href="/mmu">Minimum mutator utilization</a></li>
236
+ </ul>
237
+ <p>
238
+ This chart indicates the maximum GC pause time (the largest x value
239
+ for which y is zero), and more generally, the fraction of time that
240
+ the processors are available to application goroutines ("mutators"),
241
+ for any time window of a specified size, in the worst case.
242
+ </p>
243
+ </body>
244
+ </html>
245
+ `))
246
+
247
+ type View struct {
248
+ Type ViewType
249
+ Ranges []Range
250
+ }
251
+
252
+ type ViewType string
253
+
254
+ const (
255
+ ViewProc ViewType = "proc"
256
+ ViewThread ViewType = "thread"
257
+ )
258
+
259
+ func (v View) URL(rangeIdx int) string {
260
+ if rangeIdx < 0 {
261
+ return fmt.Sprintf("/trace?view=%s", v.Type)
262
+ }
263
+ return v.Ranges[rangeIdx].URL(v.Type)
264
+ }
265
+
266
+ type Range struct {
267
+ Name string
268
+ Start int
269
+ End int
270
+ StartTime int64
271
+ EndTime int64
272
+ }
273
+
274
+ func (r Range) URL(viewType ViewType) string {
275
+ return fmt.Sprintf("/trace?view=%s&start=%d&end=%d", viewType, r.Start, r.End)
276
+ }
277
+
278
+ func TraceHandler() http.Handler {
279
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
280
+ if err := r.ParseForm(); err != nil {
281
+ http.Error(w, err.Error(), http.StatusInternalServerError)
282
+ return
283
+ }
284
+ html := strings.ReplaceAll(templTrace, "{{PARAMS}}", r.Form.Encode())
285
+ w.Write([]byte(html))
286
+ })
287
+ }
288
+
289
+ // https://chromium.googlesource.com/catapult/+/9508452e18f130c98499cb4c4f1e1efaedee8962/tracing/docs/embedding-trace-viewer.md
290
+ // This is almost verbatim copy of https://chromium-review.googlesource.com/c/catapult/+/2062938/2/tracing/bin/index.html
291
+ var templTrace = `
292
+ <html>
293
+ <head>
294
+ <script src="/static/webcomponents.min.js"></script>
295
+ <script>
296
+ 'use strict';
297
+
298
+ function onTraceViewerImportFail() {
299
+ document.addEventListener('DOMContentLoaded', function() {
300
+ document.body.textContent =
301
+ '/static/trace_viewer_full.html is missing. File a bug in https://golang.org/issue';
302
+ });
303
+ }
304
+ </script>
305
+
306
+ <link rel="import" href="/static/trace_viewer_full.html"
307
+ onerror="onTraceViewerImportFail(event)">
308
+
309
+ <style type="text/css">
310
+ html, body {
311
+ box-sizing: border-box;
312
+ overflow: hidden;
313
+ margin: 0px;
314
+ padding: 0;
315
+ width: 100%;
316
+ height: 100%;
317
+ }
318
+ #trace-viewer {
319
+ width: 100%;
320
+ height: 100%;
321
+ }
322
+ #trace-viewer:focus {
323
+ outline: none;
324
+ }
325
+ </style>
326
+ <script>
327
+ 'use strict';
328
+ (function() {
329
+ var viewer;
330
+ var url;
331
+ var model;
332
+
333
+ function load() {
334
+ var req = new XMLHttpRequest();
335
+ var isBinary = /[.]gz$/.test(url) || /[.]zip$/.test(url);
336
+ req.overrideMimeType('text/plain; charset=x-user-defined');
337
+ req.open('GET', url, true);
338
+ if (isBinary)
339
+ req.responseType = 'arraybuffer';
340
+
341
+ req.onreadystatechange = function(event) {
342
+ if (req.readyState !== 4)
343
+ return;
344
+
345
+ window.setTimeout(function() {
346
+ if (req.status === 200)
347
+ onResult(isBinary ? req.response : req.responseText);
348
+ else
349
+ onResultFail(req.status);
350
+ }, 0);
351
+ };
352
+ req.send(null);
353
+ }
354
+
355
+ function onResultFail(err) {
356
+ var overlay = new tr.ui.b.Overlay();
357
+ overlay.textContent = err + ': ' + url + ' could not be loaded';
358
+ overlay.title = 'Failed to fetch data';
359
+ overlay.visible = true;
360
+ }
361
+
362
+ function onResult(result) {
363
+ model = new tr.Model();
364
+ var opts = new tr.importer.ImportOptions();
365
+ opts.shiftWorldToZero = false;
366
+ var i = new tr.importer.Import(model, opts);
367
+ var p = i.importTracesWithProgressDialog([result]);
368
+ p.then(onModelLoaded, onImportFail);
369
+ }
370
+
371
+ function onModelLoaded() {
372
+ viewer.model = model;
373
+ viewer.viewTitle = "trace";
374
+
375
+ if (!model || model.bounds.isEmpty)
376
+ return;
377
+ var sel = window.location.hash.substr(1);
378
+ if (sel === '')
379
+ return;
380
+ var parts = sel.split(':');
381
+ var range = new (tr.b.Range || tr.b.math.Range)();
382
+ range.addValue(parseFloat(parts[0]));
383
+ range.addValue(parseFloat(parts[1]));
384
+ viewer.trackView.viewport.interestRange.set(range);
385
+ }
386
+
387
+ function onImportFail(err) {
388
+ var overlay = new tr.ui.b.Overlay();
389
+ overlay.textContent = tr.b.normalizeException(err).message;
390
+ overlay.title = 'Import error';
391
+ overlay.visible = true;
392
+ }
393
+
394
+ document.addEventListener('WebComponentsReady', function() {
395
+ var container = document.createElement('track-view-container');
396
+ container.id = 'track_view_container';
397
+
398
+ viewer = document.createElement('tr-ui-timeline-view');
399
+ viewer.track_view_container = container;
400
+ Polymer.dom(viewer).appendChild(container);
401
+
402
+ viewer.id = 'trace-viewer';
403
+ viewer.globalMode = true;
404
+ Polymer.dom(document.body).appendChild(viewer);
405
+
406
+ url = '/jsontrace?{{PARAMS}}';
407
+ load();
408
+ });
409
+ }());
410
+ </script>
411
+ </head>
412
+ <body>
413
+ </body>
414
+ </html>
415
+ `
416
+
417
+ //go:embed static/trace_viewer_full.html static/webcomponents.min.js
418
+ var staticContent embed.FS
419
+
420
+ func StaticHandler() http.Handler {
421
+ return http.FileServer(http.FS(staticContent))
422
+ }
platform/dbops/binaries/go/go/src/internal/trace/traceviewer/mmu.go ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Minimum mutator utilization (MMU) graphing.
6
+
7
+ // TODO:
8
+ //
9
+ // In worst window list, show break-down of GC utilization sources
10
+ // (STW, assist, etc). Probably requires a different MutatorUtil
11
+ // representation.
12
+ //
13
+ // When a window size is selected, show a second plot of the mutator
14
+ // utilization distribution for that window size.
15
+ //
16
+ // Render plot progressively so rough outline is visible quickly even
17
+ // for very complex MUTs. Start by computing just a few window sizes
18
+ // and then add more window sizes.
19
+ //
20
+ // Consider using sampling to compute an approximate MUT. This would
21
+ // work by sampling the mutator utilization at randomly selected
22
+ // points in time in the trace to build an empirical distribution. We
23
+ // could potentially put confidence intervals on these estimates and
24
+ // render this progressively as we refine the distributions.
25
+
26
+ package traceviewer
27
+
28
+ import (
29
+ "encoding/json"
30
+ "fmt"
31
+ "internal/trace"
32
+ "log"
33
+ "math"
34
+ "net/http"
35
+ "strconv"
36
+ "strings"
37
+ "sync"
38
+ "time"
39
+ )
40
+
41
+ type MutatorUtilFunc func(trace.UtilFlags) ([][]trace.MutatorUtil, error)
42
+
43
+ func MMUHandlerFunc(ranges []Range, f MutatorUtilFunc) http.HandlerFunc {
44
+ mmu := &mmu{
45
+ cache: make(map[trace.UtilFlags]*mmuCacheEntry),
46
+ f: f,
47
+ ranges: ranges,
48
+ }
49
+ return func(w http.ResponseWriter, r *http.Request) {
50
+ switch r.FormValue("mode") {
51
+ case "plot":
52
+ mmu.HandlePlot(w, r)
53
+ return
54
+ case "details":
55
+ mmu.HandleDetails(w, r)
56
+ return
57
+ }
58
+ http.ServeContent(w, r, "", time.Time{}, strings.NewReader(templMMU))
59
+ }
60
+ }
61
+
62
+ var utilFlagNames = map[string]trace.UtilFlags{
63
+ "perProc": trace.UtilPerProc,
64
+ "stw": trace.UtilSTW,
65
+ "background": trace.UtilBackground,
66
+ "assist": trace.UtilAssist,
67
+ "sweep": trace.UtilSweep,
68
+ }
69
+
70
+ func requestUtilFlags(r *http.Request) trace.UtilFlags {
71
+ var flags trace.UtilFlags
72
+ for _, flagStr := range strings.Split(r.FormValue("flags"), "|") {
73
+ flags |= utilFlagNames[flagStr]
74
+ }
75
+ return flags
76
+ }
77
+
78
+ type mmuCacheEntry struct {
79
+ init sync.Once
80
+ util [][]trace.MutatorUtil
81
+ mmuCurve *trace.MMUCurve
82
+ err error
83
+ }
84
+
85
+ type mmu struct {
86
+ mu sync.Mutex
87
+ cache map[trace.UtilFlags]*mmuCacheEntry
88
+ f MutatorUtilFunc
89
+ ranges []Range
90
+ }
91
+
92
+ func (m *mmu) get(flags trace.UtilFlags) ([][]trace.MutatorUtil, *trace.MMUCurve, error) {
93
+ m.mu.Lock()
94
+ entry := m.cache[flags]
95
+ if entry == nil {
96
+ entry = new(mmuCacheEntry)
97
+ m.cache[flags] = entry
98
+ }
99
+ m.mu.Unlock()
100
+
101
+ entry.init.Do(func() {
102
+ util, err := m.f(flags)
103
+ if err != nil {
104
+ entry.err = err
105
+ } else {
106
+ entry.util = util
107
+ entry.mmuCurve = trace.NewMMUCurve(util)
108
+ }
109
+ })
110
+ return entry.util, entry.mmuCurve, entry.err
111
+ }
112
+
113
+ // HandlePlot serves the JSON data for the MMU plot.
114
+ func (m *mmu) HandlePlot(w http.ResponseWriter, r *http.Request) {
115
+ mu, mmuCurve, err := m.get(requestUtilFlags(r))
116
+ if err != nil {
117
+ http.Error(w, fmt.Sprintf("failed to produce MMU data: %v", err), http.StatusInternalServerError)
118
+ return
119
+ }
120
+
121
+ var quantiles []float64
122
+ for _, flagStr := range strings.Split(r.FormValue("flags"), "|") {
123
+ if flagStr == "mut" {
124
+ quantiles = []float64{0, 1 - .999, 1 - .99, 1 - .95}
125
+ break
126
+ }
127
+ }
128
+
129
+ // Find a nice starting point for the plot.
130
+ xMin := time.Second
131
+ for xMin > 1 {
132
+ if mmu := mmuCurve.MMU(xMin); mmu < 0.0001 {
133
+ break
134
+ }
135
+ xMin /= 1000
136
+ }
137
+ // Cover six orders of magnitude.
138
+ xMax := xMin * 1e6
139
+ // But no more than the length of the trace.
140
+ minEvent, maxEvent := mu[0][0].Time, mu[0][len(mu[0])-1].Time
141
+ for _, mu1 := range mu[1:] {
142
+ if mu1[0].Time < minEvent {
143
+ minEvent = mu1[0].Time
144
+ }
145
+ if mu1[len(mu1)-1].Time > maxEvent {
146
+ maxEvent = mu1[len(mu1)-1].Time
147
+ }
148
+ }
149
+ if maxMax := time.Duration(maxEvent - minEvent); xMax > maxMax {
150
+ xMax = maxMax
151
+ }
152
+ // Compute MMU curve.
153
+ logMin, logMax := math.Log(float64(xMin)), math.Log(float64(xMax))
154
+ const samples = 100
155
+ plot := make([][]float64, samples)
156
+ for i := 0; i < samples; i++ {
157
+ window := time.Duration(math.Exp(float64(i)/(samples-1)*(logMax-logMin) + logMin))
158
+ if quantiles == nil {
159
+ plot[i] = make([]float64, 2)
160
+ plot[i][1] = mmuCurve.MMU(window)
161
+ } else {
162
+ plot[i] = make([]float64, 1+len(quantiles))
163
+ copy(plot[i][1:], mmuCurve.MUD(window, quantiles))
164
+ }
165
+ plot[i][0] = float64(window)
166
+ }
167
+
168
+ // Create JSON response.
169
+ err = json.NewEncoder(w).Encode(map[string]any{"xMin": int64(xMin), "xMax": int64(xMax), "quantiles": quantiles, "curve": plot})
170
+ if err != nil {
171
+ log.Printf("failed to serialize response: %v", err)
172
+ return
173
+ }
174
+ }
175
+
176
+ var templMMU = `<!doctype html>
177
+ <html>
178
+ <head>
179
+ <meta charset="utf-8">
180
+ <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
181
+ <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
182
+ <script type="text/javascript">
183
+ google.charts.load('current', {'packages':['corechart']});
184
+ var chartsReady = false;
185
+ google.charts.setOnLoadCallback(function() { chartsReady = true; refreshChart(); });
186
+
187
+ var chart;
188
+ var curve;
189
+
190
+ function niceDuration(ns) {
191
+ if (ns < 1e3) { return ns + 'ns'; }
192
+ else if (ns < 1e6) { return ns / 1e3 + 'µs'; }
193
+ else if (ns < 1e9) { return ns / 1e6 + 'ms'; }
194
+ else { return ns / 1e9 + 's'; }
195
+ }
196
+
197
+ function niceQuantile(q) {
198
+ return 'p' + q*100;
199
+ }
200
+
201
+ function mmuFlags() {
202
+ var flags = "";
203
+ $("#options input").each(function(i, elt) {
204
+ if (elt.checked)
205
+ flags += "|" + elt.id;
206
+ });
207
+ return flags.substr(1);
208
+ }
209
+
210
+ function refreshChart() {
211
+ if (!chartsReady) return;
212
+ var container = $('#mmu_chart');
213
+ container.css('opacity', '.5');
214
+ refreshChart.count++;
215
+ var seq = refreshChart.count;
216
+ $.getJSON('?mode=plot&flags=' + mmuFlags())
217
+ .fail(function(xhr, status, error) {
218
+ alert('failed to load plot: ' + status);
219
+ })
220
+ .done(function(result) {
221
+ if (refreshChart.count === seq)
222
+ drawChart(result);
223
+ });
224
+ }
225
+ refreshChart.count = 0;
226
+
227
+ function drawChart(plotData) {
228
+ curve = plotData.curve;
229
+ var data = new google.visualization.DataTable();
230
+ data.addColumn('number', 'Window duration');
231
+ data.addColumn('number', 'Minimum mutator utilization');
232
+ if (plotData.quantiles) {
233
+ for (var i = 1; i < plotData.quantiles.length; i++) {
234
+ data.addColumn('number', niceQuantile(1 - plotData.quantiles[i]) + ' MU');
235
+ }
236
+ }
237
+ data.addRows(curve);
238
+ for (var i = 0; i < curve.length; i++) {
239
+ data.setFormattedValue(i, 0, niceDuration(curve[i][0]));
240
+ }
241
+
242
+ var options = {
243
+ chart: {
244
+ title: 'Minimum mutator utilization',
245
+ },
246
+ hAxis: {
247
+ title: 'Window duration',
248
+ scaleType: 'log',
249
+ ticks: [],
250
+ },
251
+ vAxis: {
252
+ title: 'Minimum mutator utilization',
253
+ minValue: 0.0,
254
+ maxValue: 1.0,
255
+ },
256
+ legend: { position: 'none' },
257
+ focusTarget: 'category',
258
+ width: 900,
259
+ height: 500,
260
+ chartArea: { width: '80%', height: '80%' },
261
+ };
262
+ for (var v = plotData.xMin; v <= plotData.xMax; v *= 10) {
263
+ options.hAxis.ticks.push({v:v, f:niceDuration(v)});
264
+ }
265
+ if (plotData.quantiles) {
266
+ options.vAxis.title = 'Mutator utilization';
267
+ options.legend.position = 'in';
268
+ }
269
+
270
+ var container = $('#mmu_chart');
271
+ container.empty();
272
+ container.css('opacity', '');
273
+ chart = new google.visualization.LineChart(container[0]);
274
+ chart = new google.visualization.LineChart(document.getElementById('mmu_chart'));
275
+ chart.draw(data, options);
276
+
277
+ google.visualization.events.addListener(chart, 'select', selectHandler);
278
+ $('#details').empty();
279
+ }
280
+
281
+ function selectHandler() {
282
+ var items = chart.getSelection();
283
+ if (items.length === 0) {
284
+ return;
285
+ }
286
+ var details = $('#details');
287
+ details.empty();
288
+ var windowNS = curve[items[0].row][0];
289
+ var url = '?mode=details&window=' + windowNS + '&flags=' + mmuFlags();
290
+ $.getJSON(url)
291
+ .fail(function(xhr, status, error) {
292
+ details.text(status + ': ' + url + ' could not be loaded');
293
+ })
294
+ .done(function(worst) {
295
+ details.text('Lowest mutator utilization in ' + niceDuration(windowNS) + ' windows:');
296
+ for (var i = 0; i < worst.length; i++) {
297
+ details.append($('<br>'));
298
+ var text = worst[i].MutatorUtil.toFixed(3) + ' at time ' + niceDuration(worst[i].Time);
299
+ details.append($('<a/>').text(text).attr('href', worst[i].URL));
300
+ }
301
+ });
302
+ }
303
+
304
+ $.when($.ready).then(function() {
305
+ $("#options input").click(refreshChart);
306
+ });
307
+ </script>
308
+ <style>
309
+ .help {
310
+ display: inline-block;
311
+ position: relative;
312
+ width: 1em;
313
+ height: 1em;
314
+ border-radius: 50%;
315
+ color: #fff;
316
+ background: #555;
317
+ text-align: center;
318
+ cursor: help;
319
+ }
320
+ .help > span {
321
+ display: none;
322
+ }
323
+ .help:hover > span {
324
+ display: block;
325
+ position: absolute;
326
+ left: 1.1em;
327
+ top: 1.1em;
328
+ background: #555;
329
+ text-align: left;
330
+ width: 20em;
331
+ padding: 0.5em;
332
+ border-radius: 0.5em;
333
+ z-index: 5;
334
+ }
335
+ </style>
336
+ </head>
337
+ <body>
338
+ <div style="position: relative">
339
+ <div id="mmu_chart" style="width: 900px; height: 500px; display: inline-block; vertical-align: top">Loading plot...</div>
340
+ <div id="options" style="display: inline-block; vertical-align: top">
341
+ <p>
342
+ <b>View</b><br>
343
+ <input type="radio" name="view" id="system" checked><label for="system">System</label>
344
+ <span class="help">?<span>Consider whole system utilization. For example, if one of four procs is available to the mutator, mutator utilization will be 0.25. This is the standard definition of an MMU.</span></span><br>
345
+ <input type="radio" name="view" id="perProc"><label for="perProc">Per-goroutine</label>
346
+ <span class="help">?<span>Consider per-goroutine utilization. When even one goroutine is interrupted by GC, mutator utilization is 0.</span></span><br>
347
+ </p>
348
+ <p>
349
+ <b>Include</b><br>
350
+ <input type="checkbox" id="stw" checked><label for="stw">STW</label>
351
+ <span class="help">?<span>Stop-the-world stops all goroutines simultaneously.</span></span><br>
352
+ <input type="checkbox" id="background" checked><label for="background">Background workers</label>
353
+ <span class="help">?<span>Background workers are GC-specific goroutines. 25% of the CPU is dedicated to background workers during GC.</span></span><br>
354
+ <input type="checkbox" id="assist" checked><label for="assist">Mark assist</label>
355
+ <span class="help">?<span>Mark assists are performed by allocation to prevent the mutator from outpacing GC.</span></span><br>
356
+ <input type="checkbox" id="sweep"><label for="sweep">Sweep</label>
357
+ <span class="help">?<span>Sweep reclaims unused memory between GCs. (Enabling this may be very slow.).</span></span><br>
358
+ </p>
359
+ <p>
360
+ <b>Display</b><br>
361
+ <input type="checkbox" id="mut"><label for="mut">Show percentiles</label>
362
+ <span class="help">?<span>Display percentile mutator utilization in addition to minimum. E.g., p99 MU drops the worst 1% of windows.</span></span><br>
363
+ </p>
364
+ </div>
365
+ </div>
366
+ <div id="details">Select a point for details.</div>
367
+ </body>
368
+ </html>
369
+ `
370
+
371
+ // HandleDetails serves details of an MMU graph at a particular window.
372
+ func (m *mmu) HandleDetails(w http.ResponseWriter, r *http.Request) {
373
+ _, mmuCurve, err := m.get(requestUtilFlags(r))
374
+ if err != nil {
375
+ http.Error(w, fmt.Sprintf("failed to produce MMU data: %v", err), http.StatusInternalServerError)
376
+ return
377
+ }
378
+
379
+ windowStr := r.FormValue("window")
380
+ window, err := strconv.ParseUint(windowStr, 10, 64)
381
+ if err != nil {
382
+ http.Error(w, fmt.Sprintf("failed to parse window parameter %q: %v", windowStr, err), http.StatusBadRequest)
383
+ return
384
+ }
385
+ worst := mmuCurve.Examples(time.Duration(window), 10)
386
+
387
+ // Construct a link for each window.
388
+ var links []linkedUtilWindow
389
+ for _, ui := range worst {
390
+ links = append(links, m.newLinkedUtilWindow(ui, time.Duration(window)))
391
+ }
392
+
393
+ err = json.NewEncoder(w).Encode(links)
394
+ if err != nil {
395
+ log.Printf("failed to serialize trace: %v", err)
396
+ return
397
+ }
398
+ }
399
+
400
+ type linkedUtilWindow struct {
401
+ trace.UtilWindow
402
+ URL string
403
+ }
404
+
405
+ func (m *mmu) newLinkedUtilWindow(ui trace.UtilWindow, window time.Duration) linkedUtilWindow {
406
+ // Find the range containing this window.
407
+ var r Range
408
+ for _, r = range m.ranges {
409
+ if r.EndTime > ui.Time {
410
+ break
411
+ }
412
+ }
413
+ return linkedUtilWindow{ui, fmt.Sprintf("%s#%v:%v", r.URL(ViewProc), float64(ui.Time)/1e6, float64(ui.Time+int64(window))/1e6)}
414
+ }
platform/dbops/binaries/go/go/src/internal/trace/traceviewer/pprof.go ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // Serving of pprof-like profiles.
6
+
7
+ package traceviewer
8
+
9
+ import (
10
+ "bufio"
11
+ "fmt"
12
+ "internal/profile"
13
+ "internal/trace"
14
+ "net/http"
15
+ "os"
16
+ "os/exec"
17
+ "path/filepath"
18
+ "runtime"
19
+ "time"
20
+ )
21
+
22
+ type ProfileFunc func(r *http.Request) ([]ProfileRecord, error)
23
+
24
+ // SVGProfileHandlerFunc serves pprof-like profile generated by prof as svg.
25
+ func SVGProfileHandlerFunc(f ProfileFunc) http.HandlerFunc {
26
+ return func(w http.ResponseWriter, r *http.Request) {
27
+ if r.FormValue("raw") != "" {
28
+ w.Header().Set("Content-Type", "application/octet-stream")
29
+
30
+ failf := func(s string, args ...any) {
31
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
32
+ w.Header().Set("X-Go-Pprof", "1")
33
+ http.Error(w, fmt.Sprintf(s, args...), http.StatusInternalServerError)
34
+ }
35
+ records, err := f(r)
36
+ if err != nil {
37
+ failf("failed to get records: %v", err)
38
+ return
39
+ }
40
+ if err := BuildProfile(records).Write(w); err != nil {
41
+ failf("failed to write profile: %v", err)
42
+ return
43
+ }
44
+ return
45
+ }
46
+
47
+ blockf, err := os.CreateTemp("", "block")
48
+ if err != nil {
49
+ http.Error(w, fmt.Sprintf("failed to create temp file: %v", err), http.StatusInternalServerError)
50
+ return
51
+ }
52
+ defer func() {
53
+ blockf.Close()
54
+ os.Remove(blockf.Name())
55
+ }()
56
+ records, err := f(r)
57
+ if err != nil {
58
+ http.Error(w, fmt.Sprintf("failed to generate profile: %v", err), http.StatusInternalServerError)
59
+ }
60
+ blockb := bufio.NewWriter(blockf)
61
+ if err := BuildProfile(records).Write(blockb); err != nil {
62
+ http.Error(w, fmt.Sprintf("failed to write profile: %v", err), http.StatusInternalServerError)
63
+ return
64
+ }
65
+ if err := blockb.Flush(); err != nil {
66
+ http.Error(w, fmt.Sprintf("failed to flush temp file: %v", err), http.StatusInternalServerError)
67
+ return
68
+ }
69
+ if err := blockf.Close(); err != nil {
70
+ http.Error(w, fmt.Sprintf("failed to close temp file: %v", err), http.StatusInternalServerError)
71
+ return
72
+ }
73
+ svgFilename := blockf.Name() + ".svg"
74
+ if output, err := exec.Command(goCmd(), "tool", "pprof", "-svg", "-output", svgFilename, blockf.Name()).CombinedOutput(); err != nil {
75
+ http.Error(w, fmt.Sprintf("failed to execute go tool pprof: %v\n%s", err, output), http.StatusInternalServerError)
76
+ return
77
+ }
78
+ defer os.Remove(svgFilename)
79
+ w.Header().Set("Content-Type", "image/svg+xml")
80
+ http.ServeFile(w, r, svgFilename)
81
+ }
82
+ }
83
+
84
+ type ProfileRecord struct {
85
+ Stack []*trace.Frame
86
+ Count uint64
87
+ Time time.Duration
88
+ }
89
+
90
+ func BuildProfile(prof []ProfileRecord) *profile.Profile {
91
+ p := &profile.Profile{
92
+ PeriodType: &profile.ValueType{Type: "trace", Unit: "count"},
93
+ Period: 1,
94
+ SampleType: []*profile.ValueType{
95
+ {Type: "contentions", Unit: "count"},
96
+ {Type: "delay", Unit: "nanoseconds"},
97
+ },
98
+ }
99
+ locs := make(map[uint64]*profile.Location)
100
+ funcs := make(map[string]*profile.Function)
101
+ for _, rec := range prof {
102
+ var sloc []*profile.Location
103
+ for _, frame := range rec.Stack {
104
+ loc := locs[frame.PC]
105
+ if loc == nil {
106
+ fn := funcs[frame.File+frame.Fn]
107
+ if fn == nil {
108
+ fn = &profile.Function{
109
+ ID: uint64(len(p.Function) + 1),
110
+ Name: frame.Fn,
111
+ SystemName: frame.Fn,
112
+ Filename: frame.File,
113
+ }
114
+ p.Function = append(p.Function, fn)
115
+ funcs[frame.File+frame.Fn] = fn
116
+ }
117
+ loc = &profile.Location{
118
+ ID: uint64(len(p.Location) + 1),
119
+ Address: frame.PC,
120
+ Line: []profile.Line{
121
+ {
122
+ Function: fn,
123
+ Line: int64(frame.Line),
124
+ },
125
+ },
126
+ }
127
+ p.Location = append(p.Location, loc)
128
+ locs[frame.PC] = loc
129
+ }
130
+ sloc = append(sloc, loc)
131
+ }
132
+ p.Sample = append(p.Sample, &profile.Sample{
133
+ Value: []int64{int64(rec.Count), int64(rec.Time)},
134
+ Location: sloc,
135
+ })
136
+ }
137
+ return p
138
+ }
139
+
140
+ func goCmd() string {
141
+ var exeSuffix string
142
+ if runtime.GOOS == "windows" {
143
+ exeSuffix = ".exe"
144
+ }
145
+ path := filepath.Join(runtime.GOROOT(), "bin", "go"+exeSuffix)
146
+ if _, err := os.Stat(path); err == nil {
147
+ return path
148
+ }
149
+ return "go"
150
+ }
platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/README.md ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Resources for Go's trace viewer
2
+
3
+ Go execution trace UI (`go tool trace`) embeds
4
+ Chrome's trace viewer (Catapult) following the
5
+ [instructions](
6
+ https://chromium.googlesource.com/catapult/+/refs/heads/master/tracing/docs/embedding-trace-viewer.md). This directory contains
7
+ the helper files to embed Chrome's trace viewer.
8
+
9
+ The current resources were generated/copied from
10
+ [`Catapult@9508452e18f130c98499cb4c4f1e1efaedee8962`](
11
+ https://chromium.googlesource.com/catapult/+/9508452e18f130c98499cb4c4f1e1efaedee8962).
12
+
13
+ ### Updating `trace_viewer_full.html`
14
+
15
+ The file was generated by catapult's `vulcanize_trace_viewer` command.
16
+
17
+ ```
18
+ $ git clone https://chromium.googlesource.com/catapult
19
+ $ cd catapult
20
+ $ ./tracing/bin/vulcanize_trace_viewer --config=full
21
+ $ cp tracing/bin/trace_viewer_full.html $GOROOT/src/cmd/trace/static/trace_viewer_full.html
22
+ ```
23
+
24
+ We are supposed to use --config=lean (produces smaller html),
25
+ but it is broken at the moment:
26
+ https://github.com/catapult-project/catapult/issues/2247
27
+
28
+ ### Updating `webcomponents.min.js`
29
+
30
+ `webcomponents.min.js` is necessary to let the trace viewer page
31
+ to import the `trace_viewer_full.html`.
32
+ This is copied from the catapult repo.
33
+
34
+ ```
35
+ $ cp third_party/polymer/components/webcomponentsjs/webcomponents.min.js $GOROOT/src/cmd/trace/static/webcomponents.min.js
36
+ ```
37
+
38
+ ## Licenses
39
+
40
+ The license for trace-viewer is as follows:
41
+ // Copyright (c) 2012 The Chromium Authors. All rights reserved.
42
+ //
43
+ // Redistribution and use in source and binary forms, with or without
44
+ // modification, are permitted provided that the following conditions are
45
+ // met:
46
+ //
47
+ // * Redistributions of source code must retain the above copyright
48
+ // notice, this list of conditions and the following disclaimer.
49
+ // * Redistributions in binary form must reproduce the above
50
+ // copyright notice, this list of conditions and the following disclaimer
51
+ // in the documentation and/or other materials provided with the
52
+ // distribution.
53
+ // * Neither the name of Google Inc. nor the names of its
54
+ // contributors may be used to endorse or promote products derived from
55
+ // this software without specific prior written permission.
56
+ //
57
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
58
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
59
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
60
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
61
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
62
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
63
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
64
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
65
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
66
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
67
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
68
+
69
+ The license for webcomponents.min.js is as follows:
70
+
71
+ /**
72
+ * @license
73
+ * Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
74
+ * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
75
+ * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
76
+ * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
77
+ * Code distributed by Google as part of the polymer project is also
78
+ * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
79
+ */
80
+ // Copyright (c) 2014 The Polymer Authors. All rights reserved.
81
+ //
82
+ // Redistribution and use in source and binary forms, with or without
83
+ // modification, are permitted provided that the following conditions are
84
+ // met:
85
+ //
86
+ // * Redistributions of source code must retain the above copyright
87
+ // notice, this list of conditions and the following disclaimer.
88
+ // * Redistributions in binary form must reproduce the above
89
+ // copyright notice, this list of conditions and the following disclaimer
90
+ // in the documentation and/or other materials provided with the
91
+ // distribution.
92
+ // * Neither the name of Google Inc. nor the names of its
93
+ // contributors may be used to endorse or promote products derived from
94
+ // this software without specific prior written permission.
95
+ //
96
+ // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
97
+ // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
98
+ // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
99
+ // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
100
+ // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
101
+ // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
102
+ // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
103
+ // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
104
+ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
105
+ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
106
+ // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/trace_viewer_full.html ADDED
The diff for this file is too large to render. See raw diff
 
platform/dbops/binaries/go/go/src/internal/trace/traceviewer/static/webcomponents.min.js ADDED
The diff for this file is too large to render. See raw diff
 
platform/dbops/binaries/go/go/src/internal/trace/v2/base.go ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ // This file contains data types that all implementations of the trace format
6
+ // parser need to provide to the rest of the package.
7
+
8
+ package trace
9
+
10
+ import (
11
+ "fmt"
12
+ "math"
13
+ "strings"
14
+
15
+ "internal/trace/v2/event"
16
+ "internal/trace/v2/event/go122"
17
+ "internal/trace/v2/version"
18
+ )
19
+
20
+ // maxArgs is the maximum number of arguments for "plain" events,
21
+ // i.e. anything that could reasonably be represented as a Base.
22
+ const maxArgs = 5
23
+
24
+ // baseEvent is the basic unprocessed event. This serves as a common
25
+ // fundamental data structure across.
26
+ type baseEvent struct {
27
+ typ event.Type
28
+ time Time
29
+ args [maxArgs - 1]uint64
30
+ }
31
+
32
+ // extra returns a slice representing extra available space in args
33
+ // that the parser can use to pass data up into Event.
34
+ func (e *baseEvent) extra(v version.Version) []uint64 {
35
+ switch v {
36
+ case version.Go122:
37
+ return e.args[len(go122.Specs()[e.typ].Args)-1:]
38
+ }
39
+ panic(fmt.Sprintf("unsupported version: go 1.%d", v))
40
+ }
41
+
42
+ // evTable contains the per-generation data necessary to
43
+ // interpret an individual event.
44
+ type evTable struct {
45
+ freq frequency
46
+ strings dataTable[stringID, string]
47
+ stacks dataTable[stackID, stack]
48
+
49
+ // extraStrings are strings that get generated during
50
+ // parsing but haven't come directly from the trace, so
51
+ // they don't appear in strings.
52
+ extraStrings []string
53
+ extraStringIDs map[string]extraStringID
54
+ nextExtra extraStringID
55
+ }
56
+
57
+ // addExtraString adds an extra string to the evTable and returns
58
+ // a unique ID for the string in the table.
59
+ func (t *evTable) addExtraString(s string) extraStringID {
60
+ if s == "" {
61
+ return 0
62
+ }
63
+ if t.extraStringIDs == nil {
64
+ t.extraStringIDs = make(map[string]extraStringID)
65
+ }
66
+ if id, ok := t.extraStringIDs[s]; ok {
67
+ return id
68
+ }
69
+ t.nextExtra++
70
+ id := t.nextExtra
71
+ t.extraStrings = append(t.extraStrings, s)
72
+ t.extraStringIDs[s] = id
73
+ return id
74
+ }
75
+
76
+ // getExtraString returns the extra string for the provided ID.
77
+ // The ID must have been produced by addExtraString for this evTable.
78
+ func (t *evTable) getExtraString(id extraStringID) string {
79
+ if id == 0 {
80
+ return ""
81
+ }
82
+ return t.extraStrings[id-1]
83
+ }
84
+
85
+ // dataTable is a mapping from EIs to Es.
86
+ type dataTable[EI ~uint64, E any] struct {
87
+ present []uint8
88
+ dense []E
89
+ sparse map[EI]E
90
+ }
91
+
92
+ // insert tries to add a mapping from id to s.
93
+ //
94
+ // Returns an error if a mapping for id already exists, regardless
95
+ // of whether or not s is the same in content. This should be used
96
+ // for validation during parsing.
97
+ func (d *dataTable[EI, E]) insert(id EI, data E) error {
98
+ if d.sparse == nil {
99
+ d.sparse = make(map[EI]E)
100
+ }
101
+ if existing, ok := d.get(id); ok {
102
+ return fmt.Errorf("multiple %Ts with the same ID: id=%d, new=%v, existing=%v", data, id, data, existing)
103
+ }
104
+ d.sparse[id] = data
105
+ return nil
106
+ }
107
+
108
+ // compactify attempts to compact sparse into dense.
109
+ //
110
+ // This is intended to be called only once after insertions are done.
111
+ func (d *dataTable[EI, E]) compactify() {
112
+ if d.sparse == nil || len(d.dense) != 0 {
113
+ // Already compactified.
114
+ return
115
+ }
116
+ // Find the range of IDs.
117
+ maxID := EI(0)
118
+ minID := ^EI(0)
119
+ for id := range d.sparse {
120
+ if id > maxID {
121
+ maxID = id
122
+ }
123
+ if id < minID {
124
+ minID = id
125
+ }
126
+ }
127
+ if maxID >= math.MaxInt {
128
+ // We can't create a slice big enough to hold maxID elements
129
+ return
130
+ }
131
+ // We're willing to waste at most 2x memory.
132
+ if int(maxID-minID) > max(len(d.sparse), 2*len(d.sparse)) {
133
+ return
134
+ }
135
+ if int(minID) > len(d.sparse) {
136
+ return
137
+ }
138
+ size := int(maxID) + 1
139
+ d.present = make([]uint8, (size+7)/8)
140
+ d.dense = make([]E, size)
141
+ for id, data := range d.sparse {
142
+ d.dense[id] = data
143
+ d.present[id/8] |= uint8(1) << (id % 8)
144
+ }
145
+ d.sparse = nil
146
+ }
147
+
148
+ // get returns the E for id or false if it doesn't
149
+ // exist. This should be used for validation during parsing.
150
+ func (d *dataTable[EI, E]) get(id EI) (E, bool) {
151
+ if id == 0 {
152
+ return *new(E), true
153
+ }
154
+ if uint64(id) < uint64(len(d.dense)) {
155
+ if d.present[id/8]&(uint8(1)<<(id%8)) != 0 {
156
+ return d.dense[id], true
157
+ }
158
+ } else if d.sparse != nil {
159
+ if data, ok := d.sparse[id]; ok {
160
+ return data, true
161
+ }
162
+ }
163
+ return *new(E), false
164
+ }
165
+
166
+ // forEach iterates over all ID/value pairs in the data table.
167
+ func (d *dataTable[EI, E]) forEach(yield func(EI, E) bool) bool {
168
+ for id, value := range d.dense {
169
+ if d.present[id/8]&(uint8(1)<<(id%8)) == 0 {
170
+ continue
171
+ }
172
+ if !yield(EI(id), value) {
173
+ return false
174
+ }
175
+ }
176
+ if d.sparse == nil {
177
+ return true
178
+ }
179
+ for id, value := range d.sparse {
180
+ if !yield(id, value) {
181
+ return false
182
+ }
183
+ }
184
+ return true
185
+ }
186
+
187
+ // mustGet returns the E for id or panics if it fails.
188
+ //
189
+ // This should only be used if id has already been validated.
190
+ func (d *dataTable[EI, E]) mustGet(id EI) E {
191
+ data, ok := d.get(id)
192
+ if !ok {
193
+ panic(fmt.Sprintf("expected id %d in %T table", id, data))
194
+ }
195
+ return data
196
+ }
197
+
198
+ // frequency is nanoseconds per timestamp unit.
199
+ type frequency float64
200
+
201
+ // mul multiplies an unprocessed to produce a time in nanoseconds.
202
+ func (f frequency) mul(t timestamp) Time {
203
+ return Time(float64(t) * float64(f))
204
+ }
205
+
206
+ // stringID is an index into the string table for a generation.
207
+ type stringID uint64
208
+
209
+ // extraStringID is an index into the extra string table for a generation.
210
+ type extraStringID uint64
211
+
212
+ // stackID is an index into the stack table for a generation.
213
+ type stackID uint64
214
+
215
+ // cpuSample represents a CPU profiling sample captured by the trace.
216
+ type cpuSample struct {
217
+ schedCtx
218
+ time Time
219
+ stack stackID
220
+ }
221
+
222
+ // asEvent produces a complete Event from a cpuSample. It needs
223
+ // the evTable from the generation that created it.
224
+ //
225
+ // We don't just store it as an Event in generation to minimize
226
+ // the amount of pointer data floating around.
227
+ func (s cpuSample) asEvent(table *evTable) Event {
228
+ // TODO(mknyszek): This is go122-specific, but shouldn't be.
229
+ // Generalize this in the future.
230
+ e := Event{
231
+ table: table,
232
+ ctx: s.schedCtx,
233
+ base: baseEvent{
234
+ typ: go122.EvCPUSample,
235
+ time: s.time,
236
+ },
237
+ }
238
+ e.base.args[0] = uint64(s.stack)
239
+ return e
240
+ }
241
+
242
+ // stack represents a goroutine stack sample.
243
+ type stack struct {
244
+ frames []frame
245
+ }
246
+
247
+ func (s stack) String() string {
248
+ var sb strings.Builder
249
+ for _, frame := range s.frames {
250
+ fmt.Fprintf(&sb, "\t%#v\n", frame)
251
+ }
252
+ return sb.String()
253
+ }
254
+
255
+ // frame represents a single stack frame.
256
+ type frame struct {
257
+ pc uint64
258
+ funcID stringID
259
+ fileID stringID
260
+ line uint64
261
+ }
platform/dbops/binaries/go/go/src/internal/trace/v2/batch.go ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package trace
6
+
7
+ import (
8
+ "bufio"
9
+ "bytes"
10
+ "encoding/binary"
11
+ "fmt"
12
+ "io"
13
+
14
+ "internal/trace/v2/event"
15
+ "internal/trace/v2/event/go122"
16
+ )
17
+
18
+ // timestamp is an unprocessed timestamp.
19
+ type timestamp uint64
20
+
21
+ // batch represents a batch of trace events.
22
+ // It is unparsed except for its header.
23
+ type batch struct {
24
+ m ThreadID
25
+ time timestamp
26
+ data []byte
27
+ }
28
+
29
+ func (b *batch) isStringsBatch() bool {
30
+ return len(b.data) > 0 && event.Type(b.data[0]) == go122.EvStrings
31
+ }
32
+
33
+ func (b *batch) isStacksBatch() bool {
34
+ return len(b.data) > 0 && event.Type(b.data[0]) == go122.EvStacks
35
+ }
36
+
37
+ func (b *batch) isCPUSamplesBatch() bool {
38
+ return len(b.data) > 0 && event.Type(b.data[0]) == go122.EvCPUSamples
39
+ }
40
+
41
+ func (b *batch) isFreqBatch() bool {
42
+ return len(b.data) > 0 && event.Type(b.data[0]) == go122.EvFrequency
43
+ }
44
+
45
+ // readBatch reads the next full batch from r.
46
+ func readBatch(r *bufio.Reader) (batch, uint64, error) {
47
+ // Read batch header byte.
48
+ b, err := r.ReadByte()
49
+ if err != nil {
50
+ return batch{}, 0, err
51
+ }
52
+ if typ := event.Type(b); typ != go122.EvEventBatch {
53
+ return batch{}, 0, fmt.Errorf("expected batch event (%s), got %s", go122.EventString(go122.EvEventBatch), go122.EventString(typ))
54
+ }
55
+
56
+ // Read the batch header: gen (generation), thread (M) ID, base timestamp
57
+ // for the batch.
58
+ gen, err := binary.ReadUvarint(r)
59
+ if err != nil {
60
+ return batch{}, gen, fmt.Errorf("error reading batch gen: %w", err)
61
+ }
62
+ m, err := binary.ReadUvarint(r)
63
+ if err != nil {
64
+ return batch{}, gen, fmt.Errorf("error reading batch M ID: %w", err)
65
+ }
66
+ ts, err := binary.ReadUvarint(r)
67
+ if err != nil {
68
+ return batch{}, gen, fmt.Errorf("error reading batch timestamp: %w", err)
69
+ }
70
+
71
+ // Read in the size of the batch to follow.
72
+ size, err := binary.ReadUvarint(r)
73
+ if err != nil {
74
+ return batch{}, gen, fmt.Errorf("error reading batch size: %w", err)
75
+ }
76
+ if size > go122.MaxBatchSize {
77
+ return batch{}, gen, fmt.Errorf("invalid batch size %d, maximum is %d", size, go122.MaxBatchSize)
78
+ }
79
+
80
+ // Copy out the batch for later processing.
81
+ var data bytes.Buffer
82
+ data.Grow(int(size))
83
+ n, err := io.CopyN(&data, r, int64(size))
84
+ if n != int64(size) {
85
+ return batch{}, gen, fmt.Errorf("failed to read full batch: read %d but wanted %d", n, size)
86
+ }
87
+ if err != nil {
88
+ return batch{}, gen, fmt.Errorf("copying batch data: %w", err)
89
+ }
90
+
91
+ // Return the batch.
92
+ return batch{
93
+ m: ThreadID(m),
94
+ time: timestamp(ts),
95
+ data: data.Bytes(),
96
+ }, gen, nil
97
+ }
platform/dbops/binaries/go/go/src/internal/trace/v2/batchcursor.go ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package trace
6
+
7
+ import (
8
+ "cmp"
9
+ "encoding/binary"
10
+ "fmt"
11
+
12
+ "internal/trace/v2/event"
13
+ "internal/trace/v2/event/go122"
14
+ )
15
+
16
+ type batchCursor struct {
17
+ m ThreadID
18
+ lastTs Time
19
+ idx int // next index into []batch
20
+ dataOff int // next index into batch.data
21
+ ev baseEvent // last read event
22
+ }
23
+
24
+ func (b *batchCursor) nextEvent(batches []batch, freq frequency) (ok bool, err error) {
25
+ // Batches should generally always have at least one event,
26
+ // but let's be defensive about that and accept empty batches.
27
+ for b.idx < len(batches) && len(batches[b.idx].data) == b.dataOff {
28
+ b.idx++
29
+ b.dataOff = 0
30
+ b.lastTs = 0
31
+ }
32
+ // Have we reached the end of the batches?
33
+ if b.idx == len(batches) {
34
+ return false, nil
35
+ }
36
+ // Initialize lastTs if it hasn't been yet.
37
+ if b.lastTs == 0 {
38
+ b.lastTs = freq.mul(batches[b.idx].time)
39
+ }
40
+ // Read an event out.
41
+ n, tsdiff, err := readTimedBaseEvent(batches[b.idx].data[b.dataOff:], &b.ev)
42
+ if err != nil {
43
+ return false, err
44
+ }
45
+ // Complete the timestamp from the cursor's last timestamp.
46
+ b.ev.time = freq.mul(tsdiff) + b.lastTs
47
+
48
+ // Move the cursor's timestamp forward.
49
+ b.lastTs = b.ev.time
50
+
51
+ // Move the cursor forward.
52
+ b.dataOff += n
53
+ return true, nil
54
+ }
55
+
56
+ func (b *batchCursor) compare(a *batchCursor) int {
57
+ return cmp.Compare(b.ev.time, a.ev.time)
58
+ }
59
+
60
+ // readTimedBaseEvent reads out the raw event data from b
61
+ // into e. It does not try to interpret the arguments
62
+ // but it does validate that the event is a regular
63
+ // event with a timestamp (vs. a structural event).
64
+ //
65
+ // It requires that the event its reading be timed, which must
66
+ // be the case for every event in a plain EventBatch.
67
+ func readTimedBaseEvent(b []byte, e *baseEvent) (int, timestamp, error) {
68
+ // Get the event type.
69
+ typ := event.Type(b[0])
70
+ specs := go122.Specs()
71
+ if int(typ) >= len(specs) {
72
+ return 0, 0, fmt.Errorf("found invalid event type: %v", typ)
73
+ }
74
+ e.typ = typ
75
+
76
+ // Get spec.
77
+ spec := &specs[typ]
78
+ if len(spec.Args) == 0 || !spec.IsTimedEvent {
79
+ return 0, 0, fmt.Errorf("found event without a timestamp: type=%v", typ)
80
+ }
81
+ n := 1
82
+
83
+ // Read timestamp diff.
84
+ ts, nb := binary.Uvarint(b[n:])
85
+ if nb <= 0 {
86
+ return 0, 0, fmt.Errorf("found invalid uvarint for timestamp")
87
+ }
88
+ n += nb
89
+
90
+ // Read the rest of the arguments.
91
+ for i := 0; i < len(spec.Args)-1; i++ {
92
+ arg, nb := binary.Uvarint(b[n:])
93
+ if nb <= 0 {
94
+ return 0, 0, fmt.Errorf("found invalid uvarint")
95
+ }
96
+ e.args[i] = arg
97
+ n += nb
98
+ }
99
+ return n, timestamp(ts), nil
100
+ }
101
+
102
+ func heapInsert(heap []*batchCursor, bc *batchCursor) []*batchCursor {
103
+ // Add the cursor to the end of the heap.
104
+ heap = append(heap, bc)
105
+
106
+ // Sift the new entry up to the right place.
107
+ heapSiftUp(heap, len(heap)-1)
108
+ return heap
109
+ }
110
+
111
+ func heapUpdate(heap []*batchCursor, i int) {
112
+ // Try to sift up.
113
+ if heapSiftUp(heap, i) != i {
114
+ return
115
+ }
116
+ // Try to sift down, if sifting up failed.
117
+ heapSiftDown(heap, i)
118
+ }
119
+
120
+ func heapRemove(heap []*batchCursor, i int) []*batchCursor {
121
+ // Sift index i up to the root, ignoring actual values.
122
+ for i > 0 {
123
+ heap[(i-1)/2], heap[i] = heap[i], heap[(i-1)/2]
124
+ i = (i - 1) / 2
125
+ }
126
+ // Swap the root with the last element, then remove it.
127
+ heap[0], heap[len(heap)-1] = heap[len(heap)-1], heap[0]
128
+ heap = heap[:len(heap)-1]
129
+ // Sift the root down.
130
+ heapSiftDown(heap, 0)
131
+ return heap
132
+ }
133
+
134
+ func heapSiftUp(heap []*batchCursor, i int) int {
135
+ for i > 0 && heap[(i-1)/2].ev.time > heap[i].ev.time {
136
+ heap[(i-1)/2], heap[i] = heap[i], heap[(i-1)/2]
137
+ i = (i - 1) / 2
138
+ }
139
+ return i
140
+ }
141
+
142
+ func heapSiftDown(heap []*batchCursor, i int) int {
143
+ for {
144
+ m := min3(heap, i, 2*i+1, 2*i+2)
145
+ if m == i {
146
+ // Heap invariant already applies.
147
+ break
148
+ }
149
+ heap[i], heap[m] = heap[m], heap[i]
150
+ i = m
151
+ }
152
+ return i
153
+ }
154
+
155
+ func min3(b []*batchCursor, i0, i1, i2 int) int {
156
+ minIdx := i0
157
+ minT := maxTime
158
+ if i0 < len(b) {
159
+ minT = b[i0].ev.time
160
+ }
161
+ if i1 < len(b) {
162
+ if t := b[i1].ev.time; t < minT {
163
+ minT = t
164
+ minIdx = i1
165
+ }
166
+ }
167
+ if i2 < len(b) {
168
+ if t := b[i2].ev.time; t < minT {
169
+ minT = t
170
+ minIdx = i2
171
+ }
172
+ }
173
+ return minIdx
174
+ }
platform/dbops/binaries/go/go/src/internal/trace/v2/batchcursor_test.go ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package trace
6
+
7
+ import (
8
+ "fmt"
9
+ "strings"
10
+ "testing"
11
+
12
+ "slices"
13
+ )
14
+
15
+ func TestHeap(t *testing.T) {
16
+ var heap []*batchCursor
17
+
18
+ // Insert a bunch of values into the heap.
19
+ checkHeap(t, heap)
20
+ heap = heapInsert(heap, makeBatchCursor(5))
21
+ checkHeap(t, heap)
22
+ for i := int64(-20); i < 20; i++ {
23
+ heap = heapInsert(heap, makeBatchCursor(i))
24
+ checkHeap(t, heap)
25
+ }
26
+
27
+ // Update an element in the middle to be the new minimum.
28
+ for i := range heap {
29
+ if heap[i].ev.time == 5 {
30
+ heap[i].ev.time = -21
31
+ heapUpdate(heap, i)
32
+ break
33
+ }
34
+ }
35
+ checkHeap(t, heap)
36
+ if heap[0].ev.time != -21 {
37
+ t.Fatalf("heap update failed, expected %d as heap min: %s", -21, heapDebugString(heap))
38
+ }
39
+
40
+ // Update the minimum element to be smaller. There should be no change.
41
+ heap[0].ev.time = -22
42
+ heapUpdate(heap, 0)
43
+ checkHeap(t, heap)
44
+ if heap[0].ev.time != -22 {
45
+ t.Fatalf("heap update failed, expected %d as heap min: %s", -22, heapDebugString(heap))
46
+ }
47
+
48
+ // Update the last element to be larger. There should be no change.
49
+ heap[len(heap)-1].ev.time = 21
50
+ heapUpdate(heap, len(heap)-1)
51
+ checkHeap(t, heap)
52
+ if heap[len(heap)-1].ev.time != 21 {
53
+ t.Fatalf("heap update failed, expected %d as heap min: %s", 21, heapDebugString(heap))
54
+ }
55
+
56
+ // Update the last element to be smaller.
57
+ heap[len(heap)-1].ev.time = 7
58
+ heapUpdate(heap, len(heap)-1)
59
+ checkHeap(t, heap)
60
+ if heap[len(heap)-1].ev.time == 21 {
61
+ t.Fatalf("heap update failed, unexpected %d as heap min: %s", 21, heapDebugString(heap))
62
+ }
63
+
64
+ // Remove an element in the middle.
65
+ for i := range heap {
66
+ if heap[i].ev.time == 5 {
67
+ heap = heapRemove(heap, i)
68
+ break
69
+ }
70
+ }
71
+ checkHeap(t, heap)
72
+ for i := range heap {
73
+ if heap[i].ev.time == 5 {
74
+ t.Fatalf("failed to remove heap elem with time %d: %s", 5, heapDebugString(heap))
75
+ }
76
+ }
77
+
78
+ // Remove tail.
79
+ heap = heapRemove(heap, len(heap)-1)
80
+ checkHeap(t, heap)
81
+
82
+ // Remove from the head, and make sure the result is sorted.
83
+ l := len(heap)
84
+ var removed []*batchCursor
85
+ for i := 0; i < l; i++ {
86
+ removed = append(removed, heap[0])
87
+ heap = heapRemove(heap, 0)
88
+ checkHeap(t, heap)
89
+ }
90
+ if !slices.IsSortedFunc(removed, (*batchCursor).compare) {
91
+ t.Fatalf("heap elements not removed in sorted order, got: %s", heapDebugString(removed))
92
+ }
93
+ }
94
+
95
+ func makeBatchCursor(v int64) *batchCursor {
96
+ return &batchCursor{ev: baseEvent{time: Time(v)}}
97
+ }
98
+
99
+ func heapDebugString(heap []*batchCursor) string {
100
+ var sb strings.Builder
101
+ fmt.Fprintf(&sb, "[")
102
+ for i := range heap {
103
+ if i != 0 {
104
+ fmt.Fprintf(&sb, ", ")
105
+ }
106
+ fmt.Fprintf(&sb, "%d", heap[i].ev.time)
107
+ }
108
+ fmt.Fprintf(&sb, "]")
109
+ return sb.String()
110
+ }
111
+
112
+ func checkHeap(t *testing.T, heap []*batchCursor) {
113
+ t.Helper()
114
+
115
+ for i := range heap {
116
+ if i == 0 {
117
+ continue
118
+ }
119
+ if heap[(i-1)/2].compare(heap[i]) > 0 {
120
+ t.Errorf("heap invariant not maintained between index %d and parent %d: %s", i, i/2, heapDebugString(heap))
121
+ }
122
+ }
123
+ if t.Failed() {
124
+ t.FailNow()
125
+ }
126
+ }
platform/dbops/binaries/go/go/src/internal/trace/v2/event.go ADDED
@@ -0,0 +1,780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 The Go Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style
3
+ // license that can be found in the LICENSE file.
4
+
5
+ package trace
6
+
7
+ import (
8
+ "fmt"
9
+ "math"
10
+ "strings"
11
+ "time"
12
+
13
+ "internal/trace/v2/event"
14
+ "internal/trace/v2/event/go122"
15
+ "internal/trace/v2/version"
16
+ )
17
+
18
+ // EventKind indicates the kind of event this is.
19
+ //
20
+ // Use this information to obtain a more specific event that
21
+ // allows access to more detailed information.
22
+ type EventKind uint16
23
+
24
+ const (
25
+ EventBad EventKind = iota
26
+
27
+ // EventKindSync is an event that indicates a global synchronization
28
+ // point in the trace. At the point of a sync event, the
29
+ // trace reader can be certain that all resources (e.g. threads,
30
+ // goroutines) that have existed until that point have been enumerated.
31
+ EventSync
32
+
33
+ // EventMetric is an event that represents the value of a metric at
34
+ // a particular point in time.
35
+ EventMetric
36
+
37
+ // EventLabel attaches a label to a resource.
38
+ EventLabel
39
+
40
+ // EventStackSample represents an execution sample, indicating what a
41
+ // thread/proc/goroutine was doing at a particular point in time via
42
+ // its backtrace.
43
+ //
44
+ // Note: Samples should be considered a close approximation of
45
+ // what a thread/proc/goroutine was executing at a given point in time.
46
+ // These events may slightly contradict the situation StateTransitions
47
+ // describe, so they should only be treated as a best-effort annotation.
48
+ EventStackSample
49
+
50
+ // EventRangeBegin and EventRangeEnd are a pair of generic events representing
51
+ // a special range of time. Ranges are named and scoped to some resource
52
+ // (identified via ResourceKind). A range that has begun but has not ended
53
+ // is considered active.
54
+ //
55
+ // EvRangeBegin and EvRangeEnd will share the same name, and an End will always
56
+ // follow a Begin on the same instance of the resource. The associated
57
+ // resource ID can be obtained from the Event. ResourceNone indicates the
58
+ // range is globally scoped. That is, any goroutine/proc/thread can start or
59
+ // stop, but only one such range may be active at any given time.
60
+ //
61
+ // EventRangeActive is like EventRangeBegin, but indicates that the range was
62
+ // already active. In this case, the resource referenced may not be in the current
63
+ // context.
64
+ EventRangeBegin
65
+ EventRangeActive
66
+ EventRangeEnd
67
+
68
+ // EvTaskBegin and EvTaskEnd are a pair of events representing a runtime/trace.Task.
69
+ EventTaskBegin
70
+ EventTaskEnd
71
+
72
+ // EventRegionBegin and EventRegionEnd are a pair of events represent a runtime/trace.Region.
73
+ EventRegionBegin
74
+ EventRegionEnd
75
+
76
+ // EventLog represents a runtime/trace.Log call.
77
+ EventLog
78
+
79
+ // Transitions in state for some resource.
80
+ EventStateTransition
81
+ )
82
+
83
+ // String returns a string form of the EventKind.
84
+ func (e EventKind) String() string {
85
+ if int(e) >= len(eventKindStrings) {
86
+ return eventKindStrings[0]
87
+ }
88
+ return eventKindStrings[e]
89
+ }
90
+
91
+ var eventKindStrings = [...]string{
92
+ EventBad: "Bad",
93
+ EventSync: "Sync",
94
+ EventMetric: "Metric",
95
+ EventLabel: "Label",
96
+ EventStackSample: "StackSample",
97
+ EventRangeBegin: "RangeBegin",
98
+ EventRangeActive: "RangeActive",
99
+ EventRangeEnd: "RangeEnd",
100
+ EventTaskBegin: "TaskBegin",
101
+ EventTaskEnd: "TaskEnd",
102
+ EventRegionBegin: "RegionBegin",
103
+ EventRegionEnd: "RegionEnd",
104
+ EventLog: "Log",
105
+ EventStateTransition: "StateTransition",
106
+ }
107
+
108
+ const maxTime = Time(math.MaxInt64)
109
+
110
+ // Time is a timestamp in nanoseconds.
111
+ //
112
+ // It corresponds to the monotonic clock on the platform that the
113
+ // trace was taken, and so is possible to correlate with timestamps
114
+ // for other traces taken on the same machine using the same clock
115
+ // (i.e. no reboots in between).
116
+ //
117
+ // The actual absolute value of the timestamp is only meaningful in
118
+ // relation to other timestamps from the same clock.
119
+ //
120
+ // BUG: Timestamps coming from traces on Windows platforms are
121
+ // only comparable with timestamps from the same trace. Timestamps
122
+ // across traces cannot be compared, because the system clock is
123
+ // not used as of Go 1.22.
124
+ //
125
+ // BUG: Traces produced by Go versions 1.21 and earlier cannot be
126
+ // compared with timestamps from other traces taken on the same
127
+ // machine. This is because the system clock was not used at all
128
+ // to collect those timestamps.
129
+ type Time int64
130
+
131
+ // Sub subtracts t0 from t, returning the duration in nanoseconds.
132
+ func (t Time) Sub(t0 Time) time.Duration {
133
+ return time.Duration(int64(t) - int64(t0))
134
+ }
135
+
136
+ // Metric provides details about a Metric event.
137
+ type Metric struct {
138
+ // Name is the name of the sampled metric.
139
+ //
140
+ // Names follow the same convention as metric names in the
141
+ // runtime/metrics package, meaning they include the unit.
142
+ // Names that match with the runtime/metrics package represent
143
+ // the same quantity. Note that this corresponds to the
144
+ // runtime/metrics package for the Go version this trace was
145
+ // collected for.
146
+ Name string
147
+
148
+ // Value is the sampled value of the metric.
149
+ //
150
+ // The Value's Kind is tied to the name of the metric, and so is
151
+ // guaranteed to be the same for metric samples for the same metric.
152
+ Value Value
153
+ }
154
+
155
+ // Label provides details about a Label event.
156
+ type Label struct {
157
+ // Label is the label applied to some resource.
158
+ Label string
159
+
160
+ // Resource is the resource to which this label should be applied.
161
+ Resource ResourceID
162
+ }
163
+
164
+ // Range provides details about a Range event.
165
+ type Range struct {
166
+ // Name is a human-readable name for the range.
167
+ //
168
+ // This name can be used to identify the end of the range for the resource
169
+ // its scoped to, because only one of each type of range may be active on
170
+ // a particular resource. The relevant resource should be obtained from the
171
+ // Event that produced these details. The corresponding RangeEnd will have
172
+ // an identical name.
173
+ Name string
174
+
175
+ // Scope is the resource that the range is scoped to.
176
+ //
177
+ // For example, a ResourceGoroutine scope means that the same goroutine
178
+ // must have a start and end for the range, and that goroutine can only
179
+ // have one range of a particular name active at any given time. The
180
+ // ID that this range is scoped to may be obtained via Event.Goroutine.
181
+ //
182
+ // The ResourceNone scope means that the range is globally scoped. As a
183
+ // result, any goroutine/proc/thread may start or end the range, and only
184
+ // one such named range may be active globally at any given time.
185
+ //
186
+ // For RangeBegin and RangeEnd events, this will always reference some
187
+ // resource ID in the current execution context. For RangeActive events,
188
+ // this may reference a resource not in the current context. Prefer Scope
189
+ // over the current execution context.
190
+ Scope ResourceID
191
+ }
192
+
193
+ // RangeAttributes provides attributes about a completed Range.
194
+ type RangeAttribute struct {
195
+ // Name is the human-readable name for the range.
196
+ Name string
197
+
198
+ // Value is the value of the attribute.
199
+ Value Value
200
+ }
201
+
202
+ // TaskID is the internal ID of a task used to disambiguate tasks (even if they
203
+ // are of the same type).
204
+ type TaskID uint64
205
+
206
+ const (
207
+ // NoTask indicates the lack of a task.
208
+ NoTask = TaskID(^uint64(0))
209
+
210
+ // BackgroundTask is the global task that events are attached to if there was
211
+ // no other task in the context at the point the event was emitted.
212
+ BackgroundTask = TaskID(0)
213
+ )
214
+
215
+ // Task provides details about a Task event.
216
+ type Task struct {
217
+ // ID is a unique identifier for the task.
218
+ //
219
+ // This can be used to associate the beginning of a task with its end.
220
+ ID TaskID
221
+
222
+ // ParentID is the ID of the parent task.
223
+ Parent TaskID
224
+
225
+ // Type is the taskType that was passed to runtime/trace.NewTask.
226
+ //
227
+ // May be "" if a task's TaskBegin event isn't present in the trace.
228
+ Type string
229
+ }
230
+
231
+ // Region provides details about a Region event.
232
+ type Region struct {
233
+ // Task is the ID of the task this region is associated with.
234
+ Task TaskID
235
+
236
+ // Type is the regionType that was passed to runtime/trace.StartRegion or runtime/trace.WithRegion.
237
+ Type string
238
+ }
239
+
240
+ // Log provides details about a Log event.
241
+ type Log struct {
242
+ // Task is the ID of the task this region is associated with.
243
+ Task TaskID
244
+
245
+ // Category is the category that was passed to runtime/trace.Log or runtime/trace.Logf.
246
+ Category string
247
+
248
+ // Message is the message that was passed to runtime/trace.Log or runtime/trace.Logf.
249
+ Message string
250
+ }
251
+
252
+ // Stack represents a stack. It's really a handle to a stack and it's trivially comparable.
253
+ //
254
+ // If two Stacks are equal then their Frames are guaranteed to be identical. If they are not
255
+ // equal, however, their Frames may still be equal.
256
+ type Stack struct {
257
+ table *evTable
258
+ id stackID
259
+ }
260
+
261
+ // Frames is an iterator over the frames in a Stack.
262
+ func (s Stack) Frames(yield func(f StackFrame) bool) bool {
263
+ if s.id == 0 {
264
+ return true
265
+ }
266
+ stk := s.table.stacks.mustGet(s.id)
267
+ for _, f := range stk.frames {
268
+ sf := StackFrame{
269
+ PC: f.pc,
270
+ Func: s.table.strings.mustGet(f.funcID),
271
+ File: s.table.strings.mustGet(f.fileID),
272
+ Line: f.line,
273
+ }
274
+ if !yield(sf) {
275
+ return false
276
+ }
277
+ }
278
+ return true
279
+ }
280
+
281
+ // NoStack is a sentinel value that can be compared against any Stack value, indicating
282
+ // a lack of a stack trace.
283
+ var NoStack = Stack{}
284
+
285
+ // StackFrame represents a single frame of a stack.
286
+ type StackFrame struct {
287
+ // PC is the program counter of the function call if this
288
+ // is not a leaf frame. If it's a leaf frame, it's the point
289
+ // at which the stack trace was taken.
290
+ PC uint64
291
+
292
+ // Func is the name of the function this frame maps to.
293
+ Func string
294
+
295
+ // File is the file which contains the source code of Func.
296
+ File string
297
+
298
+ // Line is the line number within File which maps to PC.
299
+ Line uint64
300
+ }
301
+
302
+ // Event represents a single event in the trace.
303
+ type Event struct {
304
+ table *evTable
305
+ ctx schedCtx
306
+ base baseEvent
307
+ }
308
+
309
+ // Kind returns the kind of event that this is.
310
+ func (e Event) Kind() EventKind {
311
+ return go122Type2Kind[e.base.typ]
312
+ }
313
+
314
+ // Time returns the timestamp of the event.
315
+ func (e Event) Time() Time {
316
+ return e.base.time
317
+ }
318
+
319
+ // Goroutine returns the ID of the goroutine that was executing when
320
+ // this event happened. It describes part of the execution context
321
+ // for this event.
322
+ //
323
+ // Note that for goroutine state transitions this always refers to the
324
+ // state before the transition. For example, if a goroutine is just
325
+ // starting to run on this thread and/or proc, then this will return
326
+ // NoGoroutine. In this case, the goroutine starting to run will be
327
+ // can be found at Event.StateTransition().Resource.
328
+ func (e Event) Goroutine() GoID {
329
+ return e.ctx.G
330
+ }
331
+
332
+ // Proc returns the ID of the proc this event event pertains to.
333
+ //
334
+ // Note that for proc state transitions this always refers to the
335
+ // state before the transition. For example, if a proc is just
336
+ // starting to run on this thread, then this will return NoProc.
337
+ func (e Event) Proc() ProcID {
338
+ return e.ctx.P
339
+ }
340
+
341
+ // Thread returns the ID of the thread this event pertains to.
342
+ //
343
+ // Note that for thread state transitions this always refers to the
344
+ // state before the transition. For example, if a thread is just
345
+ // starting to run, then this will return NoThread.
346
+ //
347
+ // Note: tracking thread state is not currently supported, so this
348
+ // will always return a valid thread ID. However thread state transitions
349
+ // may be tracked in the future, and callers must be robust to this
350
+ // possibility.
351
+ func (e Event) Thread() ThreadID {
352
+ return e.ctx.M
353
+ }
354
+
355
+ // Stack returns a handle to a stack associated with the event.
356
+ //
357
+ // This represents a stack trace at the current moment in time for
358
+ // the current execution context.
359
+ func (e Event) Stack() Stack {
360
+ if e.base.typ == evSync {
361
+ return NoStack
362
+ }
363
+ if e.base.typ == go122.EvCPUSample {
364
+ return Stack{table: e.table, id: stackID(e.base.args[0])}
365
+ }
366
+ spec := go122.Specs()[e.base.typ]
367
+ if len(spec.StackIDs) == 0 {
368
+ return NoStack
369
+ }
370
+ // The stack for the main execution context is always the
371
+ // first stack listed in StackIDs. Subtract one from this
372
+ // because we've peeled away the timestamp argument.
373
+ id := stackID(e.base.args[spec.StackIDs[0]-1])
374
+ if id == 0 {
375
+ return NoStack
376
+ }
377
+ return Stack{table: e.table, id: id}
378
+ }
379
+
380
+ // Metric returns details about a Metric event.
381
+ //
382
+ // Panics if Kind != EventMetric.
383
+ func (e Event) Metric() Metric {
384
+ if e.Kind() != EventMetric {
385
+ panic("Metric called on non-Metric event")
386
+ }
387
+ var m Metric
388
+ switch e.base.typ {
389
+ case go122.EvProcsChange:
390
+ m.Name = "/sched/gomaxprocs:threads"
391
+ m.Value = Value{kind: ValueUint64, scalar: e.base.args[0]}
392
+ case go122.EvHeapAlloc:
393
+ m.Name = "/memory/classes/heap/objects:bytes"
394
+ m.Value = Value{kind: ValueUint64, scalar: e.base.args[0]}
395
+ case go122.EvHeapGoal:
396
+ m.Name = "/gc/heap/goal:bytes"
397
+ m.Value = Value{kind: ValueUint64, scalar: e.base.args[0]}
398
+ default:
399
+ panic(fmt.Sprintf("internal error: unexpected event type for Metric kind: %s", go122.EventString(e.base.typ)))
400
+ }
401
+ return m
402
+ }
403
+
404
+ // Label returns details about a Label event.
405
+ //
406
+ // Panics if Kind != EventLabel.
407
+ func (e Event) Label() Label {
408
+ if e.Kind() != EventLabel {
409
+ panic("Label called on non-Label event")
410
+ }
411
+ if e.base.typ != go122.EvGoLabel {
412
+ panic(fmt.Sprintf("internal error: unexpected event type for Label kind: %s", go122.EventString(e.base.typ)))
413
+ }
414
+ return Label{
415
+ Label: e.table.strings.mustGet(stringID(e.base.args[0])),
416
+ Resource: ResourceID{Kind: ResourceGoroutine, id: int64(e.ctx.G)},
417
+ }
418
+ }
419
+
420
+ // Range returns details about an EventRangeBegin, EventRangeActive, or EventRangeEnd event.
421
+ //
422
+ // Panics if Kind != EventRangeBegin, Kind != EventRangeActive, and Kind != EventRangeEnd.
423
+ func (e Event) Range() Range {
424
+ if kind := e.Kind(); kind != EventRangeBegin && kind != EventRangeActive && kind != EventRangeEnd {
425
+ panic("Range called on non-Range event")
426
+ }
427
+ var r Range
428
+ switch e.base.typ {
429
+ case go122.EvSTWBegin, go122.EvSTWEnd:
430
+ // N.B. ordering.advance smuggles in the STW reason as e.base.args[0]
431
+ // for go122.EvSTWEnd (it's already there for Begin).
432
+ r.Name = "stop-the-world (" + e.table.strings.mustGet(stringID(e.base.args[0])) + ")"
433
+ r.Scope = ResourceID{Kind: ResourceGoroutine, id: int64(e.Goroutine())}
434
+ case go122.EvGCBegin, go122.EvGCActive, go122.EvGCEnd:
435
+ r.Name = "GC concurrent mark phase"
436
+ r.Scope = ResourceID{Kind: ResourceNone}
437
+ case go122.EvGCSweepBegin, go122.EvGCSweepActive, go122.EvGCSweepEnd:
438
+ r.Name = "GC incremental sweep"
439
+ r.Scope = ResourceID{Kind: ResourceProc}
440
+ if e.base.typ == go122.EvGCSweepActive {
441
+ r.Scope.id = int64(e.base.args[0])
442
+ } else {
443
+ r.Scope.id = int64(e.Proc())
444
+ }
445
+ r.Scope.id = int64(e.Proc())
446
+ case go122.EvGCMarkAssistBegin, go122.EvGCMarkAssistActive, go122.EvGCMarkAssistEnd:
447
+ r.Name = "GC mark assist"
448
+ r.Scope = ResourceID{Kind: ResourceGoroutine}
449
+ if e.base.typ == go122.EvGCMarkAssistActive {
450
+ r.Scope.id = int64(e.base.args[0])
451
+ } else {
452
+ r.Scope.id = int64(e.Goroutine())
453
+ }
454
+ default:
455
+ panic(fmt.Sprintf("internal error: unexpected event type for Range kind: %s", go122.EventString(e.base.typ)))
456
+ }
457
+ return r
458
+ }
459
+
460
+ // RangeAttributes returns attributes for a completed range.
461
+ //
462
+ // Panics if Kind != EventRangeEnd.
463
+ func (e Event) RangeAttributes() []RangeAttribute {
464
+ if e.Kind() != EventRangeEnd {
465
+ panic("Range called on non-Range event")
466
+ }
467
+ if e.base.typ != go122.EvGCSweepEnd {
468
+ return nil
469
+ }
470
+ return []RangeAttribute{
471
+ {
472
+ Name: "bytes swept",
473
+ Value: Value{kind: ValueUint64, scalar: e.base.args[0]},
474
+ },
475
+ {
476
+ Name: "bytes reclaimed",
477
+ Value: Value{kind: ValueUint64, scalar: e.base.args[1]},
478
+ },
479
+ }
480
+ }
481
+
482
+ // Task returns details about a TaskBegin or TaskEnd event.
483
+ //
484
+ // Panics if Kind != EventTaskBegin and Kind != EventTaskEnd.
485
+ func (e Event) Task() Task {
486
+ if kind := e.Kind(); kind != EventTaskBegin && kind != EventTaskEnd {
487
+ panic("Task called on non-Task event")
488
+ }
489
+ parentID := NoTask
490
+ var typ string
491
+ switch e.base.typ {
492
+ case go122.EvUserTaskBegin:
493
+ parentID = TaskID(e.base.args[1])
494
+ typ = e.table.strings.mustGet(stringID(e.base.args[2]))
495
+ case go122.EvUserTaskEnd:
496
+ parentID = TaskID(e.base.extra(version.Go122)[0])
497
+ typ = e.table.getExtraString(extraStringID(e.base.extra(version.Go122)[1]))
498
+ default:
499
+ panic(fmt.Sprintf("internal error: unexpected event type for Task kind: %s", go122.EventString(e.base.typ)))
500
+ }
501
+ return Task{
502
+ ID: TaskID(e.base.args[0]),
503
+ Parent: parentID,
504
+ Type: typ,
505
+ }
506
+ }
507
+
508
+ // Region returns details about a RegionBegin or RegionEnd event.
509
+ //
510
+ // Panics if Kind != EventRegionBegin and Kind != EventRegionEnd.
511
+ func (e Event) Region() Region {
512
+ if kind := e.Kind(); kind != EventRegionBegin && kind != EventRegionEnd {
513
+ panic("Region called on non-Region event")
514
+ }
515
+ if e.base.typ != go122.EvUserRegionBegin && e.base.typ != go122.EvUserRegionEnd {
516
+ panic(fmt.Sprintf("internal error: unexpected event type for Region kind: %s", go122.EventString(e.base.typ)))
517
+ }
518
+ return Region{
519
+ Task: TaskID(e.base.args[0]),
520
+ Type: e.table.strings.mustGet(stringID(e.base.args[1])),
521
+ }
522
+ }
523
+
524
+ // Log returns details about a Log event.
525
+ //
526
+ // Panics if Kind != EventLog.
527
+ func (e Event) Log() Log {
528
+ if e.Kind() != EventLog {
529
+ panic("Log called on non-Log event")
530
+ }
531
+ if e.base.typ != go122.EvUserLog {
532
+ panic(fmt.Sprintf("internal error: unexpected event type for Log kind: %s", go122.EventString(e.base.typ)))
533
+ }
534
+ return Log{
535
+ Task: TaskID(e.base.args[0]),
536
+ Category: e.table.strings.mustGet(stringID(e.base.args[1])),
537
+ Message: e.table.strings.mustGet(stringID(e.base.args[2])),
538
+ }
539
+ }
540
+
541
+ // StateTransition returns details about a StateTransition event.
542
+ //
543
+ // Panics if Kind != EventStateTransition.
544
+ func (e Event) StateTransition() StateTransition {
545
+ if e.Kind() != EventStateTransition {
546
+ panic("StateTransition called on non-StateTransition event")
547
+ }
548
+ var s StateTransition
549
+ switch e.base.typ {
550
+ case go122.EvProcStart:
551
+ s = procStateTransition(ProcID(e.base.args[0]), ProcIdle, ProcRunning)
552
+ case go122.EvProcStop:
553
+ s = procStateTransition(e.ctx.P, ProcRunning, ProcIdle)
554
+ case go122.EvProcSteal:
555
+ // N.B. ordering.advance populates e.base.extra.
556
+ beforeState := ProcRunning
557
+ if go122.ProcStatus(e.base.extra(version.Go122)[0]) == go122.ProcSyscallAbandoned {
558
+ // We've lost information because this ProcSteal advanced on a
559
+ // SyscallAbandoned state. Treat the P as idle because ProcStatus
560
+ // treats SyscallAbandoned as Idle. Otherwise we'll have an invalid
561
+ // transition.
562
+ beforeState = ProcIdle
563
+ }
564
+ s = procStateTransition(ProcID(e.base.args[0]), beforeState, ProcIdle)
565
+ case go122.EvProcStatus:
566
+ // N.B. ordering.advance populates e.base.extra.
567
+ s = procStateTransition(ProcID(e.base.args[0]), ProcState(e.base.extra(version.Go122)[0]), go122ProcStatus2ProcState[e.base.args[1]])
568
+ case go122.EvGoCreate:
569
+ s = goStateTransition(GoID(e.base.args[0]), GoNotExist, GoRunnable)
570
+ s.Stack = Stack{table: e.table, id: stackID(e.base.args[1])}
571
+ case go122.EvGoCreateSyscall:
572
+ s = goStateTransition(GoID(e.base.args[0]), GoNotExist, GoSyscall)
573
+ case go122.EvGoStart:
574
+ s = goStateTransition(GoID(e.base.args[0]), GoRunnable, GoRunning)
575
+ case go122.EvGoDestroy:
576
+ s = goStateTransition(e.ctx.G, GoRunning, GoNotExist)
577
+ s.Stack = e.Stack() // This event references the resource the event happened on.
578
+ case go122.EvGoDestroySyscall:
579
+ s = goStateTransition(e.ctx.G, GoSyscall, GoNotExist)
580
+ case go122.EvGoStop:
581
+ s = goStateTransition(e.ctx.G, GoRunning, GoRunnable)
582
+ s.Reason = e.table.strings.mustGet(stringID(e.base.args[0]))
583
+ s.Stack = e.Stack() // This event references the resource the event happened on.
584
+ case go122.EvGoBlock:
585
+ s = goStateTransition(e.ctx.G, GoRunning, GoWaiting)
586
+ s.Reason = e.table.strings.mustGet(stringID(e.base.args[0]))
587
+ s.Stack = e.Stack() // This event references the resource the event happened on.
588
+ case go122.EvGoUnblock:
589
+ s = goStateTransition(GoID(e.base.args[0]), GoWaiting, GoRunnable)
590
+ case go122.EvGoSyscallBegin:
591
+ s = goStateTransition(e.ctx.G, GoRunning, GoSyscall)
592
+ s.Stack = e.Stack() // This event references the resource the event happened on.
593
+ case go122.EvGoSyscallEnd:
594
+ s = goStateTransition(e.ctx.G, GoSyscall, GoRunning)
595
+ s.Stack = e.Stack() // This event references the resource the event happened on.
596
+ case go122.EvGoSyscallEndBlocked:
597
+ s = goStateTransition(e.ctx.G, GoSyscall, GoRunnable)
598
+ s.Stack = e.Stack() // This event references the resource the event happened on.
599
+ case go122.EvGoStatus:
600
+ // N.B. ordering.advance populates e.base.extra.
601
+ s = goStateTransition(GoID(e.base.args[0]), GoState(e.base.extra(version.Go122)[0]), go122GoStatus2GoState[e.base.args[2]])
602
+ default:
603
+ panic(fmt.Sprintf("internal error: unexpected event type for StateTransition kind: %s", go122.EventString(e.base.typ)))
604
+ }
605
+ return s
606
+ }
607
+
608
+ const evSync = ^event.Type(0)
609
+
610
+ var go122Type2Kind = [...]EventKind{
611
+ go122.EvCPUSample: EventStackSample,
612
+ go122.EvProcsChange: EventMetric,
613
+ go122.EvProcStart: EventStateTransition,
614
+ go122.EvProcStop: EventStateTransition,
615
+ go122.EvProcSteal: EventStateTransition,
616
+ go122.EvProcStatus: EventStateTransition,
617
+ go122.EvGoCreate: EventStateTransition,
618
+ go122.EvGoCreateSyscall: EventStateTransition,
619
+ go122.EvGoStart: EventStateTransition,
620
+ go122.EvGoDestroy: EventStateTransition,
621
+ go122.EvGoDestroySyscall: EventStateTransition,
622
+ go122.EvGoStop: EventStateTransition,
623
+ go122.EvGoBlock: EventStateTransition,
624
+ go122.EvGoUnblock: EventStateTransition,
625
+ go122.EvGoSyscallBegin: EventStateTransition,
626
+ go122.EvGoSyscallEnd: EventStateTransition,
627
+ go122.EvGoSyscallEndBlocked: EventStateTransition,
628
+ go122.EvGoStatus: EventStateTransition,
629
+ go122.EvSTWBegin: EventRangeBegin,
630
+ go122.EvSTWEnd: EventRangeEnd,
631
+ go122.EvGCActive: EventRangeActive,
632
+ go122.EvGCBegin: EventRangeBegin,
633
+ go122.EvGCEnd: EventRangeEnd,
634
+ go122.EvGCSweepActive: EventRangeActive,
635
+ go122.EvGCSweepBegin: EventRangeBegin,
636
+ go122.EvGCSweepEnd: EventRangeEnd,
637
+ go122.EvGCMarkAssistActive: EventRangeActive,
638
+ go122.EvGCMarkAssistBegin: EventRangeBegin,
639
+ go122.EvGCMarkAssistEnd: EventRangeEnd,
640
+ go122.EvHeapAlloc: EventMetric,
641
+ go122.EvHeapGoal: EventMetric,
642
+ go122.EvGoLabel: EventLabel,
643
+ go122.EvUserTaskBegin: EventTaskBegin,
644
+ go122.EvUserTaskEnd: EventTaskEnd,
645
+ go122.EvUserRegionBegin: EventRegionBegin,
646
+ go122.EvUserRegionEnd: EventRegionEnd,
647
+ go122.EvUserLog: EventLog,
648
+ evSync: EventSync,
649
+ }
650
+
651
+ var go122GoStatus2GoState = [...]GoState{
652
+ go122.GoRunnable: GoRunnable,
653
+ go122.GoRunning: GoRunning,
654
+ go122.GoWaiting: GoWaiting,
655
+ go122.GoSyscall: GoSyscall,
656
+ }
657
+
658
+ var go122ProcStatus2ProcState = [...]ProcState{
659
+ go122.ProcRunning: ProcRunning,
660
+ go122.ProcIdle: ProcIdle,
661
+ go122.ProcSyscall: ProcRunning,
662
+ go122.ProcSyscallAbandoned: ProcIdle,
663
+ }
664
+
665
+ // String returns the event as a human-readable string.
666
+ //
667
+ // The format of the string is intended for debugging and is subject to change.
668
+ func (e Event) String() string {
669
+ var sb strings.Builder
670
+ fmt.Fprintf(&sb, "M=%d P=%d G=%d", e.Thread(), e.Proc(), e.Goroutine())
671
+ fmt.Fprintf(&sb, " %s Time=%d", e.Kind(), e.Time())
672
+ // Kind-specific fields.
673
+ switch kind := e.Kind(); kind {
674
+ case EventMetric:
675
+ m := e.Metric()
676
+ fmt.Fprintf(&sb, " Name=%q Value=%s", m.Name, valueAsString(m.Value))
677
+ case EventLabel:
678
+ l := e.Label()
679
+ fmt.Fprintf(&sb, " Label=%q Resource=%s", l.Label, l.Resource)
680
+ case EventRangeBegin, EventRangeActive, EventRangeEnd:
681
+ r := e.Range()
682
+ fmt.Fprintf(&sb, " Name=%q Scope=%s", r.Name, r.Scope)
683
+ if kind == EventRangeEnd {
684
+ fmt.Fprintf(&sb, " Attributes=[")
685
+ for i, attr := range e.RangeAttributes() {
686
+ if i != 0 {
687
+ fmt.Fprintf(&sb, " ")
688
+ }
689
+ fmt.Fprintf(&sb, "%q=%s", attr.Name, valueAsString(attr.Value))
690
+ }
691
+ fmt.Fprintf(&sb, "]")
692
+ }
693
+ case EventTaskBegin, EventTaskEnd:
694
+ t := e.Task()
695
+ fmt.Fprintf(&sb, " ID=%d Parent=%d Type=%q", t.ID, t.Parent, t.Type)
696
+ case EventRegionBegin, EventRegionEnd:
697
+ r := e.Region()
698
+ fmt.Fprintf(&sb, " Task=%d Type=%q", r.Task, r.Type)
699
+ case EventLog:
700
+ l := e.Log()
701
+ fmt.Fprintf(&sb, " Task=%d Category=%q Message=%q", l.Task, l.Category, l.Message)
702
+ case EventStateTransition:
703
+ s := e.StateTransition()
704
+ fmt.Fprintf(&sb, " Resource=%s Reason=%q", s.Resource, s.Reason)
705
+ switch s.Resource.Kind {
706
+ case ResourceGoroutine:
707
+ id := s.Resource.Goroutine()
708
+ old, new := s.Goroutine()
709
+ fmt.Fprintf(&sb, " GoID=%d %s->%s", id, old, new)
710
+ case ResourceProc:
711
+ id := s.Resource.Proc()
712
+ old, new := s.Proc()
713
+ fmt.Fprintf(&sb, " ProcID=%d %s->%s", id, old, new)
714
+ }
715
+ if s.Stack != NoStack {
716
+ fmt.Fprintln(&sb)
717
+ fmt.Fprintln(&sb, "TransitionStack=")
718
+ s.Stack.Frames(func(f StackFrame) bool {
719
+ fmt.Fprintf(&sb, "\t%s @ 0x%x\n", f.Func, f.PC)
720
+ fmt.Fprintf(&sb, "\t\t%s:%d\n", f.File, f.Line)
721
+ return true
722
+ })
723
+ }
724
+ }
725
+ if stk := e.Stack(); stk != NoStack {
726
+ fmt.Fprintln(&sb)
727
+ fmt.Fprintln(&sb, "Stack=")
728
+ stk.Frames(func(f StackFrame) bool {
729
+ fmt.Fprintf(&sb, "\t%s @ 0x%x\n", f.Func, f.PC)
730
+ fmt.Fprintf(&sb, "\t\t%s:%d\n", f.File, f.Line)
731
+ return true
732
+ })
733
+ }
734
+ return sb.String()
735
+ }
736
+
737
+ // validateTableIDs checks to make sure lookups in e.table
738
+ // will work.
739
+ func (e Event) validateTableIDs() error {
740
+ if e.base.typ == evSync {
741
+ return nil
742
+ }
743
+ spec := go122.Specs()[e.base.typ]
744
+
745
+ // Check stacks.
746
+ for _, i := range spec.StackIDs {
747
+ id := stackID(e.base.args[i-1])
748
+ _, ok := e.table.stacks.get(id)
749
+ if !ok {
750
+ return fmt.Errorf("found invalid stack ID %d for event %s", id, spec.Name)
751
+ }
752
+ }
753
+ // N.B. Strings referenced by stack frames are validated
754
+ // early on, when reading the stacks in to begin with.
755
+
756
+ // Check strings.
757
+ for _, i := range spec.StringIDs {
758
+ id := stringID(e.base.args[i-1])
759
+ _, ok := e.table.strings.get(id)
760
+ if !ok {
761
+ return fmt.Errorf("found invalid string ID %d for event %s", id, spec.Name)
762
+ }
763
+ }
764
+ return nil
765
+ }
766
+
767
+ func syncEvent(table *evTable, ts Time) Event {
768
+ return Event{
769
+ table: table,
770
+ ctx: schedCtx{
771
+ G: NoGoroutine,
772
+ P: NoProc,
773
+ M: NoThread,
774
+ },
775
+ base: baseEvent{
776
+ typ: evSync,
777
+ time: ts,
778
+ },
779
+ }
780
+ }