Debian Codegraph @

libgo/go/runtime/time_fake.go

raw
1 // Copyright 2019 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 faketime && !windows
6
7 // Faketime isn't currently supported on Windows. This would require
8 // modifying syscall.Write to call syscall.faketimeWrite,
9 // translating the Stdout and Stderr handles into FDs 1 and 2.
10 // (See CL 192739 PS 3.)
11
12 package runtime
13
14 import "unsafe"
15
16 // faketime is the simulated time in nanoseconds since 1970 for the
17 // playground.
18 var faketime int64 = 1257894000000000000
19
20 var faketimeState struct {
21 lock mutex
22
23 // lastfaketime is the last faketime value written to fd 1 or 2.
24 lastfaketime int64
25
26 // lastfd is the fd to which lastfaketime was written.
27 //
28 // Subsequent writes to the same fd may use the same
29 // timestamp, but the timestamp must increase if the fd
30 // changes.
31 lastfd uintptr
32 }
33
34 //go:nosplit
35 func nanotime() int64 {
36 return faketime
37 }
38
39 //go:linkname time_now time.now
40 func time_now() (sec int64, nsec int32, mono int64) {
41 return faketime / 1e9, int32(faketime % 1e9), faketime
42 }
43
44 // write is like the Unix write system call.
45 // We have to avoid write barriers to avoid potential deadlock
46 // on write calls.
47 //go:nowritebarrierrec
48 func write(fd uintptr, p unsafe.Pointer, n int32) int32 {
49 if !(fd == 1 || fd == 2) {
50 // Do an ordinary write.
51 return write1(fd, p, n)
52 }
53
54 // Write with the playback header.
55
56 // First, lock to avoid interleaving writes.
57 lock(&faketimeState.lock)
58
59 // If the current fd doesn't match the fd of the previous write,
60 // ensure that the timestamp is strictly greater. That way, we can
61 // recover the original order even if we read the fds separately.
62 t := faketimeState.lastfaketime
63 if fd != faketimeState.lastfd {
64 t++
65 faketimeState.lastfd = fd
66 }
67 if faketime > t {
68 t = faketime
69 }
70 faketimeState.lastfaketime = t
71
72 // Playback header: 0 0 P B <8-byte time> <4-byte data length> (big endian)
73 var buf [4 + 8 + 4]byte
74 buf[2] = 'P'
75 buf[3] = 'B'
76 tu := uint64(t)
77 buf[4] = byte(tu >> (7 * 8))
78 buf[5] = byte(tu >> (6 * 8))
79 buf[6] = byte(tu >> (5 * 8))
80 buf[7] = byte(tu >> (4 * 8))
81 buf[8] = byte(tu >> (3 * 8))
82 buf[9] = byte(tu >> (2 * 8))
83 buf[10] = byte(tu >> (1 * 8))
84 buf[11] = byte(tu >> (0 * 8))
85 nu := uint32(n)
86 buf[12] = byte(nu >> (3 * 8))
87 buf[13] = byte(nu >> (2 * 8))
88 buf[14] = byte(nu >> (1 * 8))
89 buf[15] = byte(nu >> (0 * 8))
90 write1(fd, unsafe.Pointer(&buf[0]), int32(len(buf)))
91
92 // Write actual data.
93 res := write1(fd, p, n)
94
95 unlock(&faketimeState.lock)
96 return res
97 }