Debian Codegraph @

internal/host/host_nocgo.go

raw symbols SCIP
1 //go:build !cgo
2
3 // Copyright 2018 psgo authors
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16
17 // Package host extracts data from the host, such as the system's boot time or
18 // the tick rate of the system clock.
19 package host
20
21 import (
22 "encoding/binary"
23 "fmt"
24 "os"
25 "unsafe"
26 )
27
28 var (
29 // cache host queries to redundant calculations
30 clockTicks *int64
31 bootTime *int64
32 )
33
34 func getNativeEndianness() binary.ByteOrder {
35 var i int32 = 0x00000001
36 u := unsafe.Pointer(&i)
37 if *((*byte)(u)) == 0x01 {
38 return binary.LittleEndian
39 }
40 return binary.BigEndian
41 }
42
43 const (
44 atClktck = 17
45 )
46
47 func getFromAuxv(what uint, whatName string) (uint, error) {
48 dataLen := int(unsafe.Sizeof(int(0)))
49 p, err := os.ReadFile("/proc/self/auxv")
50 if err != nil {
51 return 0, err
52 }
53 native := getNativeEndianness()
54 for i := 0; i < len(p); {
55 var k, v uint
56
57 switch dataLen {
58 case 4:
59 k = uint(native.Uint32(p[i : i+dataLen]))
60 v = uint(native.Uint32(p[i+dataLen : i+dataLen*2]))
61 case 8:
62 k = uint(native.Uint64(p[i : i+dataLen]))
63 v = uint(native.Uint64(p[i+dataLen : i+dataLen*2]))
64 }
65 i += dataLen * 2
66 if k == what {
67 return v, nil
68 }
69 }
70 return 0, fmt.Errorf("cannot find %s in auxv", whatName)
71 }
72
73 // ClockTicks returns sysconf(SC_CLK_TCK).
74 func ClockTicks() (int64, error) {
75 if clockTicks == nil {
76 ret, err := getFromAuxv(atClktck, "AT_CLKTCK")
77 if err != nil {
78 return -1, err
79 }
80 ticks := int64(ret)
81 clockTicks = &ticks
82 }
83 return *clockTicks, nil
84 }