50 Commits
rm ... master

Author SHA1 Message Date
eleksir
05eab972d7 Looks like we do not need separators for buttons 2026-03-31 02:07:17 +03:00
eleksir
eeddce7225 Merge branch 'master' of http://git.lan/eleksir/i3status-go 2026-03-31 01:32:28 +03:00
eleksir
56aa0f7e5e Fix rendering in main.go - separators never handled in formally correct way. 2026-03-31 01:26:46 +03:00
eleksir
86596461a1 More efficiently reap zombeis in spawn.go 2026-03-31 01:23:02 +03:00
eleksir
cd57dbc770 More efficient look for leading "{" symbold in stdin.go 2026-03-31 01:18:33 +03:00
eleksir
f2c24bc0ec Render buttons border immedialtely after windo list population 2026-03-31 01:12:32 +03:00
eleksir
bd6aa31c4d Discard unneccessary cast to any 2026-03-31 01:04:47 +03:00
eleksir
f59ac30f51 Handle error in batteries.go in battery.GetAll(), maybe it is bad idea 2026-03-31 01:02:17 +03:00
eleksir
4beda1639e Fix hypotetical file leakage in cputemp.go 2026-03-31 00:59:34 +03:00
eleksir
7a133f3867 Fix possinble division by zero in cputemp.go 2026-03-31 00:57:37 +03:00
eleksir
3f1adbe126 Log error in la.go if unable to open file 2026-03-31 00:55:38 +03:00
eleksir
0d3f805a2d Inconsistent string trimming in batteries.go 2026-03-31 00:53:51 +03:00
eleksir
2855b9e612 Eliminate unused variable in signal.go 2026-03-31 00:51:44 +03:00
eleksir
217948ade6 Inconsistent variable name in ifmon.go 2026-03-31 00:49:52 +03:00
eleksir
c621d03a71 Fix issue while getting windows tree in i3.go 2026-03-31 00:40:10 +03:00
eleksir
13efa0393c Do not exec() if binary path is empty 2026-03-31 00:38:15 +03:00
eleksir
d5f81e9fd6 Remove redundant close of /dev/null in spawn.go 2026-03-31 00:36:12 +03:00
eleksir
8f742709b6 Make delay before execution command in more efficient way 2026-03-31 00:32:02 +03:00
eleksir
40213ba5c3 Read swap statistics only if swap stats enabled 2026-03-31 00:29:09 +03:00
eleksir
deeb0dfbf0 Formally check open() result for /dev/null 2026-03-31 00:27:18 +03:00
eleksir
ad013fb8f5 Cache regex evaluation in i3.go 2026-03-31 00:23:48 +03:00
eleksir
6def26ef02 Add missing modeline to cmd/battery-test/main.go 2026-03-31 00:21:57 +03:00
eleksir
a16816e862 Avoid busy loop in zombies reap procedure. 2026-03-31 00:21:06 +03:00
eleksir
cc6cc192cb Fix battery detection. 2026-03-31 00:19:02 +03:00
eleksir
f59b735f38 Fix possible multiple command execution in rare case. 2026-03-31 00:17:12 +03:00
eleksir
53c7fe292e In runcommand.go logged incorrect variable 2026-03-31 00:14:29 +03:00
eleksir
fe0b0bf6dd Fix inconsistent swap calculation 2026-03-31 00:11:54 +03:00
eleksir
8f3f6c77bd Fix bug - right-most separator never displayed 2026-03-31 00:09:19 +03:00
eleksir
5750894336 Add vim modeline to all *.go files 2026-03-31 00:08:15 +03:00
eleksir
63f1a142d8 Fix couple nasty bugs in collection.go, safer type assertions. 2026-03-30 23:49:06 +03:00
eleksir
9bea626f7c Fix potential panic in i3.go, check interface{} for nil 2026-03-30 23:36:06 +03:00
eleksir
3f5704237a [WIP] Update linter config + speed optimizations 2025-11-23 16:41:20 +03:00
eleksir
d9ce425981 Finally fix parsing of app buttons, now settings and fallback values should work as expected 2025-07-15 14:29:27 +03:00
eleksir
069b09e5ec Update default config example 2025-07-12 14:00:55 +03:00
eleksir
8f2afa0441 Fix font size checks and fallbacks 2025-07-12 13:43:10 +03:00
eleksir
8fa1c6d596 Allow to override (in config) color and font settings for AppButtons block 2025-07-12 12:41:13 +03:00
eleksir
12f4dc75f0 Fix linter warnings 2025-06-24 16:13:36 +03:00
eleksir
913fcc34ee Fix incorrect display measurement units in swap calculation in mem plugin 2025-06-24 16:12:48 +03:00
eleksir
ac856f4174 Fix empty font name and incorrect font size name in VPN plugin output 2025-06-24 16:11:43 +03:00
eleksir
a5d793926b Fix typo in README.md 2025-06-01 18:59:15 +03:00
eleksir
40a94bd001 Add missing runcommand.go 2025-06-01 18:57:47 +03:00
eleksir
d19836b821 Update README.md 2025-05-19 12:27:56 +03:00
eleksir
32d865e24e Implement cmdrun config parameter 2025-05-19 12:19:25 +03:00
eleksir
757fb5e57e Add sysfs method to get battery charge for linux 2025-04-24 20:42:32 +03:00
eleksir
6b81991ebb Add small delay in spawner 2025-04-24 18:38:19 +03:00
eleksir
95a5033dfc Use any instead of interface{} 2025-04-07 20:50:49 +03:00
eleksir
30cb930a5e Update deps 2025-04-07 20:41:57 +03:00
eleksir
4fd0815c1d Use tickers instead of time.Sleep(), simplify main loop condition 2025-04-07 20:41:13 +03:00
eleksir
44dbaee87a Fix more golangci-lint warnings and update its config, bump required version of go compiler to 1.24.2 2025-04-07 20:14:14 +03:00
eleksir
f905ba79a3 Fix "no batt" case, when one of the batteries have dodgy driver 2025-04-07 19:52:41 +03:00
121 changed files with 5670 additions and 3424 deletions

View File

@@ -1,28 +1,12 @@
version: "2"
run: run:
tests: false go: "1.24"
skip-dirs:
- data
- vendor
modules-download-mode: readonly modules-download-mode: readonly
tests: false
allow-parallel-runners: true allow-parallel-runners: true
go: '1.21'
output:
sort-results: true
linters-settings:
gosec:
excludes:
# not relevant here
- G404 # Insecure random number source (rand)
- G306 # Expect WriteFile permissions to be 0600 or less (gosec)
linters: linters:
disable-all: true default: none
enable: enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- unused
- asasalint - asasalint
- asciicheck - asciicheck
- bodyclose - bodyclose
@@ -30,23 +14,29 @@ linters:
- contextcheck - contextcheck
- decorder - decorder
- durationcheck - durationcheck
- errcheck
- errchkjson - errchkjson
- errorlint - errorlint
- exportloopref - exptostd
- ginkgolinter - ginkgolinter
- gocheckcompilerdirectives - gocheckcompilerdirectives
- gocritic - gocritic
- godoclint
- godot - godot
- goerr113 - godox
- gofmt - goprintffuncname
- goimports
- gosec - gosec
- gosmopolitan - gosmopolitan
- govet
- grouper - grouper
- importas - importas
- ineffassign
- intrange
- ireturn - ireturn
- makezero - makezero
- mirror - mirror
- misspell
- modernize
- nakedret - nakedret
- nilerr - nilerr
- nilnil - nilnil
@@ -54,13 +44,758 @@ linters:
- noctx - noctx
- nolintlint - nolintlint
- nonamedreturns - nonamedreturns
- perfsprint
- predeclared - predeclared
- promlinter - promlinter
- reassign - reassign
- revive - revive
- rowserrcheck - rowserrcheck
- stylecheck - staticcheck
- unconvert - unconvert
- unused
- usestdlibvars
- wastedassign - wastedassign
- whitespace - wsl_v5
- wsl settings:
decorder:
dec-order:
- type
- const
- var
- func
gocritic:
disable-all: false
enable-all: true
disabled-checks:
- singleCaseSwitch
- octalLiteral
- regexpSimplify
- paramTypeCombine
- whyNoLint
- hugeParam
godoclint:
default: all
ignore-unexported: false
ignore-exported: false
include-unexported: true
disable:
- max-len
godot:
scope: all
exclude:
# Exclude todo and fixme comments.
- "^fixme:"
- "^todo:"
period: true
capital: false
godox:
keywords:
- FIXME
gosec: # go-fucking-sic
excludes:
# Боже, как же вы затрахали своей крипто-ебучкой, наркоманы хреновы!
- G405 # Detect the usage of DES or RC4
- G406 # Detect the usage of MD4 or RIPEMD160
# Оно не используется для повышения безопасности или каких-то таких секъюрных вещей, оно используется для выборки
# произвольного элемента из массива, так что ИДИ НАХУЙ с этой проверкой и не еби мозги липовой безопасностью.
- G404 # Insecure random number source (rand)
- G501 # Import blocklist: crypto/md5
- G502 # Import blocklist: crypto/des
- G503 # Import blocklist: crypto/rc4
- G504 # Import blocklist: net/http/cgi
- G505 # Import blocklist: crypto/sha1
- G506 # Import blocklist: golang.org/x/crypto/md4
- G507 # Import blocklist: golang.org/x/crypto/ripemd160
config:
global:
audit: true
# Ваша сраная паранойя при создании файлов и каталогов мешает нормальной работе сервисов. Группы придуманы для
# удобства, группе удобно давать право чтения. Поэтому идите нахуй со своими ограничениями на чтение для
# группы, "безопасные" клоуны.
G301: "0755"
G306: "0644"
govet:
disable-all: false
enable-all: true
disable:
- shadow
- fieldalignment
grouper:
# Require the use of a single global 'const' declaration only.
# Default: false
const-require-single-const: true
# Require the use of grouped global 'const' declarations.
# Default: false
const-require-grouping: true
# Require the use of a single 'import' declaration only.
# Default: false
import-require-single-import: true
# Require the use of grouped 'import' declarations.
# Default: false
import-require-grouping: true
# Require the use of a single global 'type' declaration only.
# Default: false
type-require-single-type: true
# Require the use of grouped global 'type' declarations.
# Default: false
type-require-grouping: true
# Require the use of a single global 'var' declaration only.
# Default: false
var-require-single-var: true
# Require the use of grouped global 'var' declarations.
# Default: false
var-require-grouping: true
misspell:
# Correct spellings using locale preferences for US or UK.
# Setting locale to US will correct the British spelling of 'colour' to 'color'.
# Default is to use a neutral variety of English.
locale: US
# Typos to ignore.
# Should be in lower case.
# Default: []
ignore-rules:
- someword
# Extra word corrections.
# `typo` and `correction` should only contain letters.
# The words are case-insensitive.
# Default: []
extra-words:
- typo: "iff"
correction: "if"
- typo: "cancelation"
correction: "cancellation"
# Mode of the analysis:
# - default: checks all the file content.
# - restricted: checks only comments.
# Default: ""
mode: restricted
nonamedreturns:
# Report named error if it is assigned inside defer.
# Default: false
report-error-in-defer: true
perfsprint:
integer-format: true
int-conversion: true
error-format: true
err-error: false
errorf: true
string-format: true
sprintf1: true
strconcat: true
bool-format: true
hex-format: true
concat-loop: true
loop-other-ops: false
revive:
enable-all-rules: false
staticcheck:
# https://staticcheck.dev/docs/configuration/options/#dot_import_whitelist
# Default: ["github.com/mmcloughlin/avo/build", "github.com/mmcloughlin/avo/operand", "github.com/mmcloughlin/avo/reg"]
dot-import-whitelist:
- fmt
# https://staticcheck.dev/docs/configuration/options/#initialisms
# Default: ["ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "QPS", "RAM", "RPC", "SLA", "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "GID", "UID", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS", "SIP", "RTP", "AMQP", "DB", "TS"]
initialisms:
[
"ACL",
"API",
"ASCII",
"CPU",
"CSS",
"DNS",
"EOF",
"GUID",
"HTML",
"HTTP",
"HTTPS",
"ID",
"IP",
"JSON",
"QPS",
"RAM",
"RPC",
"SLA",
"SMTP",
"SQL",
"SSH",
"TCP",
"TLS",
"TTL",
"UDP",
"UI",
"GID",
"UID",
"UUID",
"URI",
"URL",
"UTF8",
"VM",
"XML",
"XMPP",
"XSRF",
"XSS",
"SIP",
"RTP",
"AMQP",
"DB",
"TS",
]
# https://staticcheck.dev/docs/configuration/options/#http_status_code_whitelist
# Default: ["200", "400", "404", "500"]
http-status-code-whitelist: ["200", "400", "404", "500"]
# SAxxxx checks in https://staticcheck.dev/docs/configuration/options/#checks
# Example (to disable some checks): [ "all", "-SA1000", "-SA1001"]
# Run `GL_DEBUG=staticcheck golangci-lint run --enable=staticcheck` to see all available checks and enabled by config checks.
# Default: ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1020", "-ST1021", "-ST1022"]
checks:
# Invalid regular expression.
# https://staticcheck.dev/docs/checks/#SA1000
- SA1000
# Invalid template.
# https://staticcheck.dev/docs/checks/#SA1001
- SA1001
# Invalid format in 'time.Parse'.
# https://staticcheck.dev/docs/checks/#SA1002
- SA1002
# Unsupported argument to functions in 'encoding/binary'.
# https://staticcheck.dev/docs/checks/#SA1003
- SA1003
# Suspiciously small untyped constant in 'time.Sleep'.
# https://staticcheck.dev/docs/checks/#SA1004
- SA1004
# Invalid first argument to 'exec.Command'.
# https://staticcheck.dev/docs/checks/#SA1005
- SA1005
# 'Printf' with dynamic first argument and no further arguments.
# https://staticcheck.dev/docs/checks/#SA1006
- SA1006
# Invalid URL in 'net/url.Parse'.
# https://staticcheck.dev/docs/checks/#SA1007
- SA1007
# Non-canonical key in 'http.Header' map.
# https://staticcheck.dev/docs/checks/#SA1008
- SA1008
# '(*regexp.Regexp).FindAll' called with 'n == 0', which will always return zero results.
# https://staticcheck.dev/docs/checks/#SA1010
- SA1010
# Various methods in the "strings" package expect valid UTF-8, but invalid input is provided.
# https://staticcheck.dev/docs/checks/#SA1011
- SA1011
# A nil 'context.Context' is being passed to a function, consider using 'context.TODO' instead.
# https://staticcheck.dev/docs/checks/#SA1012
- SA1012
# 'io.Seeker.Seek' is being called with the whence constant as the first argument, but it should be the second.
# https://staticcheck.dev/docs/checks/#SA1013
- SA1013
# Non-pointer value passed to 'Unmarshal' or 'Decode'.
# https://staticcheck.dev/docs/checks/#SA1014
- SA1014
# Using 'time.Tick' in a way that will leak. Consider using 'time.NewTicker', and only use 'time.Tick' in tests, commands and endless functions.
# https://staticcheck.dev/docs/checks/#SA1015
- SA1015
# Trapping a signal that cannot be trapped.
# https://staticcheck.dev/docs/checks/#SA1016
- SA1016
# Channels used with 'os/signal.Notify' should be buffered.
# https://staticcheck.dev/docs/checks/#SA1017
- SA1017
# 'strings.Replace' called with 'n == 0', which does nothing.
# https://staticcheck.dev/docs/checks/#SA1018
- SA1018
# Using a deprecated function, variable, constant or field.
# https://staticcheck.dev/docs/checks/#SA1019
- SA1019
# Using an invalid host:port pair with a 'net.Listen'-related function.
# https://staticcheck.dev/docs/checks/#SA1020
- SA1020
# Using 'bytes.Equal' to compare two 'net.IP'.
# https://staticcheck.dev/docs/checks/#SA1021
- SA1021
# Modifying the buffer in an 'io.Writer' implementation.
# https://staticcheck.dev/docs/checks/#SA1023
- SA1023
# A string cutset contains duplicate characters.
# https://staticcheck.dev/docs/checks/#SA1024
- SA1024
# It is not possible to use '(*time.Timer).Reset''s return value correctly.
# https://staticcheck.dev/docs/checks/#SA1025
- SA1025
# Cannot marshal channels or functions.
# https://staticcheck.dev/docs/checks/#SA1026
- SA1026
# Atomic access to 64-bit variable must be 64-bit aligned.
# https://staticcheck.dev/docs/checks/#SA1027
- SA1027
# 'sort.Slice' can only be used on slices.
# https://staticcheck.dev/docs/checks/#SA1028
- SA1028
# Inappropriate key in call to 'context.WithValue'.
# https://staticcheck.dev/docs/checks/#SA1029
- SA1029
# Invalid argument in call to a 'strconv' function.
# https://staticcheck.dev/docs/checks/#SA1030
- SA1030
# Overlapping byte slices passed to an encoder.
# https://staticcheck.dev/docs/checks/#SA1031
- SA1031
# Wrong order of arguments to 'errors.Is'.
# https://staticcheck.dev/docs/checks/#SA1032
- SA1032
# 'sync.WaitGroup.Add' called inside the goroutine, leading to a race condition.
# https://staticcheck.dev/docs/checks/#SA2000
- SA2000
# Empty critical section, did you mean to defer the unlock?.
# https://staticcheck.dev/docs/checks/#SA2001
- SA2001
# Called 'testing.T.FailNow' or 'SkipNow' in a goroutine, which isn't allowed.
# https://staticcheck.dev/docs/checks/#SA2002
- SA2002
# Deferred 'Lock' right after locking, likely meant to defer 'Unlock' instead.
# https://staticcheck.dev/docs/checks/#SA2003
- SA2003
# 'TestMain' doesn't call 'os.Exit', hiding test failures.
# https://staticcheck.dev/docs/checks/#SA3000
- SA3000
# Assigning to 'b.N' in benchmarks distorts the results.
# https://staticcheck.dev/docs/checks/#SA3001
- SA3001
# Binary operator has identical expressions on both sides.
# https://staticcheck.dev/docs/checks/#SA4000
- SA4000
# '&*x' gets simplified to 'x', it does not copy 'x'.
# https://staticcheck.dev/docs/checks/#SA4001
- SA4001
# Comparing unsigned values against negative values is pointless.
# https://staticcheck.dev/docs/checks/#SA4003
- SA4003
# The loop exits unconditionally after one iteration.
# https://staticcheck.dev/docs/checks/#SA4004
- SA4004
# Field assignment that will never be observed. Did you mean to use a pointer receiver?.
# https://staticcheck.dev/docs/checks/#SA4005
- SA4005
# A value assigned to a variable is never read before being overwritten. Forgotten error check or dead code?.
# https://staticcheck.dev/docs/checks/#SA4006
- SA4006
# The variable in the loop condition never changes, are you incrementing the wrong variable?.
# https://staticcheck.dev/docs/checks/#SA4008
- SA4008
# A function argument is overwritten before its first use.
# https://staticcheck.dev/docs/checks/#SA4009
- SA4009
# The result of 'append' will never be observed anywhere.
# https://staticcheck.dev/docs/checks/#SA4010
- SA4010
# Break statement with no effect. Did you mean to break out of an outer loop?.
# https://staticcheck.dev/docs/checks/#SA4011
- SA4011
# Comparing a value against NaN even though no value is equal to NaN.
# https://staticcheck.dev/docs/checks/#SA4012
- SA4012
# Negating a boolean twice ('!!b') is the same as writing 'b'. This is either redundant, or a typo.
# https://staticcheck.dev/docs/checks/#SA4013
- SA4013
# An if/else if chain has repeated conditions and no side-effects; if the condition didn't match the first time, it won't match the second time, either.
# https://staticcheck.dev/docs/checks/#SA4014
- SA4014
# Calling functions like 'math.Ceil' on floats converted from integers doesn't do anything useful.
# https://staticcheck.dev/docs/checks/#SA4015
- SA4015
# Certain bitwise operations, such as 'x ^ 0', do not do anything useful.
# https://staticcheck.dev/docs/checks/#SA4016
- SA4016
# Discarding the return values of a function without side effects, making the call pointless.
# https://staticcheck.dev/docs/checks/#SA4017
- SA4017
# Self-assignment of variables.
# https://staticcheck.dev/docs/checks/#SA4018
- SA4018
# Multiple, identical build constraints in the same file.
# https://staticcheck.dev/docs/checks/#SA4019
- SA4019
# Unreachable case clause in a type switch.
# https://staticcheck.dev/docs/checks/#SA4020
- SA4020
# "x = append(y)" is equivalent to "x = y".
# https://staticcheck.dev/docs/checks/#SA4021
- SA4021
# Comparing the address of a variable against nil.
# https://staticcheck.dev/docs/checks/#SA4022
- SA4022
# Impossible comparison of interface value with untyped nil.
# https://staticcheck.dev/docs/checks/#SA4023
- SA4023
# Checking for impossible return value from a builtin function.
# https://staticcheck.dev/docs/checks/#SA4024
- SA4024
# Integer division of literals that results in zero.
# https://staticcheck.dev/docs/checks/#SA4025
- SA4025
# Go constants cannot express negative zero.
# https://staticcheck.dev/docs/checks/#SA4026
- SA4026
# '(*net/url.URL).Query' returns a copy, modifying it doesn't change the URL.
# https://staticcheck.dev/docs/checks/#SA4027
- SA4027
# 'x % 1' is always zero.
# https://staticcheck.dev/docs/checks/#SA4028
- SA4028
# Ineffective attempt at sorting slice.
# https://staticcheck.dev/docs/checks/#SA4029
- SA4029
# Ineffective attempt at generating random number.
# https://staticcheck.dev/docs/checks/#SA4030
- SA4030
# Checking never-nil value against nil.
# https://staticcheck.dev/docs/checks/#SA4031
- SA4031
# Comparing 'runtime.GOOS' or 'runtime.GOARCH' against impossible value.
# https://staticcheck.dev/docs/checks/#SA4032
- SA4032
# Assignment to nil map.
# https://staticcheck.dev/docs/checks/#SA5000
- SA5000
# Deferring 'Close' before checking for a possible error.
# https://staticcheck.dev/docs/checks/#SA5001
- SA5001
# The empty for loop ("for {}") spins and can block the scheduler.
# https://staticcheck.dev/docs/checks/#SA5002
- SA5002
# Defers in infinite loops will never execute.
# https://staticcheck.dev/docs/checks/#SA5003
- SA5003
# "for { select { ..." with an empty default branch spins.
# https://staticcheck.dev/docs/checks/#SA5004
- SA5004
# The finalizer references the finalized object, preventing garbage collection.
# https://staticcheck.dev/docs/checks/#SA5005
- SA5005
# Infinite recursive call.
# https://staticcheck.dev/docs/checks/#SA5007
- SA5007
# Invalid struct tag.
# https://staticcheck.dev/docs/checks/#SA5008
- SA5008
# Invalid Printf call.
# https://staticcheck.dev/docs/checks/#SA5009
- SA5009
# Impossible type assertion.
# https://staticcheck.dev/docs/checks/#SA5010
- SA5010
# Possible nil pointer dereference.
# https://staticcheck.dev/docs/checks/#SA5011
- SA5011
# Passing odd-sized slice to function expecting even size.
# https://staticcheck.dev/docs/checks/#SA5012
- SA5012
# Using 'regexp.Match' or related in a loop, should use 'regexp.Compile'.
# https://staticcheck.dev/docs/checks/#SA6000
- SA6000
# Missing an optimization opportunity when indexing maps by byte slices.
# https://staticcheck.dev/docs/checks/#SA6001
- SA6001
# Storing non-pointer values in 'sync.Pool' allocates memory.
# https://staticcheck.dev/docs/checks/#SA6002
- SA6002
# Converting a string to a slice of runes before ranging over it.
# https://staticcheck.dev/docs/checks/#SA6003
- SA6003
# Inefficient string comparison with 'strings.ToLower' or 'strings.ToUpper'.
# https://staticcheck.dev/docs/checks/#SA6005
- SA6005
# Using io.WriteString to write '[]byte'.
# https://staticcheck.dev/docs/checks/#SA6006
- SA6006
# Defers in range loops may not run when you expect them to.
# https://staticcheck.dev/docs/checks/#SA9001
- SA9001
# Using a non-octal 'os.FileMode' that looks like it was meant to be in octal.
# https://staticcheck.dev/docs/checks/#SA9002
- SA9002
# Empty body in an if or else branch.
# https://staticcheck.dev/docs/checks/#SA9003
- SA9003
# Only the first constant has an explicit type.
# https://staticcheck.dev/docs/checks/#SA9004
- SA9004
# Trying to marshal a struct with no public fields nor custom marshaling.
# https://staticcheck.dev/docs/checks/#SA9005
- SA9005
# Dubious bit shifting of a fixed size integer value.
# https://staticcheck.dev/docs/checks/#SA9006
- SA9006
# Deleting a directory that shouldn't be deleted.
# https://staticcheck.dev/docs/checks/#SA9007
- SA9007
# 'else' branch of a type assertion is probably not reading the right value.
# https://staticcheck.dev/docs/checks/#SA9008
- SA9008
# Ineffectual Go compiler directive.
# https://staticcheck.dev/docs/checks/#SA9009
- SA9009
# Incorrect or missing package comment.
# https://staticcheck.dev/docs/checks/#ST1000
- ST1000
# Dot imports are discouraged.
# https://staticcheck.dev/docs/checks/#ST1001
- ST1001
# Poorly chosen identifier.
# https://staticcheck.dev/docs/checks/#ST1003
- ST1003
# Incorrectly formatted error string.
# https://staticcheck.dev/docs/checks/#ST1005
- ST1005
# Poorly chosen receiver name.
# https://staticcheck.dev/docs/checks/#ST1006
- ST1006
# A function's error value should be its last return value.
# https://staticcheck.dev/docs/checks/#ST1008
- ST1008
# Poorly chosen name for variable of type 'time.Duration'.
# https://staticcheck.dev/docs/checks/#ST1011
- ST1011
# Poorly chosen name for error variable.
# https://staticcheck.dev/docs/checks/#ST1012
- ST1012
# Should use constants for HTTP error codes, not magic numbers.
# https://staticcheck.dev/docs/checks/#ST1013
- ST1013
# A switch's default case should be the first or last case.
# https://staticcheck.dev/docs/checks/#ST1015
- ST1015
# Use consistent method receiver names.
# https://staticcheck.dev/docs/checks/#ST1016
- ST1016
# Don't use Yoda conditions.
# https://staticcheck.dev/docs/checks/#ST1017
- ST1017
# Avoid zero-width and control characters in string literals.
# https://staticcheck.dev/docs/checks/#ST1018
- ST1018
# Importing the same package multiple times.
# https://staticcheck.dev/docs/checks/#ST1019
- ST1019
# The documentation of an exported function should start with the function's name.
# https://staticcheck.dev/docs/checks/#ST1020
- ST1020
# The documentation of an exported type should start with type's name.
# https://staticcheck.dev/docs/checks/#ST1021
- ST1021
# The documentation of an exported variable or constant should start with variable's name.
# https://staticcheck.dev/docs/checks/#ST1022
- ST1022
# Redundant type in variable declaration.
# https://staticcheck.dev/docs/checks/#ST1023
- ST1023
# Use plain channel send or receive instead of single-case select.
# https://staticcheck.dev/docs/checks/#S1000
- S1000
# Replace for loop with call to copy.
# https://staticcheck.dev/docs/checks/#S1001
- S1001
# Omit comparison with boolean constant.
# https://staticcheck.dev/docs/checks/#S1002
- S1002
# Replace call to 'strings.Index' with 'strings.Contains'.
# https://staticcheck.dev/docs/checks/#S1003
- S1003
# Replace call to 'bytes.Compare' with 'bytes.Equal'.
# https://staticcheck.dev/docs/checks/#S1004
- S1004
# Drop unnecessary use of the blank identifier.
# https://staticcheck.dev/docs/checks/#S1005
- S1005
# Use "for { ... }" for infinite loops.
# https://staticcheck.dev/docs/checks/#S1006
- S1006
# Simplify regular expression by using raw string literal.
# https://staticcheck.dev/docs/checks/#S1007
- S1007
# Simplify returning boolean expression.
# https://staticcheck.dev/docs/checks/#S1008
- S1008
# Omit redundant nil check on slices, maps, and channels.
# https://staticcheck.dev/docs/checks/#S1009
- S1009
# Omit default slice index.
# https://staticcheck.dev/docs/checks/#S1010
- S1010
# Use a single 'append' to concatenate two slices.
# https://staticcheck.dev/docs/checks/#S1011
- S1011
# Replace 'time.Now().Sub(x)' with 'time.Since(x)'.
# https://staticcheck.dev/docs/checks/#S1012
- S1012
# Use a type conversion instead of manually copying struct fields.
# https://staticcheck.dev/docs/checks/#S1016
- S1016
# Replace manual trimming with 'strings.TrimPrefix'.
# https://staticcheck.dev/docs/checks/#S1017
- S1017
# Use "copy" for sliding elements.
# https://staticcheck.dev/docs/checks/#S1018
- S1018
# Simplify "make" call by omitting redundant arguments.
# https://staticcheck.dev/docs/checks/#S1019
- S1019
# Omit redundant nil check in type assertion.
# https://staticcheck.dev/docs/checks/#S1020
- S1020
# Merge variable declaration and assignment.
# https://staticcheck.dev/docs/checks/#S1021
- S1021
# Omit redundant control flow.
# https://staticcheck.dev/docs/checks/#S1023
- S1023
# Replace 'x.Sub(time.Now())' with 'time.Until(x)'.
# https://staticcheck.dev/docs/checks/#S1024
- S1024
# Don't use 'fmt.Sprintf("%s", x)' unnecessarily.
# https://staticcheck.dev/docs/checks/#S1025
- S1025
# Simplify error construction with 'fmt.Errorf'.
# https://staticcheck.dev/docs/checks/#S1028
- S1028
# Range over the string directly.
# https://staticcheck.dev/docs/checks/#S1029
- S1029
# Use 'bytes.Buffer.String' or 'bytes.Buffer.Bytes'.
# https://staticcheck.dev/docs/checks/#S1030
- S1030
# Omit redundant nil check around loop.
# https://staticcheck.dev/docs/checks/#S1031
- S1031
# Use 'sort.Ints(x)', 'sort.Float64s(x)', and 'sort.Strings(x)'.
# https://staticcheck.dev/docs/checks/#S1032
- S1032
# Unnecessary guard around call to "delete".
# https://staticcheck.dev/docs/checks/#S1033
- S1033
# Use result of type assertion to simplify cases.
# https://staticcheck.dev/docs/checks/#S1034
- S1034
# Redundant call to 'net/http.CanonicalHeaderKey' in method call on 'net/http.Header'.
# https://staticcheck.dev/docs/checks/#S1035
- S1035
# Unnecessary guard around map access.
# https://staticcheck.dev/docs/checks/#S1036
- S1036
# Elaborate way of sleeping.
# https://staticcheck.dev/docs/checks/#S1037
- S1037
# Unnecessarily complex way of printing formatted string.
# https://staticcheck.dev/docs/checks/#S1038
- S1038
# Unnecessary use of 'fmt.Sprint'.
# https://staticcheck.dev/docs/checks/#S1039
- S1039
# Type assertion to current type.
# https://staticcheck.dev/docs/checks/#S1040
- S1040
# Apply De Morgan's law.
# https://staticcheck.dev/docs/checks/#QF1001
- QF1001
# Convert untagged switch to tagged switch.
# https://staticcheck.dev/docs/checks/#QF1002
- QF1002
# Convert if/else-if chain to tagged switch.
# https://staticcheck.dev/docs/checks/#QF1003
- QF1003
# Use 'strings.ReplaceAll' instead of 'strings.Replace' with 'n == -1'.
# https://staticcheck.dev/docs/checks/#QF1004
- QF1004
# Expand call to 'math.Pow'.
# https://staticcheck.dev/docs/checks/#QF1005
- QF1005
# Lift 'if'+'break' into loop condition.
# https://staticcheck.dev/docs/checks/#QF1006
- QF1006
# Merge conditional assignment into variable declaration.
# https://staticcheck.dev/docs/checks/#QF1007
- QF1007
# Omit embedded fields from selector expression.
# https://staticcheck.dev/docs/checks/#QF1008
- QF1008
# Use 'time.Time.Equal' instead of '==' operator.
# https://staticcheck.dev/docs/checks/#QF1009
- QF1009
# Convert slice of bytes to string when printing it.
# https://staticcheck.dev/docs/checks/#QF1010
- QF1010
# Omit redundant type from variable declaration.
# https://staticcheck.dev/docs/checks/#QF1011
- QF1011
# Use 'fmt.Fprintf(x, ...)' instead of 'x.Write(fmt.Sprintf(...))'.
# https://staticcheck.dev/docs/checks/#QF1012
- QF1012
unconvert:
# Remove conversions that force intermediate rounding.
# Default: false
fast-math: true
# Be more conservative (experimental).
# Default: false
safe: true
usestdlibvars:
# Suggest the use of http.MethodXX.
# Default: true
http-method: false
# Suggest the use of http.StatusXX.
# Default: true
http-status-code: false
# Suggest the use of time.Month in time.Date.
# Default: false
time-date-month: true
# Suggest the use of time.Weekday.String().
# Default: true
time-weekday: true
# Suggest the use of time.Month.String().
# Default: false
time-month: true
# Suggest the use of time.Layout.
# Default: false
time-layout: true
# Suggest the use of crypto.Hash.String().
# Default: false
crypto-hash: true
# Suggest the use of rpc.DefaultXXPath.
# Default: false
default-rpc-path: true
# Suggest the use of sql.LevelXX.String().
# Default: false
sql-isolation-level: true
# Suggest the use of tls.SignatureScheme.String().
# Default: false
tls-signature-scheme: true
# Suggest the use of constant.Kind.String().
# Default: false
constant-kind: true
wsl_v5:
allow-first-in-block: true
allow-whole-block: true
branch-max-lines: 2
case-max-lines: 2
default: all
disable:
- if
- err
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
paths:
- third_party$
- builtin$
- examples$
formatters:
enable:
- gofmt
- goimports
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$

View File

@@ -1,9 +1,10 @@
#!/usr/bin/env gmake -f #!/usr/bin/env gmake -f
BUILDOPTS=-ldflags="-s -w" -a -gcflags=all=-l -trimpath BUILDOPTS=-ldflags="-s -w" -a -gcflags=all=-l -trimpath -buildvcs=false
BINARY=i3status-go BINARY=i3status-go
TEST1=battery-test TEST1=battery-test
TEST2=cmdrun-test
## Use calssic targets where first one is deafult target ## Use calssic targets where first one is deafult target
all: clean build all: clean build
@@ -13,17 +14,21 @@ build:
go build ${BUILDOPTS} -o ${BINARY} ./cmd/${BINARY} go build ${BUILDOPTS} -o ${BINARY} ./cmd/${BINARY}
battery-test: battery-test:
rm -rf ${TEST1}
go build ${BUILDOPTS} -o ${TEST1} ./cmd/${TEST1} go build ${BUILDOPTS} -o ${TEST1} ./cmd/${TEST1}
cmdrun-test:
rm -rf ${TEST1}
go build ${BUILDOPTS} -o ${TEST2} ./cmd/${TEST2}
## Remove binary with golang compiler' means ## Remove binary with golang compiler' means
clean: clean:
rm -rf ${BINARY} ${TEST1} rm -rf ${BINARY} ${TEST1} ${TEST2}
## Misc target, for development purposes. Updates vendored libs, brutal way. ## Misc target, for development purposes. Updates vendored libs, brutal way.
upgrade: upgrade:
$(RM) -r vendor $(RM) -r vendor
go get -d -u -t ./... go get -u -t ./...
go mod tidy go mod tidy
go mod vendor go mod vendor

View File

@@ -14,11 +14,12 @@ It is i3bar text generator.
* PulseAudio volume indicator, can adjust master volume too * PulseAudio volume indicator, can adjust master volume too
* Clock * Clock
* Cron jobs (intended to use for show periodic desktop notifications but not limited to) * Cron jobs (intended to use for show periodic desktop notifications but not limited to)
* Show output of one-shot system command
## How to build it ## How to build it
This appliction was tested to compile with go v1.21 but can be built with earlier versions (seems down to 1.18, not This application was tested to compile with go v1.24.
sure).
All you need is go lang compiler and gnu make utility. Invoke All you need is go lang compiler and gnu make utility. Invoke
```bash ```bash

View File

@@ -1,3 +1,4 @@
// Package main simple test for battery funtionality.
package main package main
import ( import (
@@ -11,13 +12,14 @@ import (
// Program entry point. // Program entry point.
func main() { func main() {
for { for {
batteries, err := battery.GetAll() batteries, _ := battery.GetAll()
if err != nil { for index, battery := range batteries {
fmt.Printf("Unable to get battery info: %w", err) fmt.Printf("Battery %d: %s\n", index, spew.Sdump(battery))
} }
spew.Dump(batteries)
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
} }
} }
/* vim: set ft=go noet ai ts=4 sw=4 sts=4: */

View File

@@ -2,7 +2,7 @@
// Default text and *block* border colors. If not set #3e78fd is used. // Default text and *block* border colors. If not set #3e78fd is used.
"color" : "#3e78fd", "color" : "#3e78fd",
// Default backbround color. If not set value of #edeceb is used. // Default background color. If not set value of #edeceb is used.
"background" : "#000000", "background" : "#000000",
// Can be omitted, then Liberation Mono will be used. // Can be omitted, then Liberation Mono will be used.
@@ -518,6 +518,15 @@
"battery": { "battery": {
"enabled": false, "enabled": false,
// Valid only on linux, where we have mounted sysfs and /sys/class/power_supply/BAT0/capacity available
"use_sysfs": false,
// it is possible to set files here, if none set, /sys/class/power_supply/BAT0/capacity will be taken.
"sysfs_files": [
"/sys/class/power_supply/BAT0/capacity",
"/sys/class/power_supply/HIDP0/capacity"
],
// If omitted set to default color defined up here. // If omitted set to default color defined up here.
"color": "#3e78fd", "color": "#3e78fd",
@@ -693,10 +702,95 @@
] ]
}, },
// Prints stdout of command to panel.
"cmdrun" : {
"enabled": false,
// Delay between two consecutive command batch runs.
"delay": 3,
// command' binary.
"cmd": "/bin/bash",
// Arguments for command binary.
"args": ["-c", "echo 42"],
// If omitted set to default color defined up here.
"color": "#3e78fd",
// If omitted set to default background color defined up here.
"background": "#000000",
// If omitted set to default font defined up here.
"font": "Noto Sans",
// ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’, or one of relative sizes
// ‘smaller’ or ‘larger’. If omitted set to default font size defined up here.
"font_size": "medium",
// Re-define separator parameters for each command block here.
"separator": {
"left": {
// Set to false if omitted.
"enabled": true,
// If omitted set to default color defined for separator up here.
"color": "#3e78fd",
// If omitted set to default background color defined for separator up here.
"background": "#000000",
// If omitted set to default symbol defined for separator up here.
"symbol": "▶",
// If omitted set to default font defined for separator up here.
"font": "Noto Sans",
// ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’, or one of relative sizes
// ‘smaller’ or ‘larger’. If omitted set to default font size defined for separator up here.
"font_size": "medium"
},
"right": {
// Set to false if omitted.
"enabled": true,
// If omitted set to default color defined for separator up here.
"color": "#3e78fd",
// If omitted set to default background color defined for separator up here.
"background": "#000000",
// If omitted set to default symbol defined for separator up here.
"symbol": "◀",
// If omitted set to default font defined for separator up here.
"font": "Noto Sans",
// ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’, or one of relative sizes
// ‘smaller’ or ‘larger’. If omitted set to default font size defined for separator up here.
"font_size": "medium"
}
}
}
// Whether to display Application Buttons. // Whether to display Application Buttons.
"app_buttons": { "app_buttons": {
"enabled": true, "enabled": true,
// If omitted set to default color defined up here.
"color": "#3e78fd",
// If omitted set to default background color defined up here.
"background": "#000000",
// If omitted set to default font defined up here.
"font": "Noto Sans",
// ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’, or one of relative sizes
// ‘smaller’ or ‘larger’. If omitted set to default font size defined up here.
"font_size": "medium",
// Re-define separator parameters for net-if block here. // Re-define separator parameters for net-if block here.
"separator": { "separator": {
"left": { "left": {
@@ -740,31 +834,36 @@
// ‘smaller’ or ‘larger’. If omitted set to default font size defined for separator up here. // ‘smaller’ or ‘larger’. If omitted set to default font size defined for separator up here.
"font_size": "medium" "font_size": "medium"
} }
}, }
}, },
// Buttons - application launch "buttons" // Buttons - application launch "buttons"
"apps": [ "apps": [
{ {
// Text dispalyed on button // Text displayed on button, pango markup supported.
"full_text" : "📂", "full_text" : "📂",
// Internal name, can be any string, but unique for each app button // Internal name, can be any string, but unique for each app button.
"name" : "thunar", "name" : "thunar",
// Command itself // Command itself.
"cmd" : "thunar", "cmd" : "thunar",
// Array of command args, optional // Array of command args, optional.
"args": [ "." ], "args": [ "." ],
// Regexp that match with Instance component of WM_CLASS(STRING) of xprop output // Regexp that match with Instance component of WM_CLASS(STRING) of xprop output.
"instance": "^thunar$", "instance": "^thunar$",
// Regexp that match with Class component of WM_CLASS(STRING) of xprop output // Regexp that match with Class component of WM_CLASS(STRING) of xprop output.
"class": "^Thunar$", "class": "^Thunar$",
// text color in html notation // Text color in html notation.
"color": "#ffa500", "color": "#ffa500",
// background color in html notation // background color in html notation.
"background" : "#000000", "background" : "#000000",
// border color in html notation // If omitted set to default font defined for app_buttons up here.
"font": "Noto Sans",
// ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’, or one of relative sizes
// ‘smaller’ or ‘larger’. If omitted set to default font size defined for app_buttons up here.
"font_size": "medium",
// Border color in html notation.
"border": "#666666", "border": "#666666",
// border color if there is at least one window with given Instance and/or Class exist // Border color if there is at least one window with given Instance and/or Class exist.
"border_active": "#3e78fd", "border_active": "#3e78fd",
// Vertical line between objects on bar - if omitted true value is assumed by i3bar, but we set it to false // Vertical line between objects on bar - if omitted true value is assumed by i3bar, but we set it to false
// in that case. It is limitation of golang json parser. // in that case. It is limitation of golang json parser.

View File

@@ -1,3 +1,4 @@
// Package main status string generator for i3bar.
package main package main
import ( import (
@@ -8,6 +9,7 @@ import (
"log" "log"
"os" "os"
"os/signal" "os/signal"
"strconv"
"strings" "strings"
"syscall" "syscall"
@@ -15,7 +17,7 @@ import (
) )
//go:embed default-config.json //go:embed default-config.json
var DefaultConfig []byte var DefaultConfig []byte //nolint: godoclint, grouper, nolintlint
// Program entry point. // Program entry point.
func main() { func main() {
@@ -42,15 +44,11 @@ func main() {
// Conf.Values.PA // Conf.Values.PA
Conf.Values.SoundVolume = "🔊:0%" Conf.Values.SoundVolume = "🔊:0%"
// TODO: Проставить дефолтные значения для глобальных переменных модулей. Conf.Values.BatteryString = "<span color='" + Conf.Battery.Color +
Conf.Values.BatteryString = fmt.Sprintf( "' background='" + Conf.Battery.Background +
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>", "' font='" + Conf.Battery.SymbolFont +
Conf.Battery.Color, "' size='" + Conf.Battery.SymbolFontSize +
Conf.Battery.Background, "'>" + Conf.Battery.Symbol + "</span>"
Conf.Battery.SymbolFont,
Conf.Battery.SymbolFontSize,
Conf.Battery.Symbol,
)
Conf.Values.BatteryString += fmt.Sprintf( Conf.Values.BatteryString += fmt.Sprintf(
"<span color='%s' background='%s' font='%s' size='%s'> ??%% •</span>", "<span color='%s' background='%s' font='%s' size='%s'> ??%% •</span>",
@@ -84,6 +82,14 @@ func main() {
Conf.Clock.FontSize, Conf.Clock.FontSize,
) )
Conf.Values.RunCommandOutput = fmt.Sprintf(
"<span color='%s' background='%s' font='%s' size='%s'>?</span>",
Conf.CmdRun.Color,
Conf.CmdRun.Background,
Conf.CmdRun.Font,
Conf.CmdRun.FontSize,
)
go Conf.Spawner() go Conf.Spawner()
go Conf.ParseStdin() go Conf.ParseStdin()
go Conf.CleanZombies() go Conf.CleanZombies()
@@ -96,6 +102,7 @@ func main() {
// Kick signal handler // Kick signal handler
go Conf.SigHandler() go Conf.SigHandler()
signal.Notify(Conf.Channels.SigChan, signal.Notify(Conf.Channels.SigChan,
syscall.SIGUSR1, syscall.SIGUSR1,
syscall.SIGUSR2, syscall.SIGUSR2,
@@ -143,6 +150,10 @@ func main() {
go Conf.UpdateVPNStatus() go Conf.UpdateVPNStatus()
} }
if Conf.CmdRun.Enabled {
go Conf.RunCommand()
}
/* /*
I3bar documentation pretends that message protocol must be valid json. In practice, we only have to print valid I3bar documentation pretends that message protocol must be valid json. In practice, we only have to print valid
header, empty json array and (potentially infinite) json lines (line that is valid json by itself) that is header, empty json array and (potentially infinite) json lines (line that is valid json by itself) that is
@@ -160,40 +171,16 @@ func main() {
fmt.Println("[ [],") fmt.Println("[ [],")
for { for range Conf.Channels.UpdateReady {
if <-Conf.Channels.UpdateReady {
// Actually build json struct, marshal it and print result // Actually build json struct, marshal it and print result
var j []lib.I3BarOutBlock var j []lib.I3BarOutBlock
// TODO: впилить для первого и последнего батона separator // TODO: впилить для первого и последнего батона separator
if Conf.AppButtons.Enabled { if Conf.AppButtons.Enabled {
for num, app := range Conf.Apps { for _, app := range Conf.Apps {
var b lib.I3BarOutBlock var b lib.I3BarOutBlock
if num == 0 {
b.FullText = fmt.Sprintf(
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>",
Conf.AppButtons.Separator.Left.Color,
Conf.AppButtons.Separator.Left.Background,
Conf.AppButtons.Separator.Left.Font,
Conf.AppButtons.Separator.Left.FontSize,
Conf.AppButtons.Separator.Left.Symbol,
)
}
b.FullText = app.FullText b.FullText = app.FullText
if num == len(Conf.Apps) {
b.FullText = fmt.Sprintf(
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>",
Conf.AppButtons.Separator.Right.Color,
Conf.AppButtons.Separator.Right.Background,
Conf.AppButtons.Separator.Right.Font,
Conf.AppButtons.Separator.Right.FontSize,
Conf.AppButtons.Separator.Right.Symbol,
)
}
b.Background = app.Background b.Background = app.Background
b.Color = app.Color b.Color = app.Color
b.Instance = app.Instance b.Instance = app.Instance
@@ -218,42 +205,55 @@ func main() {
} }
if Conf.CPUTemp.Enabled { if Conf.CPUTemp.Enabled {
var b lib.I3BarOutBlock var (
b lib.I3BarOutBlock
sb strings.Builder
)
b.Color = Conf.CPUTemp.Color b.Color = Conf.CPUTemp.Color
b.Background = Conf.CPUTemp.Background b.Background = Conf.CPUTemp.Background
if Conf.CPUTemp.Separator.Left.Enabled { if Conf.CPUTemp.Separator.Left.Enabled {
b.FullText = fmt.Sprintf( sb.WriteString("<span color='")
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>", sb.WriteString(Conf.CPUTemp.Separator.Left.Color)
Conf.CPUTemp.Separator.Left.Color, sb.WriteString("' background='")
Conf.CPUTemp.Separator.Left.Background, sb.WriteString(Conf.CPUTemp.Separator.Left.Background)
Conf.CPUTemp.Separator.Left.Font, sb.WriteString("' font='")
Conf.CPUTemp.Separator.Left.FontSize, sb.WriteString(Conf.CPUTemp.Separator.Left.Font)
Conf.CPUTemp.Separator.Left.Symbol, sb.WriteString("' size='")
) sb.WriteString(Conf.CPUTemp.Separator.Left.FontSize)
sb.WriteString("'>")
sb.WriteString(Conf.CPUTemp.Separator.Left.Symbol)
sb.WriteString("</span>")
} }
b.FullText += fmt.Sprintf( sb.WriteString("<span color='")
"<span color='%s' background='%s' font='%s' size='%s'>CPU: %d°</span>", sb.WriteString(Conf.CPUTemp.Color)
Conf.CPUTemp.Color, sb.WriteString("' background='")
Conf.CPUTemp.Background, sb.WriteString(Conf.CPUTemp.Background)
Conf.CPUTemp.Font, sb.WriteString("' font='")
Conf.CPUTemp.FontSize, sb.WriteString(Conf.CPUTemp.Font)
Conf.Values.CPUTemperature, sb.WriteString("' size='")
) sb.WriteString(Conf.CPUTemp.FontSize)
sb.WriteString("'>CPU: ")
sb.WriteString(strconv.FormatInt(Conf.Values.CPUTemperature, 10))
sb.WriteString("°</span>")
if Conf.CPUTemp.Separator.Right.Enabled { if Conf.CPUTemp.Separator.Right.Enabled {
b.FullText += fmt.Sprintf( sb.WriteString("<span color='")
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>", sb.WriteString(Conf.CPUTemp.Separator.Right.Color)
Conf.CPUTemp.Separator.Right.Color, sb.WriteString("' background='")
Conf.CPUTemp.Separator.Right.Background, sb.WriteString(Conf.CPUTemp.Separator.Right.Background)
Conf.CPUTemp.Separator.Right.Font, sb.WriteString("' font='")
Conf.CPUTemp.Separator.Right.FontSize, sb.WriteString(Conf.CPUTemp.Separator.Right.Font)
Conf.CPUTemp.Separator.Right.Symbol, sb.WriteString("' size='")
) sb.WriteString(Conf.CPUTemp.Separator.Right.FontSize)
sb.WriteString("'>")
sb.WriteString(Conf.CPUTemp.Separator.Right.Symbol)
sb.WriteString("</span>")
} }
b.FullText = sb.String()
b.Markup = "pango" b.Markup = "pango"
b.Separator = false b.Separator = false
@@ -261,56 +261,66 @@ func main() {
} }
if Conf.Mem.Enabled { if Conf.Mem.Enabled {
var b lib.I3BarOutBlock var (
b lib.I3BarOutBlock
sb strings.Builder
)
b.Color = Conf.Mem.Color b.Color = Conf.Mem.Color
b.Background = Conf.Mem.Background b.Background = Conf.Mem.Background
if Conf.Mem.Separator.Left.Enabled { if Conf.Mem.Separator.Left.Enabled {
b.FullText = fmt.Sprintf( sb.WriteString("<span color='")
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>", sb.WriteString(Conf.Mem.Separator.Left.Color)
Conf.Mem.Separator.Left.Color, sb.WriteString("' background='")
Conf.Mem.Separator.Left.Background, sb.WriteString(Conf.Mem.Separator.Left.Background)
Conf.Mem.Separator.Left.Font, sb.WriteString("' font='")
Conf.Mem.Separator.Left.FontSize, sb.WriteString(Conf.Mem.Separator.Left.Font)
Conf.Mem.Separator.Left.Symbol, sb.WriteString("' size='")
) sb.WriteString(Conf.Mem.Separator.Left.FontSize)
sb.WriteString("'>")
sb.WriteString(Conf.Mem.Separator.Left.Symbol)
sb.WriteString("</span>")
} }
sb.WriteString("<span color='")
sb.WriteString(Conf.Mem.Color)
sb.WriteString("' background='")
sb.WriteString(Conf.Mem.Background)
sb.WriteString("' font='")
sb.WriteString(Conf.Mem.Font)
sb.WriteString("' size='")
sb.WriteString(Conf.Mem.FontSize)
sb.WriteString("'>M:")
sb.WriteString(strconv.FormatUint(Conf.Values.Memory.Usedpct, 10))
sb.WriteString("% SHM:")
sb.WriteString(strconv.FormatUint(Conf.Values.Memory.Shared, 10))
if Conf.Mem.ShowSwap { if Conf.Mem.ShowSwap {
b.FullText += fmt.Sprintf( sb.WriteString("% SW:")
"<span color='%s' background='%s' font='%s' size='%s'>M:%d%% SHM:%dM SW:%dM</span>", sb.WriteString(strconv.FormatUint(Conf.Values.Memory.Swap, 10))
Conf.Mem.Color, sb.WriteString("M")
Conf.Mem.Background,
Conf.Mem.Font,
Conf.Mem.FontSize,
Conf.Values.Memory.Usedpct,
Conf.Values.Memory.Shared,
Conf.Values.Memory.Swap,
)
} else { } else {
b.FullText += fmt.Sprintf( sb.WriteString("%")
"<span color='%s' background='%s' font='%s' size='%s'>M:%d%% SHM:%dM</span>",
Conf.Mem.Color,
Conf.Mem.Background,
Conf.Mem.Font,
Conf.Mem.FontSize,
Conf.Values.Memory.Usedpct,
Conf.Values.Memory.Shared,
)
} }
sb.WriteString("</span>")
if Conf.Mem.Separator.Right.Enabled { if Conf.Mem.Separator.Right.Enabled {
b.FullText += fmt.Sprintf( sb.WriteString("<span color='")
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>", sb.WriteString(Conf.Mem.Separator.Right.Color)
Conf.Mem.Separator.Right.Color, sb.WriteString("' background='")
Conf.Mem.Separator.Right.Background, sb.WriteString(Conf.Mem.Separator.Right.Background)
Conf.Mem.Separator.Right.Font, sb.WriteString("' font='")
Conf.Mem.Separator.Right.FontSize, sb.WriteString(Conf.Mem.Separator.Right.Font)
Conf.Mem.Separator.Right.Symbol, sb.WriteString("' size='")
) sb.WriteString(Conf.Mem.Separator.Right.FontSize)
sb.WriteString("'>")
sb.WriteString(Conf.Mem.Separator.Right.Symbol)
sb.WriteString("</span>")
} }
b.FullText = sb.String()
b.Markup = "pango" b.Markup = "pango"
b.Separator = false b.Separator = false
@@ -318,42 +328,55 @@ func main() {
} }
if Conf.LA.Enabled { if Conf.LA.Enabled {
var b lib.I3BarOutBlock var (
b lib.I3BarOutBlock
sb strings.Builder
)
b.Color = Conf.LA.Color b.Color = Conf.LA.Color
b.Background = Conf.LA.Background b.Background = Conf.LA.Background
if Conf.LA.Separator.Left.Enabled { if Conf.LA.Separator.Left.Enabled {
b.FullText = fmt.Sprintf( sb.WriteString("<span color='")
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>", sb.WriteString(Conf.LA.Separator.Left.Color)
Conf.LA.Separator.Left.Color, sb.WriteString("' background='")
Conf.LA.Separator.Left.Background, sb.WriteString(Conf.LA.Separator.Left.Background)
Conf.LA.Separator.Left.Font, sb.WriteString("' font='")
Conf.LA.Separator.Left.FontSize, sb.WriteString(Conf.LA.Separator.Left.Font)
Conf.LA.Separator.Left.Symbol, sb.WriteString("' size='")
) sb.WriteString(Conf.LA.Separator.Left.FontSize)
sb.WriteString("'>")
sb.WriteString(Conf.LA.Separator.Left.Symbol)
sb.WriteString("</span>")
} }
b.FullText += fmt.Sprintf( sb.WriteString("<span color='")
"<span color='%s' background='%s' font='%s' size='%s'>LA:%s</span>", sb.WriteString(Conf.LA.Color)
Conf.LA.Color, sb.WriteString("' background='")
Conf.LA.Background, sb.WriteString(Conf.LA.Background)
Conf.LA.Font, sb.WriteString("' font='")
Conf.LA.FontSize, sb.WriteString(Conf.LA.Font)
Conf.Values.La, sb.WriteString("' size='")
) sb.WriteString(Conf.LA.FontSize)
sb.WriteString("'>LA:")
sb.WriteString(Conf.Values.La)
sb.WriteString("</span>")
if Conf.LA.Separator.Right.Enabled { if Conf.LA.Separator.Right.Enabled {
b.FullText += fmt.Sprintf( sb.WriteString("<span color='")
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>", sb.WriteString(Conf.LA.Separator.Right.Color)
Conf.LA.Separator.Right.Color, sb.WriteString("' background='")
Conf.LA.Separator.Right.Background, sb.WriteString(Conf.LA.Separator.Right.Background)
Conf.LA.Separator.Right.Font, sb.WriteString("' font='")
Conf.LA.Separator.Right.FontSize, sb.WriteString(Conf.LA.Separator.Right.Font)
Conf.LA.Separator.Right.Symbol, sb.WriteString("' size='")
) sb.WriteString(Conf.LA.Separator.Right.FontSize)
sb.WriteString("'>")
sb.WriteString(Conf.LA.Separator.Right.Symbol)
sb.WriteString("</span>")
} }
b.FullText = sb.String()
b.Markup = "pango" b.Markup = "pango"
b.Separator = false b.Separator = false
@@ -520,41 +543,41 @@ func main() {
j = append(j, b) j = append(j, b)
} }
if Conf.Clock.Enabled { if Conf.CmdRun.Enabled {
var b lib.I3BarOutBlock var b lib.I3BarOutBlock
b.Name = `wallclock` b.Name = `runcommandoutput`
b.Color = Conf.Clock.Color b.Color = Conf.CmdRun.Color
b.Background = Conf.Clock.Background b.Background = Conf.CmdRun.Background
if Conf.Clock.Separator.Left.Enabled { if Conf.CmdRun.Separator.Left.Enabled {
b.FullText = fmt.Sprintf( b.FullText = fmt.Sprintf(
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>", "<span color='%s' background='%s' font='%s' size='%s'>%s</span>",
Conf.Clock.Separator.Left.Color, Conf.CmdRun.Separator.Left.Color,
Conf.Clock.Separator.Left.Background, Conf.CmdRun.Separator.Left.Background,
Conf.Clock.Separator.Left.Font, Conf.CmdRun.Separator.Left.Font,
Conf.Clock.Separator.Left.FontSize, Conf.CmdRun.Separator.Left.FontSize,
Conf.Clock.Separator.Left.Symbol, Conf.CmdRun.Separator.Left.Symbol,
) )
} }
b.FullText += fmt.Sprintf( b.FullText += fmt.Sprintf(
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>", "<span color='%s' background='%s' font='%s' size='%s'>%s</span>",
Conf.Clock.Color, Conf.CmdRun.Color,
Conf.Clock.Background, Conf.CmdRun.Background,
Conf.Clock.Font, Conf.CmdRun.Font,
Conf.Clock.FontSize, Conf.CmdRun.FontSize,
Conf.Values.ClockTime, Conf.Values.RunCommandOutput,
) )
if Conf.Clock.Separator.Right.Enabled { if Conf.CmdRun.Separator.Right.Enabled {
b.FullText += fmt.Sprintf( b.FullText += fmt.Sprintf(
"<span color='%s' background='%s' font='%s' size='%s'>%s</span>", "<span color='%s' background='%s' font='%s' size='%s'>%s</span>",
Conf.Clock.Separator.Right.Color, Conf.CmdRun.Separator.Right.Color,
Conf.Clock.Separator.Right.Background, Conf.CmdRun.Separator.Right.Background,
Conf.Clock.Separator.Right.Font, Conf.CmdRun.Separator.Right.Font,
Conf.Clock.Separator.Right.FontSize, Conf.CmdRun.Separator.Right.FontSize,
Conf.Clock.Separator.Right.Symbol, Conf.CmdRun.Separator.Right.Symbol,
) )
} }
@@ -564,12 +587,68 @@ func main() {
j = append(j, b) j = append(j, b)
} }
if Conf.Clock.Enabled {
var (
b lib.I3BarOutBlock
sb strings.Builder
)
b.Name = `wallclock`
b.Color = Conf.Clock.Color
b.Background = Conf.Clock.Background
if Conf.Clock.Separator.Left.Enabled {
sb.WriteString("<span color='")
sb.WriteString(Conf.Clock.Separator.Left.Color)
sb.WriteString("' background='")
sb.WriteString(Conf.Clock.Separator.Left.Background)
sb.WriteString("' font='")
sb.WriteString(Conf.Clock.Separator.Left.Font)
sb.WriteString("' size='")
sb.WriteString(Conf.Clock.Separator.Left.FontSize)
sb.WriteString("'>")
sb.WriteString(Conf.Clock.Separator.Left.Symbol)
sb.WriteString("</span>")
}
sb.WriteString("<span color='")
sb.WriteString(Conf.Clock.Color)
sb.WriteString("' background='")
sb.WriteString(Conf.Clock.Background)
sb.WriteString("' font='")
sb.WriteString(Conf.Clock.Font)
sb.WriteString("' size='")
sb.WriteString(Conf.Clock.FontSize)
sb.WriteString("'>")
sb.WriteString(Conf.Values.ClockTime)
sb.WriteString("</span>")
if Conf.Clock.Separator.Right.Enabled {
sb.WriteString("<span color='")
sb.WriteString(Conf.Clock.Separator.Right.Color)
sb.WriteString("' background='")
sb.WriteString(Conf.Clock.Separator.Right.Background)
sb.WriteString("' font='")
sb.WriteString(Conf.Clock.Separator.Right.Font)
sb.WriteString("' size='")
sb.WriteString(Conf.Clock.Separator.Right.FontSize)
sb.WriteString("'>")
sb.WriteString(Conf.Clock.Separator.Right.Symbol)
sb.WriteString("</span>")
}
b.FullText = sb.String()
b.Markup = "pango"
b.Separator = false
j = append(j, b)
}
if Conf.Values.PrintOutput && len(j) > 0 { if Conf.Values.PrintOutput && len(j) > 0 {
Conf.Channels.MsgChan <- j Conf.Channels.MsgChan <- j
} }
} }
} }
}
// PrintToI3bar prints info to stdout according to ipc docs (https://i3wm.org/docs/i3bar-protocol.html) // PrintToI3bar prints info to stdout according to ipc docs (https://i3wm.org/docs/i3bar-protocol.html)
func PrintToI3bar(c *lib.MyConfig) { func PrintToI3bar(c *lib.MyConfig) {
@@ -587,3 +666,5 @@ func PrintToI3bar(c *lib.MyConfig) {
fmt.Println(strings.TrimSuffix(buf.String(), "\n") + ",") fmt.Println(strings.TrimSuffix(buf.String(), "\n") + ",")
} }
} }
/* vim: set ft=go noet ai ts=4 sw=4 sts=4: */

View File

@@ -1 +1 @@
/home/eleksir/git/i3status-go/cmd/i3status-go/default-config.json ../cmd/i3status-go/default-config.json

19
go.mod
View File

@@ -1,12 +1,12 @@
module i3status-go module i3status-go
go 1.22.6 go 1.24.2
require ( require (
github.com/adrg/xdg v0.5.0 github.com/adrg/xdg v0.5.3
github.com/davecgh/go-spew v1.1.1 github.com/davecgh/go-spew v1.1.1
github.com/distatus/battery v0.11.0 github.com/distatus/battery v0.11.0
github.com/go-co-op/gocron/v2 v2.12.1 github.com/go-co-op/gocron/v2 v2.16.1
github.com/hjson/hjson-go v3.3.0+incompatible github.com/hjson/hjson-go v3.3.0+incompatible
github.com/mafik/pulseaudio v0.0.0-20240327130323-384e01075e6e github.com/mafik/pulseaudio v0.0.0-20240327130323-384e01075e6e
github.com/shirou/gopsutil v3.21.11+incompatible github.com/shirou/gopsutil v3.21.11+incompatible
@@ -17,11 +17,18 @@ require (
github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc // indirect github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc // indirect
github.com/BurntSushi/xgbutil v0.0.0-20190907113008-ad855c713046 // indirect github.com/BurntSushi/xgbutil v0.0.0-20190907113008-ad855c713046 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect github.com/go-ole/go-ole v1.3.0 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/jonboulle/clockwork v0.4.0 // indirect github.com/jonboulle/clockwork v0.5.0 // indirect
github.com/robfig/cron/v3 v3.0.1 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 // indirect golang.org/x/sync v0.12.0 // indirect
golang.org/x/sys v0.25.0 // indirect golang.org/x/sys v0.32.0 // indirect
howett.net/plist v1.0.1 // indirect howett.net/plist v1.0.1 // indirect
) )
tool (
i3status-go/cmd/battery-test
i3status-go/cmd/i3status-go
i3status-go/internal/lib
)

26
go.sum
View File

@@ -4,14 +4,14 @@ github.com/BurntSushi/xgb v0.0.0-20210121224620-deaf085860bc/go.mod h1:IVnqGOEym
github.com/BurntSushi/xgbutil v0.0.0-20160919175755-f7c97cef3b4e/go.mod h1:uw9h2sd4WWHOPdJ13MQpwK5qYWKYDumDqxWWIknEQ+k= github.com/BurntSushi/xgbutil v0.0.0-20160919175755-f7c97cef3b4e/go.mod h1:uw9h2sd4WWHOPdJ13MQpwK5qYWKYDumDqxWWIknEQ+k=
github.com/BurntSushi/xgbutil v0.0.0-20190907113008-ad855c713046 h1:O/r2Sj+8QcMF7V5IcmiE2sMFV2q3J47BEirxbXJAdzA= github.com/BurntSushi/xgbutil v0.0.0-20190907113008-ad855c713046 h1:O/r2Sj+8QcMF7V5IcmiE2sMFV2q3J47BEirxbXJAdzA=
github.com/BurntSushi/xgbutil v0.0.0-20190907113008-ad855c713046/go.mod h1:uw9h2sd4WWHOPdJ13MQpwK5qYWKYDumDqxWWIknEQ+k= github.com/BurntSushi/xgbutil v0.0.0-20190907113008-ad855c713046/go.mod h1:uw9h2sd4WWHOPdJ13MQpwK5qYWKYDumDqxWWIknEQ+k=
github.com/adrg/xdg v0.5.0 h1:dDaZvhMXatArP1NPHhnfaQUqWBLBsmx1h1HXQdMoFCY= github.com/adrg/xdg v0.5.3 h1:xRnxJXne7+oWDatRhR1JLnvuccuIeCoBu2rtuLqQB78=
github.com/adrg/xdg v0.5.0/go.mod h1:dDdY4M4DF9Rjy4kHPeNL+ilVF+p2lK8IdM9/rTSGcI4= github.com/adrg/xdg v0.5.3/go.mod h1:nlTsY+NNiCBGCK2tpm09vRqfVzrc2fLmXGpBLF0zlTQ=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/distatus/battery v0.11.0 h1:KJk89gz90Iq/wJtbjjM9yUzBXV+ASV/EG2WOOL7N8lc= github.com/distatus/battery v0.11.0 h1:KJk89gz90Iq/wJtbjjM9yUzBXV+ASV/EG2WOOL7N8lc=
github.com/distatus/battery v0.11.0/go.mod h1:KmVkE8A8hpIX4T78QRdMktYpEp35QfOL8A8dwZBxq2k= github.com/distatus/battery v0.11.0/go.mod h1:KmVkE8A8hpIX4T78QRdMktYpEp35QfOL8A8dwZBxq2k=
github.com/go-co-op/gocron/v2 v2.12.1 h1:dCIIBFbzhWKdgXeEifBjHPzgQ1hoWhjS4289Hjjy1uw= github.com/go-co-op/gocron/v2 v2.16.1 h1:ux/5zxVRveCaCuTtNI3DiOk581KC1KpJbpJFYUEVYwo=
github.com/go-co-op/gocron/v2 v2.12.1/go.mod h1:xY7bJxGazKam1cz04EebrlP4S9q4iWdiAylMGP3jY9w= github.com/go-co-op/gocron/v2 v2.16.1/go.mod h1:opexeOFy5BplhsKdA7bzY9zeYih8I8/WNJ4arTIFPVc=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
@@ -23,8 +23,8 @@ github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+
github.com/hjson/hjson-go v3.3.0+incompatible h1:Rqr+Ya+0aCJMjaE4s8E9YKvuJLuLVpEvz4ONum52vnI= github.com/hjson/hjson-go v3.3.0+incompatible h1:Rqr+Ya+0aCJMjaE4s8E9YKvuJLuLVpEvz4ONum52vnI=
github.com/hjson/hjson-go v3.3.0+incompatible/go.mod h1:qsetwF8NlsTsOTwZTApNlTCerV+b2GjYRRcIk4JMFio= github.com/hjson/hjson-go v3.3.0+incompatible/go.mod h1:qsetwF8NlsTsOTwZTApNlTCerV+b2GjYRRcIk4JMFio=
github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=
github.com/jonboulle/clockwork v0.4.0 h1:p4Cf1aMWXnXAUh8lVfewRBx1zaTSYKrKMF2g3ST4RZ4= github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I=
github.com/jonboulle/clockwork v0.4.0/go.mod h1:xgRqUGwRcjKCO1vbZUEtSLrqKoPSsUpK7fnezOII0kc= github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60=
github.com/mafik/pulseaudio v0.0.0-20240327130323-384e01075e6e h1:y6jINFpNNS+IEizD6s9j35aKVNRsfsoEKN8IStRDQm0= github.com/mafik/pulseaudio v0.0.0-20240327130323-384e01075e6e h1:y6jINFpNNS+IEizD6s9j35aKVNRsfsoEKN8IStRDQm0=
github.com/mafik/pulseaudio v0.0.0-20240327130323-384e01075e6e/go.mod h1:dlpd1fnLAhI6g9tM/aCobgN/Yka1/SkHrBTfAgDdb9Q= github.com/mafik/pulseaudio v0.0.0-20240327130323-384e01075e6e/go.mod h1:dlpd1fnLAhI6g9tM/aCobgN/Yka1/SkHrBTfAgDdb9Q=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
@@ -33,24 +33,22 @@ github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI=
github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
go.i3wm.org/i3 v0.0.0-20190720062127-36e6ec85cc5a h1:yeQv6GWN8DsA2f3b+u1zhRIJg2HmsGYqXsd+W7ULr7Q= go.i3wm.org/i3 v0.0.0-20190720062127-36e6ec85cc5a h1:yeQv6GWN8DsA2f3b+u1zhRIJg2HmsGYqXsd+W7ULr7Q=
go.i3wm.org/i3 v0.0.0-20190720062127-36e6ec85cc5a/go.mod h1:7w17+r1F28Yxb1pHu8SxARJo+RGvJCAGOEf+GLw+2aQ= go.i3wm.org/i3 v0.0.0-20190720062127-36e6ec85cc5a/go.mod h1:7w17+r1F28Yxb1pHu8SxARJo+RGvJCAGOEf+GLw+2aQ=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk=
golang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY=
golang.org/x/net v0.0.0-20181102091132-c10e9556a7bc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181102091132-c10e9556a7bc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg= gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

View File

@@ -1,8 +1,14 @@
// Package lib represents guts of i3status-go.
package lib package lib
import ( import (
"fmt" "fmt"
"log"
"math" "math"
"os"
"path/filepath"
"strconv"
"strings"
"time" "time"
"github.com/distatus/battery" "github.com/distatus/battery"
@@ -11,24 +17,103 @@ import (
// UpdateBatteryInfo updates info about battery charge. // UpdateBatteryInfo updates info about battery charge.
func (c *MyConfig) UpdateBatteryInfo() { func (c *MyConfig) UpdateBatteryInfo() {
var ( var (
InitialDelay = 100 * time.Millisecond
LoopIterationDelay = 5 * time.Second
Delay = InitialDelay
ticker = time.NewTicker(Delay)
)
for range ticker.C {
if Delay == InitialDelay {
Delay = LoopIterationDelay
ticker.Reset(Delay)
}
var (
batteries = []*battery.Battery{}
Batts string
ch int ch int
status string status string
Batts string
) )
for { if c.Battery.UseSysfs {
batteries, err := battery.GetAll() for _, file := range c.Battery.SysfsFiles {
var batt battery.Battery
_, err := os.Stat(file)
// If file exists.
if !os.IsNotExist(err) {
var (
myCharge string
myStatus string
)
b, err := os.ReadFile(file)
if err != nil { if err != nil {
Batts = fmt.Sprintf( log.Printf("Unable to read file %s: %s", file, err)
"<span font='%s' size='%s'>%s</span><span font='%s' size='%s'> no batt</span>",
c.Battery.SymbolFont, continue
c.Battery.SymbolFontSize, }
c.Battery.Symbol,
c.Battery.Font, myCharge = strings.TrimSpace(string(b))
c.Battery.FontSize,
) statusFile := filepath.Dir(file) + "/status"
_, err = os.Stat(statusFile)
if !os.IsNotExist(err) {
b, err := os.ReadFile(statusFile)
if err != nil {
log.Printf("Unable to read file %s: %s", statusFile, err)
continue
}
myStatus = strings.TrimSpace(string(b))
} else { } else {
continue
}
// Make stub battery class :) .
switch myStatus {
case "Charging":
batt.State.Raw = battery.Charging
case "Discharging":
batt.State.Raw = battery.Discharging
case "Empty":
batt.State.Raw = battery.Empty
case "Full":
batt.State.Raw = battery.Full
default:
batt.State.Raw = battery.Unknown
}
ch, err := strconv.Atoi(myCharge)
if err != nil {
log.Printf("Unable to convert string from file %s to integer", file)
continue
}
batt.Current = float64(ch)
batteries = append(batteries, &batt)
}
}
} else {
var err error
batteries, err = battery.GetAll()
if err != nil {
log.Printf("Unable to get battery info: %s", err)
}
}
var ( var (
battsInfo string battsInfo string
chStr string chStr string
@@ -48,10 +133,14 @@ func (c *MyConfig) UpdateBatteryInfo() {
// N.B. there can be case when battery is overcharged and shows >100%. It also can indicate that // N.B. there can be case when battery is overcharged and shows >100%. It also can indicate that
// calibration data is out of date and battery should be re-calibrated. // calibration data is out of date and battery should be re-calibrated.
if c.Battery.UseSysfs {
ch = int(b.Current)
} else {
ch = int(math.Round((b.Full - (b.Full - b.Current)) * (100 / b.Full))) ch = int(math.Round((b.Full - (b.Full - b.Current)) * (100 / b.Full)))
}
switch { switch {
case ch > 85: case ch <= 500 && ch >= 84:
if c.Battery.ChargeColor.Full == "" { if c.Battery.ChargeColor.Full == "" {
chStr = fmt.Sprintf( chStr = fmt.Sprintf(
"<span color='%s' background='%s' font='%s' size='%s'>% 3d%%</span>", "<span color='%s' background='%s' font='%s' size='%s'>% 3d%%</span>",
@@ -114,7 +203,7 @@ func (c *MyConfig) UpdateBatteryInfo() {
) )
} }
case ch < 10: case ch < 10 && ch >= 0:
if c.Battery.ChargeColor.Empty == "" { if c.Battery.ChargeColor.Empty == "" {
chStr = fmt.Sprintf( chStr = fmt.Sprintf(
"<span color='%s' background='%s' font='%s' size='%s'>% 3d%%</span>", "<span color='%s' background='%s' font='%s' size='%s'>% 3d%%</span>",
@@ -134,6 +223,9 @@ func (c *MyConfig) UpdateBatteryInfo() {
ch, ch,
) )
} }
default:
continue
} }
battsInfo += fmt.Sprintf( battsInfo += fmt.Sprintf(
@@ -160,13 +252,12 @@ func (c *MyConfig) UpdateBatteryInfo() {
if battsInfo != "" { if battsInfo != "" {
Batts = battsInfo Batts = battsInfo
} }
}
if c.Values.BatteryString != Batts { if c.Values.BatteryString != Batts {
c.Values.BatteryString = Batts c.Values.BatteryString = Batts
c.Channels.UpdateReady <- true c.Channels.UpdateReady <- true
} }
}
}
time.Sleep(5 * time.Second) /* vim: set ft=go noet ai ts=4 sw=4 sts=4: */
}
}

View File

@@ -7,7 +7,19 @@ import (
// UpdateClock get and updates (on i3bar) info about system clock. // UpdateClock get and updates (on i3bar) info about system clock.
func (c *MyConfig) UpdateClock() { func (c *MyConfig) UpdateClock() {
for { var (
InitialDelay = 100 * time.Millisecond
LoopIterationDelay = 1 * time.Second
Delay = InitialDelay
ticker = time.NewTicker(Delay)
)
for range ticker.C {
if Delay == InitialDelay {
Delay = LoopIterationDelay
ticker.Reset(Delay)
}
currentTime := time.Now() currentTime := time.Now()
hours, minutes, _ := currentTime.Clock() hours, minutes, _ := currentTime.Clock()
year, month, day := currentTime.Date() year, month, day := currentTime.Date()
@@ -21,7 +33,7 @@ func (c *MyConfig) UpdateClock() {
c.Values.ClockTime = myclock c.Values.ClockTime = myclock
c.Channels.UpdateReady <- true c.Channels.UpdateReady <- true
} }
}
}
time.Sleep(1 * time.Second) /* vim: set ft=go noet ai ts=4 sw=4 sts=4: */
}
}

View File

@@ -7,62 +7,64 @@ import (
// Collection is sync.Map, that stores arbitrary data. // Collection is sync.Map, that stores arbitrary data.
type Collection struct { type Collection struct {
items sync.Map items sync.Map
close chan struct{}
} }
// Item just interface for stoing any data. // Item just interface for stoing any data.
type item struct { type item struct {
data interface{} data any
} }
// NewCollection creates new instance of "collection". // NewCollection creates new instance of "collection".
func NewCollection() *Collection { func NewCollection() *Collection {
c := &Collection{ //nolint:exhaustruct c := &Collection{}
close: make(chan struct{}),
}
return c return c
} }
// Get returns value by given key. Or empty value. // Get returns value by given key. Or empty value.
func (collection *Collection) Get(key interface{}) (interface{}, bool) { func (collection *Collection) Get(key any) (any, bool) {
obj, exists := collection.items.Load(key) obj, exists := collection.items.Load(key)
if !exists { if !exists {
return nil, false return nil, false
} }
item := obj.(item) it, ok := obj.(item)
if !ok {
return nil, false
}
return item.data, true return it.data, true
} }
// Set saves value to given "collection". // Set saves value to given "collection".
func (collection *Collection) Set(key interface{}, value interface{}) { func (collection *Collection) Set(key any, value any) {
collection.items.Store(key, item{ collection.items.Store(key, item{
data: value, data: value,
}) })
} }
// Range apply function f to all keys/values in collection. Retuns immediatly on first error. // Range apply function f to all keys/values in collection. Returns immediately on first error.
func (collection *Collection) Range(f func(key, value interface{}) bool) { func (collection *Collection) Range(f func(key, value any) bool) {
fn := func(key, value interface{}) bool { fn := func(key, value any) bool {
item := value.(item) it, ok := value.(item)
if !ok {
return true
}
return f(key, item.data) return f(key, it.data)
} }
collection.items.Range(fn) collection.items.Range(fn)
} }
// Delete deletes key and corresponding value from collection. // Delete deletes key and corresponding value from collection.
func (collection *Collection) Delete(key interface{}) { func (collection *Collection) Delete(key any) {
collection.items.Delete(key) collection.items.Delete(key)
} }
// Close frees memory occupied by collection and deletes collection itself. // Close frees memory occupied by collection and deletes collection itself.
func (collection *Collection) Close() { func (collection *Collection) Close() {
collection.close <- struct{}{}
collection.items = sync.Map{} collection.items = sync.Map{}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -10,68 +10,83 @@ import (
// UpdateCPUTemperature gets and updates average CPU cores temperature. // UpdateCPUTemperature gets and updates average CPU cores temperature.
func (c *MyConfig) UpdateCPUTemperature() { func (c *MyConfig) UpdateCPUTemperature() {
n := len(c.CPUTemp.File) var (
n = len(c.CPUTemp.File)
InitialDelay = 100 * time.Millisecond
LoopIterationDelay = 3 * time.Second
Delay = InitialDelay
ticker = time.NewTicker(Delay)
)
for { for range ticker.C {
var ( var (
temperature = make([]int64, n) temperature = make([]int64, n)
tSum int64 tSum int64
tAvg int64 tAvg int64
validCount int
) )
if Delay == InitialDelay {
Delay = LoopIterationDelay
ticker.Reset(Delay)
}
for i, filename := range c.CPUTemp.File { for i, filename := range c.CPUTemp.File {
file, err := os.Open(filename) file, err := os.Open(filename)
if err != nil { if err != nil {
log.Printf("Unable to open %s: %s", filename, err) log.Printf("Unable to open %s: %s", filename, err)
} else { continue
}
defer file.Close()
reader := bufio.NewReader(file) reader := bufio.NewReader(file)
line, _, err := reader.ReadLine() line, _, err := reader.ReadLine()
if err != nil { if err != nil {
log.Printf("Unable to read from %s: %s", filename, err) log.Printf("Unable to read from %s: %s", filename, err)
err = file.Close() continue
if err != nil {
log.Printf("Unable to close %s: %s", filename, err)
} }
} else {
err = file.Close()
if err != nil {
log.Printf("Unable to close %s: %s", filename, err)
} else {
temp, err := strconv.ParseInt(string(line), 10, 32) temp, err := strconv.ParseInt(string(line), 10, 32)
if err != nil { if err != nil {
log.Printf("Unable to convert string to number from file %s: %s", filename, err) log.Printf("Unable to convert string to number from file %s: %s", filename, err)
} else { continue
}
if temp > 1000 { if temp > 1000 {
temp /= 1000 temp /= 1000
} }
temperature[i] = temp temperature[i] = temp
} validCount++
}
}
}
} }
if len(temperature) == 1 { if validCount == 0 {
tAvg = temperature[0] continue
}
if validCount == 1 {
for _, t := range temperature {
if t != 0 {
tAvg = t
break
}
}
} else { } else {
for _, t := range temperature { for _, t := range temperature {
tSum += t tSum += t
} }
tAvg = tSum / int64(len(temperature)) tAvg = tSum / int64(validCount)
} }
if c.Values.CPUTemperature != tAvg { if c.Values.CPUTemperature != tAvg {
c.Values.CPUTemperature = tAvg c.Values.CPUTemperature = tAvg
c.Channels.UpdateReady <- true c.Channels.UpdateReady <- true
} }
}
}
time.Sleep(3 * time.Second) /* vim: set ft=go noet ai ts=4 sw=4 sts=4: */
}
}

View File

@@ -7,7 +7,9 @@ import (
) )
// myCron contains cron handler. // myCron contains cron handler.
var myCron gocron.Scheduler var (
myCron gocron.Scheduler
)
// RunCron parses config part, related to cron tasks and kicks cron to run. // RunCron parses config part, related to cron tasks and kicks cron to run.
func (c MyConfig) RunCron() { func (c MyConfig) RunCron() {
@@ -25,15 +27,12 @@ func (c MyConfig) RunCron() {
_, err := myCron.NewJob( _, err := myCron.NewJob(
gocron.CronJob(job.Time, false), gocron.CronJob(job.Time, false),
gocron.NewTask( gocron.NewTask(
// Сука, просто заспавнить бинарь, ну почему это надо делать через жопу-то?
any(
func() bool { func() bool {
c.Channels.RunChan <- job.Cmd c.Channels.RunChan <- job.Cmd
return true return true
}, },
), ),
),
) )
if err != nil { if err != nil {
@@ -43,3 +42,5 @@ func (c MyConfig) RunCron() {
myCron.Start() myCron.Start()
} }
/* vim: set ft=go noet ai ts=4 sw=4 sts=4: */

View File

@@ -19,15 +19,18 @@ var WL WinList
// UpdateI3WinList subsribes to all window-related events and send them to I3EventParser() for more detailed parsing. // UpdateI3WinList subsribes to all window-related events and send them to I3EventParser() for more detailed parsing.
func (c *MyConfig) UpdateI3WinList() { func (c *MyConfig) UpdateI3WinList() {
// TODO: Здесь получить начальный список окон, управляемых i3wm (через GetTree()) и сложить их атрибутику в переменную WL
Tree, err := i3.GetTree() Tree, err := i3.GetTree()
if err != nil { if err != nil {
log.Printf("Unable to get list of windows: %s", err) log.Printf("Unable to get list of windows: %s", err)
return
} }
c.ExtractProps(Tree.Root) c.ExtractProps(Tree.Root)
c.Channels.UpdateReady <- true
i3wm := i3.Subscribe(i3.WindowEventType) i3wm := i3.Subscribe(i3.WindowEventType)
for i3wm.Next() { for i3wm.Next() {
@@ -105,9 +108,11 @@ func (c *MyConfig) I3EventParser(e *i3.WindowEvent) {
// interfaceToUint превращает данный интерфейс в Uint64. // interfaceToUint превращает данный интерфейс в Uint64.
// Если может, конечно :) . // Если может, конечно :) .
func interfaceToUint64(iface interface{}) uint64 { func interfaceToUint64(iface any) uint64 {
// А теперь мы начинаем дурдом, нам надо превратить ёбанный interface{} в []string if iface == nil {
// Поскольку interface{} может быть чем угодно, перестрахуемся return 0
}
if reflect.TypeOf(iface).Kind() == reflect.Uint64 { if reflect.TypeOf(iface).Kind() == reflect.Uint64 {
return reflect.ValueOf(iface).Uint() return reflect.ValueOf(iface).Uint()
} }
@@ -152,18 +157,16 @@ func HasWindows(className string, instanceName string) bool {
func FindWindowInstance(regexpStr string) bool { func FindWindowInstance(regexpStr string) bool {
var found = false var found = false
f := func(key interface{}, value interface{}) bool { re, err := regexp.Compile(regexpStr)
keyStr := reflect.ValueOf(key).String()
re, err := regexp.Compile(regexpStr) //nolint:nolintlint, gocritic, we do not want shit our pants and panic on
// erroneous regexp, we want log it to stderr, that it.
if err != nil { if err != nil {
log.Printf("Unable to perform regexp match: %s", err) log.Printf("Unable to perform regexp match: %s", err)
return true return false
} }
f := func(key any, value any) bool { //nolint: revive
keyStr := reflect.ValueOf(key).String()
if re.Match([]byte(keyStr)) { //nolint:mirror if re.Match([]byte(keyStr)) { //nolint:mirror
found = true found = true
@@ -183,18 +186,16 @@ func FindWindowInstance(regexpStr string) bool {
func FindWindowClass(regexpStr string) bool { func FindWindowClass(regexpStr string) bool {
var found = false var found = false
f := func(key interface{}, value interface{}) bool { re, err := regexp.Compile(regexpStr)
keyStr := reflect.ValueOf(key).String()
re, err := regexp.Compile(regexpStr) //nolint:nolintlint, gocritic, we do not want shit our pants and panic on
// erroneous regexp, we want log it to stderr, that it.
if err != nil { if err != nil {
log.Printf("Unable to perform regexp match: %s", err) log.Printf("Unable to perform regexp match: %s", err)
return true return false
} }
f := func(key any, value any) bool { //nolint: revive
keyStr := reflect.ValueOf(key).String()
if re.Match([]byte(keyStr)) { //nolint:mirror if re.Match([]byte(keyStr)) { //nolint:mirror
found = true found = true
@@ -225,3 +226,5 @@ func (c *MyConfig) ExtractProps(n *i3.Node) {
c.ExtractProps(node) c.ExtractProps(node)
} }
} }
/* vim: set ft=go noet ai ts=4 sw=4 sts=4: */

View File

@@ -11,7 +11,19 @@ import (
// UpdateIfStatus updates network interfaces status for i3bar. // UpdateIfStatus updates network interfaces status for i3bar.
func (c *MyConfig) UpdateIfStatus() { func (c *MyConfig) UpdateIfStatus() {
for { var (
InitialDelay = 100 * time.Millisecond
LoopIterationDelay = 3 * time.Second
Delay = InitialDelay
ticker = time.NewTicker(Delay)
)
for range ticker.C {
if Delay == InitialDelay {
Delay = LoopIterationDelay
ticker.Reset(Delay)
}
var statusSum string var statusSum string
for _, item := range c.NetIf.If { for _, item := range c.NetIf.If {
@@ -32,8 +44,8 @@ func (c *MyConfig) UpdateIfStatus() {
} else { } else {
switch strings.TrimSpace(string(operstate)) { switch strings.TrimSpace(string(operstate)) {
case "up": case "up":
StatusStr := fmt.Sprintf("<span foreground=\"%s\">⍋</span>", c.NetIf.UpColor) statusStr := fmt.Sprintf("<span foreground=\"%s\">⍋</span>", c.NetIf.UpColor)
operstate = []byte(StatusStr) operstate = []byte(statusStr)
case "down": case "down":
statusStr := fmt.Sprintf("<span foreground=\"%s\">⍒</span>", c.NetIf.DownColor) statusStr := fmt.Sprintf("<span foreground=\"%s\">⍒</span>", c.NetIf.DownColor)
operstate = []byte(statusStr) operstate = []byte(statusStr)
@@ -53,7 +65,7 @@ func (c *MyConfig) UpdateIfStatus() {
c.Values.IfStatus = statusSum c.Values.IfStatus = statusSum
c.Channels.UpdateReady <- true c.Channels.UpdateReady <- true
} }
}
}
time.Sleep(3 * time.Second) /* vim: set ft=go noet ai ts=4 sw=4 sts=4: */
}
}

View File

@@ -2,6 +2,7 @@ package lib
import ( import (
"fmt" "fmt"
"log"
"time" "time"
"github.com/shirou/gopsutil/load" "github.com/shirou/gopsutil/load"
@@ -9,8 +10,26 @@ import (
// UpdateLaStats вытаскивает показание LA за последнюю минуту. // UpdateLaStats вытаскивает показание LA за последнюю минуту.
func (c *MyConfig) UpdateLaStats() { func (c *MyConfig) UpdateLaStats() {
for { var (
l, _ := load.Avg() InitialDelay = 100 * time.Millisecond
LoopIterationDelay = 3 * time.Second
Delay = InitialDelay
ticker = time.NewTicker(Delay)
)
for range ticker.C {
if Delay == InitialDelay {
Delay = LoopIterationDelay
ticker.Reset(Delay)
}
l, err := load.Avg()
if err != nil {
log.Printf("Unable to get LA stats: %s", err)
continue
}
lav := fmt.Sprintf("%.2f", l.Load1) lav := fmt.Sprintf("%.2f", l.Load1)
@@ -18,7 +37,7 @@ func (c *MyConfig) UpdateLaStats() {
c.Values.La = lav c.Values.La = lav
c.Channels.UpdateReady <- true c.Channels.UpdateReady <- true
} }
}
}
time.Sleep(3 * time.Second) /* vim: set ft=go noet ai ts=4 sw=4 sts=4: */
}
}

View File

@@ -16,7 +16,19 @@ type Mem struct {
// UpdateMemStats parses mem info stats. // UpdateMemStats parses mem info stats.
func (c *MyConfig) UpdateMemStats() { func (c *MyConfig) UpdateMemStats() {
for { var (
InitialDelay = 100 * time.Millisecond
LoopIterationDelay = 3 * time.Second
Delay = InitialDelay
ticker = time.NewTicker(Delay)
)
for range ticker.C {
if Delay == InitialDelay {
Delay = LoopIterationDelay
ticker.Reset(Delay)
}
v, err := mem.VirtualMemory() v, err := mem.VirtualMemory()
if err != nil { if err != nil {
@@ -26,6 +38,7 @@ func (c *MyConfig) UpdateMemStats() {
continue continue
} }
if c.Mem.ShowSwap {
sw, err := mem.SwapMemory() sw, err := mem.SwapMemory()
if err != nil { if err != nil {
@@ -35,11 +48,10 @@ func (c *MyConfig) UpdateMemStats() {
continue continue
} }
if c.Mem.ShowSwap { if c.Values.Memory.Usedpct != uint64(v.UsedPercent) || c.Values.Memory.Shared != v.Shared/1024/1024 || c.Values.Memory.Swap != sw.Used/1024/1024 {
if c.Values.Memory.Usedpct != uint64(v.UsedPercent) || c.Values.Memory.Shared != v.Shared/1024/1024 || c.Values.Memory.Swap != v.SwapTotal-v.SwapFree {
c.Values.Memory.Usedpct = uint64(v.UsedPercent) c.Values.Memory.Usedpct = uint64(v.UsedPercent)
c.Values.Memory.Shared = v.Shared / 1024 / 1024 c.Values.Memory.Shared = v.Shared / 1024 / 1024
c.Values.Memory.Swap = sw.Used c.Values.Memory.Swap = sw.Used / 1024 / 1024
c.Channels.UpdateReady <- true c.Channels.UpdateReady <- true
} }
} else { } else {
@@ -49,7 +61,7 @@ func (c *MyConfig) UpdateMemStats() {
c.Channels.UpdateReady <- true c.Channels.UpdateReady <- true
} }
} }
}
}
time.Sleep(3 * time.Second) /* vim: set ft=go noet ai ts=4 sw=4 sts=4: */
}
}

View File

@@ -113,12 +113,12 @@ func (c *MyConfig) PaReinit() error {
var err error var err error
// If we out of updates, seems someone killed pulseaudio server. Restart it. // If we out of updates, seems someone killed pulseaudio server. Restart it.
cmd := exec.Command("pulseaudio", "--check") cmd := exec.Command("pulseaudio", "--check") //nolint: noctx
if err := cmd.Run(); err == nil { if err := cmd.Run(); err == nil {
log.Printf("pulseaudio already running, but seems not responding, try gracefully kill it") log.Printf("pulseaudio already running, but seems not responding, try gracefully kill it")
cmd = exec.Command("pulseaudio", "--kill") cmd = exec.Command("pulseaudio", "--kill") //nolint: noctx
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
return fmt.Errorf("unable to kill pulseaudio: %w", err) return fmt.Errorf("unable to kill pulseaudio: %w", err)
@@ -127,7 +127,7 @@ func (c *MyConfig) PaReinit() error {
cnt := 0 cnt := 0
for { for {
cmd := exec.Command("pulseaudio", "--check") cmd := exec.Command("pulseaudio", "--check") //nolint: noctx
// PA not running. Breakout of loop. // PA not running. Breakout of loop.
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
@@ -135,7 +135,7 @@ func (c *MyConfig) PaReinit() error {
} }
if cnt >= 5 { if cnt >= 5 {
return errors.New("timeout waiting pulseaudio to exit") //nolint: goerr113 return errors.New("timeout waiting pulseaudio to exit") //nolint: err113
} }
log.Print("Waiting for pulseaudio to exit") log.Print("Waiting for pulseaudio to exit")
@@ -154,10 +154,10 @@ func (c *MyConfig) PaReinit() error {
// audio. // audio.
if c.SimpleVolumePa.DontExitOnLogin { if c.SimpleVolumePa.DontExitOnLogin {
// Do not exit on any kind of login/logout events. // Do not exit on any kind of login/logout events.
cmd = exec.Command("pulseaudio", "--exit-idle-time=-1", "--start") cmd = exec.Command("pulseaudio", "--exit-idle-time=-1", "--start") //nolint: noctx
} else { } else {
// Exit immediately on logout(?). // Exit immediately on logout(?).
cmd = exec.Command("pulseaudio", "--exit-idle-time=0", "--start") cmd = exec.Command("pulseaudio", "--exit-idle-time=0", "--start") //nolint: noctx
} }
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
@@ -173,6 +173,8 @@ func (c *MyConfig) PaReinit() error {
return err return err
} }
// SVPAHandler simple volume pulse audio handler works with events sent to SVPAHandlerChan cahnnel. Left/right clicks,
// wheel turning events etc.
func (c *MyConfig) SVPAHandler() { func (c *MyConfig) SVPAHandler() {
for e := range c.Channels.SVPAHandlerChan { for e := range c.Channels.SVPAHandlerChan {
if e.Button == 3 { if e.Button == 3 {
@@ -220,3 +222,5 @@ func (c *MyConfig) SVPAHandler() {
} }
} }
} }
/* vim: set ft=go noet ai ts=4 sw=4 sts=4: */

View File

@@ -0,0 +1,43 @@
package lib
import (
"log"
"time"
)
// RunCommand gets list of commands runs them sequentally and conacatenates their output.
func (c *MyConfig) RunCommand() {
var (
InitialDelay = 100 * time.Millisecond
LoopIterationDelay = time.Duration(c.CmdRun.Delay) * time.Second
Delay = InitialDelay
ticker = time.NewTicker(Delay)
)
for range ticker.C {
if Delay == InitialDelay {
Delay = LoopIterationDelay
ticker.Reset(Delay)
}
var (
outputString string
command = []string{c.CmdRun.Cmd}
)
if len(c.CmdRun.Args) > 0 {
command = append(command, c.CmdRun.Args...)
}
outputString += RunProcess(command)
log.Println(outputString)
if c.Values.RunCommandOutput != outputString {
c.Values.RunCommandOutput = outputString
c.Channels.UpdateReady <- true
}
}
}
/* vim: set ft=go noet ai ts=4 sw=4 sts=4: */

View File

@@ -6,8 +6,6 @@ import (
"syscall" "syscall"
) )
var PrintOutput = true
// SigHandler OS signal handler. // SigHandler OS signal handler.
func (c *MyConfig) SigHandler() { func (c *MyConfig) SigHandler() {
for s := range c.Channels.SigChan { for s := range c.Channels.SigChan {
@@ -33,3 +31,5 @@ func (c *MyConfig) SigHandler() {
} }
} }
} }
/* vim: set ft=go noet ai ts=4 sw=4 sts=4: */

View File

@@ -1,9 +1,11 @@
package lib package lib
import ( import (
"bytes"
"log" "log"
"os" "os"
"os/exec" "os/exec"
"strings"
"syscall" "syscall"
"time" "time"
) )
@@ -11,8 +13,21 @@ import (
// Spawner forks and execs given program, and also detaches form its control tty. // Spawner forks and execs given program, and also detaches form its control tty.
func (c *MyConfig) Spawner() { func (c *MyConfig) Spawner() {
for prg := range c.Channels.RunChan { for prg := range c.Channels.RunChan {
devnullR, _ := os.Open(os.DevNull) time.Sleep(25 * time.Millisecond)
devnullW, _ := os.OpenFile(os.DevNull, os.O_WRONLY|os.O_APPEND, 0644)
devnullR, err := os.Open(os.DevNull)
if err != nil {
log.Printf("Unable to open /dev/null for reading: %s", err)
continue
}
defer devnullR.Close()
devnullW, err := os.OpenFile(os.DevNull, os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
log.Printf("Unable to open /dev/null for writing: %s", err)
continue
}
defer devnullW.Close()
spa := syscall.SysProcAttr{ spa := syscall.SysProcAttr{
Setsid: true, Setsid: true,
@@ -30,6 +45,7 @@ func (c *MyConfig) Spawner() {
if err != nil { if err != nil {
log.Printf("Unable to spawn %s: %s", prg[0], err) log.Printf("Unable to spawn %s: %s", prg[0], err)
continue
} }
_, err = syscall.ForkExec(bin, prg, &pa) _, err = syscall.ForkExec(bin, prg, &pa)
@@ -37,10 +53,6 @@ func (c *MyConfig) Spawner() {
if err != nil { if err != nil {
log.Printf("Unable to spawn %s: %s", prg[0], err) log.Printf("Unable to spawn %s: %s", prg[0], err)
} }
// Close file errors we don't handle :) at all.
_ = devnullR.Close()
_ = devnullW.Close()
} }
} }
@@ -49,8 +61,52 @@ func (c *MyConfig) CleanZombies() {
r := syscall.Rusage{} r := syscall.Rusage{}
for { for {
_, _ = syscall.Wait4(-1, nil, 0, &r) pid, _ := syscall.Wait4(-1, nil, syscall.WNOHANG, &r)
if pid > 0 {
continue
}
time.Sleep(1 * time.Minute) time.Sleep(1 * time.Minute)
} }
} }
// RunProcess runs given command and returns contents of command stdout. On error prints error on stderr and returns
// empty syting.
func RunProcess(command []string) string {
var (
cmd *exec.Cmd
stdout, stderr bytes.Buffer
)
switch len(command) {
case 1:
cmd = exec.Command(command[0], "") //nolint: gosec
default:
cmd = exec.Command(command[0], command[1:]...) //nolint: gosec
}
cmd.Dir = "/"
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
if stdout.String() != "" {
log.Printf("Unable to run '%s': %s, %s", strings.Join(command, " "), err, stdout.String())
} else {
log.Printf("Unable to run '%s': %s", strings.Join(command, " "), err)
}
return ""
}
if stderr.String() != "" {
log.Printf("%s: %s", strings.Join(command, " "), stderr.String())
}
return strings.TrimRight(stdout.String(), "\n")
}
/* vim: set ft=go noet ai ts=4 sw=4 sts=4: */

View File

@@ -51,17 +51,11 @@ func (c *MyConfig) ParseStdin() {
continue continue
} }
for i := 0; i < len(buf); i++ { buf = strings.TrimLeftFunc(buf, func(r rune) bool {
if strings.HasPrefix(buf, "{") { return r != '{'
break })
}
buf = buf[1:]
}
if len(buf) == 0 {
log.Print("String from stdin has zero length, skipping")
if !strings.HasPrefix(buf, "{") {
continue continue
} }
@@ -116,18 +110,24 @@ func (c *MyConfig) ParseStdin() {
break break
} }
case app.Name != "" && e.Name == app.Name: case app.Name != "" && e.Name == app.Name:
prg := append([]string{}, app.Cmd) prg := append([]string{}, app.Cmd)
prg = append(prg, app.Args...) prg = append(prg, app.Args...)
c.Channels.RunChan <- prg c.Channels.RunChan <- prg
break
case app.Instance != "" && e.Instance == app.Instance: case app.Instance != "" && e.Instance == app.Instance:
prg := append([]string{}, app.Cmd) prg := append([]string{}, app.Cmd)
prg = append(prg, app.Args...) prg = append(prg, app.Args...)
c.Channels.RunChan <- prg c.Channels.RunChan <- prg
break
} }
} }
} }
} }
/* vim: set ft=go noet ai ts=4 sw=4 sts=4: */

View File

@@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"net" "net"
"os" "os"
"strings"
"time" "time"
) )
@@ -11,64 +12,83 @@ import (
func (c *MyConfig) UpdateVPNStatus() { func (c *MyConfig) UpdateVPNStatus() {
var ( var (
vpnCStatus string vpnCStatus string
tcpCheck string
vpnCheck string vpnCheck string
b strings.Builder
InitialDelay = 100 * time.Millisecond
LoopIterationDelay = 3 * time.Second
Delay = InitialDelay
ticker = time.NewTicker(Delay)
) )
for { for range ticker.C {
if Delay == InitialDelay {
Delay = LoopIterationDelay
ticker.Reset(Delay)
}
if c.VPNFileCheck() { if c.VPNFileCheck() {
if c.Vpn.UpColor == "" { if c.Vpn.UpColor == "" {
vpnCheck = `⍋` b.WriteRune('⍋')
} else { } else {
vpnCheck = fmt.Sprintf(`<span foreground="%s">⍋</span>`, c.Vpn.UpColor) b.WriteString("<span foreground=\"")
b.WriteString(c.Vpn.UpColor)
b.WriteString("\">⍋</span>")
} }
} else { } else {
if c.Vpn.DownColor == "" { if c.Vpn.DownColor == "" {
vpnCheck = `⍒` b.WriteRune('⍒')
} else { } else {
vpnCheck = fmt.Sprintf(`<span foreground="%s">⍒</span>`, c.Vpn.DownColor) b.WriteString("<span foreground=\"")
b.WriteString(c.Vpn.DownColor)
b.WriteString("\">⍒</span>")
} }
} }
vpnCheck = b.String()
b.Reset()
if c.Vpn.TCPCheck.Enabled { if c.Vpn.TCPCheck.Enabled {
if c.VPNTCPCheck() { if c.VPNTCPCheck() {
if c.Vpn.UpColor == "" { if c.Vpn.UpColor == "" {
tcpCheck = `✔` b.WriteRune('✔')
} else { } else {
tcpCheck = fmt.Sprintf(`<span foreground="%s">✔</span>`, c.Vpn.UpColor) b.WriteString("<span foreground=\"")
b.WriteString(c.Vpn.UpColor)
b.WriteString("\">✔</span>")
} }
} else { } else {
if c.Vpn.DownColor == "" { if c.Vpn.DownColor == "" {
tcpCheck = `✘` b.WriteRune('✘')
} else { } else {
tcpCheck = fmt.Sprintf(`<span foreground="%s">✘</span>`, c.Vpn.DownColor) b.WriteString("<span foreground=\"")
b.WriteString(c.Vpn.DownColor)
b.WriteString("\">✘</span>")
} }
} }
vpnCStatus = fmt.Sprintf("VPN:%s:%s", vpnCheck, tcpCheck) vpnCStatus = "VPN:" + vpnCheck + ":" + b.String()
} else { } else {
vpnCStatus = fmt.Sprintf("VPN:%s", vpnCheck) vpnCStatus = "VPN:" + vpnCheck
} }
if c.Values.VPNStatus != vpnCStatus { if c.Values.VPNStatus != vpnCStatus {
c.Values.VPNStatus = vpnCStatus c.Values.VPNStatus = vpnCStatus
c.Channels.UpdateReady <- true c.Channels.UpdateReady <- true
} }
time.Sleep(3 * time.Second)
} }
} }
// VPNTCPCheck intended to check arbitrary service inside vpn segment, to indicate that openvpn sevice not stoned. // VPNTCPCheck intended to check arbitrary service inside vpn segment, to indicate that openvpn service not stoned.
func (c *MyConfig) VPNTCPCheck() bool { func (c *MyConfig) VPNTCPCheck() bool {
conn, err := net.DialTimeout( conn, err := net.DialTimeout( //nolint: noctx
"tcp", "tcp",
fmt.Sprintf("%s:%d", c.Vpn.TCPCheck.Host, c.Vpn.TCPCheck.Port), fmt.Sprintf("%s:%d", c.Vpn.TCPCheck.Host, c.Vpn.TCPCheck.Port), //nolint: hostport
time.Second*time.Duration(c.Vpn.TCPCheck.Timeout), time.Second*time.Duration(c.Vpn.TCPCheck.Timeout),
) )
if err == nil { if err == nil {
_ = conn.Close() _ = conn.Close()
return true return true
} }
@@ -92,3 +112,5 @@ func (c *MyConfig) VPNFileCheck() bool {
return true return true
} }
/* vim: set ft=go noet ai ts=4 sw=4 sts=4: */

26
vendor/github.com/adrg/xdg/README.md generated vendored
View File

@@ -41,8 +41,9 @@ Provides an implementation of the [XDG Base Directory Specification](https://spe
The specification defines a set of standard paths for storing application files, The specification defines a set of standard paths for storing application files,
including data and configuration files. For portability and flexibility reasons, including data and configuration files. For portability and flexibility reasons,
applications should use the XDG defined locations instead of hardcoding paths. applications should use the XDG defined locations instead of hardcoding paths.
The package also includes the locations of well known [user directories](https://wiki.archlinux.org/index.php/XDG_user_directories), as well as
other common directories such as fonts and applications. The package also includes the locations of well known [user directories](https://wiki.archlinux.org/index.php/XDG_user_directories),
support for the non-standard `XDG_BIN_HOME` directory, as well as other common directories such as fonts and applications.
The current implementation supports **most flavors of Unix**, **Windows**, **macOS** and **Plan 9**. The current implementation supports **most flavors of Unix**, **Windows**, **macOS** and **Plan 9**.
On Windows, where XDG environment variables are not usually set, the package uses [Known Folders](https://docs.microsoft.com/en-us/windows/win32/shell/known-folders) On Windows, where XDG environment variables are not usually set, the package uses [Known Folders](https://docs.microsoft.com/en-us/windows/win32/shell/known-folders)
@@ -71,14 +72,15 @@ Sensible fallback locations are used for the folders which are not set.
<br/> <br/>
| <a href="#xdg-base-directory"><img width="400" height="0"></a> | <a href="#xdg-base-directory"><img width="500" height="0"></a><p>Unix</p> | <a href="#xdg-base-directory"><img width="600" height="0"></a><p>macOS</p> | <a href="#xdg-base-directory"><img width="500" height="0"></a><p>Plan 9</p> | | <a href="#xdg-base-directory"><img width="400" height="0"></a> | <a href="#xdg-base-directory"><img width="500" height="0"></a><p>Unix</p> | <a href="#xdg-base-directory"><img width="600" height="0"></a><p>macOS</p> | <a href="#xdg-base-directory"><img width="500" height="0"></a><p>Plan 9</p> |
| :------------------------------------------------------------: | :-----------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------: | | :------------------------------------------------------------: | :-----------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------: |
| <kbd><b>XDG_DATA_HOME</b></kbd> | <kbd>~/.local/share</kbd> | <kbd>~/Library/Application&nbsp;Support</kbd> | <kbd>$home/lib</kbd> | | <kbd><b>XDG_DATA_HOME</b></kbd> | <kbd>~/.local/share</kbd> | <kbd>~/Library/Application&nbsp;Support</kbd> | <kbd>$home/lib</kbd> |
| <kbd><b>XDG_DATA_DIRS</b></kbd> | <kbd>/usr/local/share</kbd><br/><kbd>/usr/share</kbd> | <kbd>/Library/Application&nbsp;Support</kbd> | <kbd>/lib</kbd> | | <kbd><b>XDG_DATA_DIRS</b></kbd> | <kbd>/usr/local/share</kbd><br/><kbd>/usr/share</kbd> | <kbd>/Library/Application&nbsp;Support</kbd><kbd>~/.local/share</kbd> | <kbd>/lib</kbd> |
| <kbd><b>XDG_CONFIG_HOME</b></kbd> | <kbd>~/.config</kbd> | <kbd>~/Library/Application&nbsp;Support</kbd> | <kbd>$home/lib</kbd> | | <kbd><b>XDG_CONFIG_HOME</b></kbd> | <kbd>~/.config</kbd> | <kbd>~/Library/Application&nbsp;Support</kbd> | <kbd>$home/lib</kbd> |
| <kbd><b>XDG_CONFIG_DIRS</b></kbd> | <kbd>/etc/xdg</kbd> | <kbd>~/Library/Preferences</kbd><br/><kbd>/Library/Application&nbsp;Support</kbd><br/><kbd>/Library/Preferences</kbd> | <kbd>/lib</kbd> | | <kbd><b>XDG_CONFIG_DIRS</b></kbd> | <kbd>/etc/xdg</kbd> | <kbd>~/Library/Preferences</kbd><br/><kbd>/Library/Application&nbsp;Support</kbd><br/><kbd>/Library/Preferences</kbd><br/><kbd>&#126;/.config</kbd> | <kbd>/lib</kbd> |
| <kbd><b>XDG_STATE_HOME</b></kbd> | <kbd>~/.local/state</kbd> | <kbd>~/Library/Application&nbsp;Support</kbd> | <kbd>$home/lib/state</kbd> | | <kbd><b>XDG_STATE_HOME</b></kbd> | <kbd>~/.local/state</kbd> | <kbd>~/Library/Application&nbsp;Support</kbd> | <kbd>$home/lib/state</kbd> |
| <kbd><b>XDG_CACHE_HOME</b></kbd> | <kbd>~/.cache</kbd> | <kbd>~/Library/Caches</kbd> | <kbd>$home/lib/cache</kbd> | | <kbd><b>XDG_CACHE_HOME</b></kbd> | <kbd>~/.cache</kbd> | <kbd>~/Library/Caches</kbd> | <kbd>$home/lib/cache</kbd> |
| <kbd><b>XDG_RUNTIME_DIR</b></kbd> | <kbd>/run/user/UID</kbd> | <kbd>~/Library/Application&nbsp;Support</kbd> | <kbd>/tmp</kbd> | | <kbd><b>XDG_RUNTIME_DIR</b></kbd> | <kbd>/run/user/$UID</kbd> | <kbd>~/Library/Application&nbsp;Support</kbd> | <kbd>/tmp</kbd> |
| <kbd><b>XDG_BIN_HOME</b></kbd> | <kbd>~/.local/bin</kbd> | <kbd>~/.local/bin</kbd> | <kbd>$home/bin</kbd> |
</details> </details>
@@ -95,6 +97,7 @@ Sensible fallback locations are used for the folders which are not set.
| <kbd><b>XDG_STATE_HOME</b></kbd> | <kbd>LocalAppData</kbd> | <kbd>%LOCALAPPDATA%</kbd> | | <kbd><b>XDG_STATE_HOME</b></kbd> | <kbd>LocalAppData</kbd> | <kbd>%LOCALAPPDATA%</kbd> |
| <kbd><b>XDG_CACHE_HOME</b></kbd> | <kbd>LocalAppData\cache</kbd> | <kbd>%LOCALAPPDATA%\cache</kbd> | | <kbd><b>XDG_CACHE_HOME</b></kbd> | <kbd>LocalAppData\cache</kbd> | <kbd>%LOCALAPPDATA%\cache</kbd> |
| <kbd><b>XDG_RUNTIME_DIR</b></kbd> | <kbd>LocalAppData</kbd> | <kbd>%LOCALAPPDATA%</kbd> | | <kbd><b>XDG_RUNTIME_DIR</b></kbd> | <kbd>LocalAppData</kbd> | <kbd>%LOCALAPPDATA%</kbd> |
| <kbd><b>XDG_BIN_HOME</b></kbd> | <kbd>UserProgramFiles</kbd> | <kbd>%LOCALAPPDATA%\Programs</kbd> |
</details> </details>
@@ -164,9 +167,9 @@ as shown in the following tables.
<br/> <br/>
| <a href="#other-directories"><img width="400" height="0"></a> | <a href="#other-directories"><img width="300" height="0"></a><p>Known&nbsp;Folder(s)</p> | <a href="#other-directories"><img width="1300" height="0"></a><p>Fallback(s)</p> | | <a href="#other-directories"><img width="400" height="0"></a> | <a href="#other-directories"><img width="300" height="0"></a><p>Known&nbsp;Folder(s)</p> | <a href="#other-directories"><img width="1300" height="0"></a><p>Fallback(s)</p> |
| :-----------------------------------------------------------: | :--------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------: | | :-----------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
| <kbd><b>Home</b></kbd> | <kbd>Profile</kbd> | <kbd>%USERPROFILE%</kbd> | | <kbd><b>Home</b></kbd> | <kbd>Profile</kbd> | <kbd>%USERPROFILE%</kbd> |
| <kbd><b>Applications</b></kbd> | <kbd>Programs</kbd><br/><kbd>CommonPrograms</kbd> | <kbd>%APPDATA%\Microsoft\Windows\Start&nbsp;Menu\Programs</kbd><br/><kbd>%ProgramData%\Microsoft\Windows\Start&nbsp;Menu\Programs</kbd> | | <kbd><b>Applications</b></kbd> | <kbd>Programs</kbd><br/><kbd>CommonPrograms</kbd> <br/><kbd>ProgramFiles</kbd><br/><kbd>ProgramFilesCommon</kbd><br/><kbd>UserProgramFiles</kbd><br/><kbd>UserProgramFilesCommon</kbd> | <kbd>%APPDATA%\Microsoft\Windows\Start&nbsp;Menu\Programs</kbd><br/><kbd>%ProgramData%\Microsoft\Windows\Start&nbsp;Menu\Programs</kbd><br/><kbd>%ProgramFiles%</kbd><br/><kbd>%ProgramFiles%\Common Files</kbd><br/><kbd>%LOCALAPPDATA%\Programs</kbd><br/><kbd>%LOCALAPPDATA%\Programs\Common</kbd>|
| <kbd><b>Fonts</b></kbd> | <kbd>Fonts</kbd> | <kbd>%SystemRoot%\Fonts</kbd><br/><kbd>%LOCALAPPDATA%\Microsoft\Windows\Fonts</kbd> | | <kbd><b>Fonts</b></kbd> | <kbd>Fonts</kbd> | <kbd>%SystemRoot%\Fonts</kbd><br/><kbd>%LOCALAPPDATA%\Microsoft\Windows\Fonts</kbd> |
</details> </details>
@@ -193,6 +196,7 @@ func main() {
log.Println("Home state directory:", xdg.StateHome) log.Println("Home state directory:", xdg.StateHome)
log.Println("Cache directory:", xdg.CacheHome) log.Println("Cache directory:", xdg.CacheHome)
log.Println("Runtime directory:", xdg.RuntimeDir) log.Println("Runtime directory:", xdg.RuntimeDir)
log.Println("Home binaries directory:", xdg.BinHome)
// Other common directories. // Other common directories.
log.Println("Home directory:", xdg.Home) log.Println("Home directory:", xdg.Home)
@@ -203,6 +207,9 @@ func main() {
// ConfigFile takes one parameter which must contain the name of the file, // ConfigFile takes one parameter which must contain the name of the file,
// but it can also contain a set of parent directories. If the directories // but it can also contain a set of parent directories. If the directories
// don't exist, they will be created relative to the base config directory. // don't exist, they will be created relative to the base config directory.
// It is recommended for files to be saved inside an application directory
// relative to the base directory rather than directly inside the base
// directory (e.g. `appname/config.yaml` instead of `appname-config.yaml`).
configFilePath, err := xdg.ConfigFile("appname/config.yaml") configFilePath, err := xdg.ConfigFile("appname/config.yaml")
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
@@ -277,7 +284,8 @@ See [CONTRIBUTING.MD](CONTRIBUTING.md).
[djdv](https://github.com/djdv), [djdv](https://github.com/djdv),
[rrjjvv](https://github.com/rrjjvv), [rrjjvv](https://github.com/rrjjvv),
[GreyXor](https://github.com/GreyXor), [GreyXor](https://github.com/GreyXor),
[Rican7](https://github.com/Rican7). [Rican7](https://github.com/Rican7),
[nothub](https://github.com/nothub).
## References ## References

View File

@@ -1,6 +1,10 @@
package xdg package xdg
import "github.com/adrg/xdg/internal/pathutil" import (
"os"
"github.com/adrg/xdg/internal/pathutil"
)
// XDG Base Directory environment variables. // XDG Base Directory environment variables.
const ( const (
@@ -11,6 +15,9 @@ const (
envStateHome = "XDG_STATE_HOME" envStateHome = "XDG_STATE_HOME"
envCacheHome = "XDG_CACHE_HOME" envCacheHome = "XDG_CACHE_HOME"
envRuntimeDir = "XDG_RUNTIME_DIR" envRuntimeDir = "XDG_RUNTIME_DIR"
// Non-standard.
envBinHome = "XDG_BIN_HOME"
) )
type baseDirectories struct { type baseDirectories struct {
@@ -22,7 +29,8 @@ type baseDirectories struct {
cacheHome string cacheHome string
runtime string runtime string
// Non-standard directories. // Non-standard.
binHome string
fonts []string fonts []string
applications []string applications []string
} }
@@ -44,7 +52,13 @@ func (bd baseDirectories) cacheFile(relPath string) (string, error) {
} }
func (bd baseDirectories) runtimeFile(relPath string) (string, error) { func (bd baseDirectories) runtimeFile(relPath string) (string, error) {
return pathutil.Create(relPath, []string{bd.runtime}) var paths []string
for _, p := range pathutil.Unique([]string{bd.runtime, os.TempDir()}) {
if pathutil.Exists(p) {
paths = append(paths, p)
}
}
return pathutil.Create(relPath, paths)
} }
func (bd baseDirectories) searchDataFile(relPath string) (string, error) { func (bd baseDirectories) searchDataFile(relPath string) (string, error) {
@@ -64,5 +78,5 @@ func (bd baseDirectories) searchCacheFile(relPath string) (string, error) {
} }
func (bd baseDirectories) searchRuntimeFile(relPath string) (string, error) { func (bd baseDirectories) searchRuntimeFile(relPath string) (string, error) {
return pathutil.Search(relPath, []string{bd.runtime}) return pathutil.Search(relPath, pathutil.Unique([]string{bd.runtime, os.TempDir()}))
} }

8
vendor/github.com/adrg/xdg/doc.go generated vendored
View File

@@ -16,9 +16,10 @@ The current implementation supports most flavors of Unix, Windows, Mac OS and Pl
For more information regarding the Windows Known Folders see: For more information regarding the Windows Known Folders see:
https://docs.microsoft.com/en-us/windows/win32/shell/known-folders https://docs.microsoft.com/en-us/windows/win32/shell/known-folders
Usage # Usage
XDG Base Directory XDG Base Directory
package main package main
import ( import (
@@ -36,6 +37,7 @@ XDG Base Directory
log.Println("Home state directory:", xdg.StateHome) log.Println("Home state directory:", xdg.StateHome)
log.Println("Cache directory:", xdg.CacheHome) log.Println("Cache directory:", xdg.CacheHome)
log.Println("Runtime directory:", xdg.RuntimeDir) log.Println("Runtime directory:", xdg.RuntimeDir)
log.Println("Home binaries directory:", xdg.BinHome)
// Other common directories. // Other common directories.
log.Println("Home directory:", xdg.Home) log.Println("Home directory:", xdg.Home)
@@ -46,6 +48,9 @@ XDG Base Directory
// ConfigFile takes one parameter which must contain the name of the file, // ConfigFile takes one parameter which must contain the name of the file,
// but it can also contain a set of parent directories. If the directories // but it can also contain a set of parent directories. If the directories
// don't exist, they will be created relative to the base config directory. // don't exist, they will be created relative to the base config directory.
// It is recommended for files to be saved inside an application directory
// relative to the base directory rather than directly inside the base
// directory (e.g. `appname/config.yaml` instead of `appname-config.yaml`).
configFilePath, err := xdg.ConfigFile("appname/config.yaml") configFilePath, err := xdg.ConfigFile("appname/config.yaml")
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
@@ -76,6 +81,7 @@ XDG Base Directory
} }
XDG user directories XDG user directories
package main package main
import ( import (

View File

@@ -4,7 +4,6 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings"
) )
// Unique eliminates the duplicate paths from the provided slice and returns // Unique eliminates the duplicate paths from the provided slice and returns
@@ -52,7 +51,6 @@ func First(paths []string) string {
// relative to the selected parent path. // relative to the selected parent path.
func Create(name string, paths []string) (string, error) { func Create(name string, paths []string) (string, error) {
searchedPaths := make([]string, 0, len(paths)) searchedPaths := make([]string, 0, len(paths))
for _, p := range paths { for _, p := range paths {
p = filepath.Join(p, name) p = filepath.Join(p, name)
@@ -67,8 +65,8 @@ func Create(name string, paths []string) (string, error) {
searchedPaths = append(searchedPaths, dir) searchedPaths = append(searchedPaths, dir)
} }
return "", fmt.Errorf("could not create any of the following paths: %s", return "", fmt.Errorf("could not create any of the following paths: %v",
strings.Join(searchedPaths, ", ")) searchedPaths)
} }
// Search searches for the file with the specified `name` in the provided // Search searches for the file with the specified `name` in the provided
@@ -76,7 +74,6 @@ func Create(name string, paths []string) (string, error) {
// but it can also contain a set of parent directories. // but it can also contain a set of parent directories.
func Search(name string, paths []string) (string, error) { func Search(name string, paths []string) (string, error) {
searchedPaths := make([]string, 0, len(paths)) searchedPaths := make([]string, 0, len(paths))
for _, p := range paths { for _, p := range paths {
p = filepath.Join(p, name) p = filepath.Join(p, name)
if Exists(p) { if Exists(p) {
@@ -86,8 +83,8 @@ func Search(name string, paths []string) (string, error) {
searchedPaths = append(searchedPaths, filepath.Dir(p)) searchedPaths = append(searchedPaths, filepath.Dir(p))
} }
return "", fmt.Errorf("could not locate `%s` in any of the following paths: %s", return "", fmt.Errorf("could not locate `%s` in any of the following paths: %v",
filepath.Base(name), strings.Join(searchedPaths, ", ")) filepath.Base(name), searchedPaths)
} }
// EnvPath returns the value of the environment variable with the specified // EnvPath returns the value of the environment variable with the specified

View File

@@ -18,18 +18,24 @@ func initBaseDirs(home string) {
// Initialize standard directories. // Initialize standard directories.
baseDirs.dataHome = pathutil.EnvPath(envDataHome, homeAppSupport) baseDirs.dataHome = pathutil.EnvPath(envDataHome, homeAppSupport)
baseDirs.data = pathutil.EnvPathList(envDataDirs, rootAppSupport) baseDirs.data = pathutil.EnvPathList(envDataDirs,
rootAppSupport,
filepath.Join(home, ".local", "share"),
)
baseDirs.configHome = pathutil.EnvPath(envConfigHome, homeAppSupport) baseDirs.configHome = pathutil.EnvPath(envConfigHome, homeAppSupport)
baseDirs.config = pathutil.EnvPathList(envConfigDirs, baseDirs.config = pathutil.EnvPathList(envConfigDirs,
filepath.Join(home, "Library", "Preferences"), filepath.Join(home, "Library", "Preferences"),
rootAppSupport, rootAppSupport,
"/Library/Preferences", "/Library/Preferences",
filepath.Join(home, ".config"),
) )
baseDirs.stateHome = pathutil.EnvPath(envStateHome, homeAppSupport) baseDirs.stateHome = pathutil.EnvPath(envStateHome, homeAppSupport)
baseDirs.cacheHome = pathutil.EnvPath(envCacheHome, filepath.Join(home, "Library", "Caches")) baseDirs.cacheHome = pathutil.EnvPath(envCacheHome, filepath.Join(home, "Library", "Caches"))
baseDirs.runtime = pathutil.EnvPath(envRuntimeDir, homeAppSupport) baseDirs.runtime = pathutil.EnvPath(envRuntimeDir, homeAppSupport)
// Initialize non-standard directories. // Initialize non-standard directories.
baseDirs.binHome = pathutil.EnvPath(envBinHome, filepath.Join(home, ".local", "bin"))
baseDirs.applications = []string{ baseDirs.applications = []string{
"/Applications", "/Applications",
} }

View File

@@ -26,6 +26,8 @@ func initBaseDirs(home string) {
baseDirs.runtime = pathutil.EnvPath(envRuntimeDir, "/tmp") baseDirs.runtime = pathutil.EnvPath(envRuntimeDir, "/tmp")
// Initialize non-standard directories. // Initialize non-standard directories.
baseDirs.binHome = pathutil.EnvPath(envBinHome, filepath.Join(home, "bin"))
baseDirs.applications = []string{ baseDirs.applications = []string{
filepath.Join(home, "bin"), filepath.Join(home, "bin"),
"/bin", "/bin",

View File

@@ -27,6 +27,8 @@ func initBaseDirs(home string) {
baseDirs.runtime = pathutil.EnvPath(envRuntimeDir, filepath.Join("/run/user", strconv.Itoa(os.Getuid()))) baseDirs.runtime = pathutil.EnvPath(envRuntimeDir, filepath.Join("/run/user", strconv.Itoa(os.Getuid())))
// Initialize non-standard directories. // Initialize non-standard directories.
baseDirs.binHome = pathutil.EnvPath(envBinHome, filepath.Join(home, ".local", "bin"))
appDirs := []string{ appDirs := []string{
filepath.Join(baseDirs.dataHome, "applications"), filepath.Join(baseDirs.dataHome, "applications"),
filepath.Join(home, ".local/share/applications"), filepath.Join(home, ".local/share/applications"),

View File

@@ -25,10 +25,17 @@ func initBaseDirs(home string, kf *knownFolders) {
baseDirs.runtime = pathutil.EnvPath(envRuntimeDir, kf.localAppData) baseDirs.runtime = pathutil.EnvPath(envRuntimeDir, kf.localAppData)
// Initialize non-standard directories. // Initialize non-standard directories.
baseDirs.binHome = pathutil.EnvPath(envBinHome, kf.userProgramFiles)
baseDirs.applications = []string{ baseDirs.applications = []string{
kf.programs, kf.programs,
kf.commonPrograms, kf.commonPrograms,
kf.programFiles,
kf.programFilesCommon,
kf.userProgramFiles,
kf.userProgramFilesCommon,
} }
baseDirs.fonts = []string{ baseDirs.fonts = []string{
kf.fonts, kf.fonts,
filepath.Join(kf.localAppData, "Microsoft", "Windows", "Fonts"), filepath.Join(kf.localAppData, "Microsoft", "Windows", "Fonts"),
@@ -65,6 +72,10 @@ type knownFolders struct {
fonts string fonts string
programs string programs string
commonPrograms string commonPrograms string
programFiles string
programFilesCommon string
userProgramFiles string
userProgramFilesCommon string
} }
func initKnownFolders(home string) *knownFolders { func initKnownFolders(home string) *knownFolders {
@@ -156,6 +167,30 @@ func initKnownFolders(home string) *knownFolders {
nil, nil,
[]string{filepath.Join(kf.programData, "Microsoft", "Windows", "Start Menu", "Programs")}, []string{filepath.Join(kf.programData, "Microsoft", "Windows", "Start Menu", "Programs")},
) )
kf.programFiles = pathutil.KnownFolder(
windows.FOLDERID_ProgramFiles,
[]string{"ProgramFiles"},
[]string{filepath.Join(kf.systemDrive, "Program Files")},
)
kf.programFilesCommon = pathutil.KnownFolder(
windows.FOLDERID_ProgramFilesCommon,
nil,
[]string{filepath.Join(kf.programFiles, "Common Files")},
)
kf.userProgramFiles = pathutil.KnownFolder(
windows.FOLDERID_UserProgramFiles,
nil,
[]string{
filepath.Join(kf.localAppData, "Programs"),
},
)
kf.userProgramFilesCommon = pathutil.KnownFolder(
windows.FOLDERID_UserProgramFilesCommon,
nil,
[]string{
filepath.Join(kf.userProgramFiles, "Common"),
},
)
return kf return kf
} }

19
vendor/github.com/adrg/xdg/xdg.go generated vendored
View File

@@ -67,6 +67,12 @@ var (
// swapped out to disk. // swapped out to disk.
RuntimeDir string RuntimeDir string
// BinHome defines the base directory relative to which user-specific
// binary files should be written. This directory is defined by
// the non-standard $XDG_BIN_HOME environment variable. If the variable is
// not set, a default equal to $HOME/.local/bin should be used.
BinHome string
// UserDirs defines the locations of well known user directories. // UserDirs defines the locations of well known user directories.
UserDirs UserDirectories UserDirs UserDirectories
@@ -104,6 +110,7 @@ func Reload() {
RuntimeDir = baseDirs.runtime RuntimeDir = baseDirs.runtime
// Set non-standard directories. // Set non-standard directories.
BinHome = baseDirs.binHome
FontDirs = baseDirs.fonts FontDirs = baseDirs.fonts
ApplicationDirs = baseDirs.applications ApplicationDirs = baseDirs.applications
} }
@@ -154,8 +161,9 @@ func CacheFile(relPath string) (string, error) {
// The relPath parameter must contain the name of the runtime file, and // The relPath parameter must contain the name of the runtime file, and
// optionally, a set of parent directories (e.g. appname/app.pid). // optionally, a set of parent directories (e.g. appname/app.pid).
// If the specified directories do not exist, they will be created relative // If the specified directories do not exist, they will be created relative
// to the base runtime directory. On failure, an error containing the // to the base runtime directory. If the base runtime directory does not exist,
// attempted paths is returned. // the operating system's temporary directory is used as a fallback. On failure,
// an error containing the attempted paths is returned.
func RuntimeFile(relPath string) (string, error) { func RuntimeFile(relPath string) (string, error) {
return baseDirs.runtimeFile(relPath) return baseDirs.runtimeFile(relPath)
} }
@@ -194,8 +202,11 @@ func SearchCacheFile(relPath string) (string, error) {
// SearchRuntimeFile searches for the specified file in the runtime search path. // SearchRuntimeFile searches for the specified file in the runtime search path.
// The relPath parameter must contain the name of the runtime file, and // The relPath parameter must contain the name of the runtime file, and
// optionally, a set of parent directories (e.g. appname/app.pid). If the // optionally, a set of parent directories (e.g. appname/app.pid). The runtime
// file cannot be found, an error specifying the searched path is returned. // file is also searched in the operating system's temporary directory in order
// to cover cases in which the runtime base directory does not exist or is not
// accessible. If the file cannot be found, an error specifying the searched
// paths is returned.
func SearchRuntimeFile(relPath string) (string, error) { func SearchRuntimeFile(relPath string) (string, error) {
return baseDirs.searchRuntimeFile(relPath) return baseDirs.searchRuntimeFile(relPath)
} }

View File

@@ -20,10 +20,9 @@ issues:
linters: linters:
enable: enable:
- bodyclose - bodyclose
- exportloopref - copyloopvar
- gofumpt - gofumpt
- goimports - goimports
- gosec
- gosimple - gosimple
- govet - govet
- ineffassign - ineffassign
@@ -39,6 +38,5 @@ output:
- format: colored-line-number - format: colored-line-number
print-issued-lines: true print-issued-lines: true
print-linter-name: true print-linter-name: true
uniq-by-line: true
path-prefix: "" path-prefix: ""
sort-results: true sort-results: true

View File

@@ -12,7 +12,7 @@ repos:
- id: end-of-file-fixer - id: end-of-file-fixer
- id: trailing-whitespace - id: trailing-whitespace
- repo: https://github.com/golangci/golangci-lint - repo: https://github.com/golangci/golangci-lint
rev: v1.55.2 rev: v1.64.5
hooks: hooks:
- id: golangci-lint - id: golangci-lint
- repo: https://github.com/TekWizely/pre-commit-golang - repo: https://github.com/TekWizely/pre-commit-golang

View File

@@ -6,7 +6,7 @@ fmt:
@go list -f {{.Dir}} ./... | xargs -I{} gofmt -w -s {} @go list -f {{.Dir}} ./... | xargs -I{} gofmt -w -s {}
lint: lint:
@grep "^func " example_test.go | sort -c @grep "^func [a-zA-Z]" example_test.go | sort -c
@golangci-lint run @golangci-lint run
test: test:
@@ -16,7 +16,7 @@ test_coverage:
@go test -race -v $(GO_FLAGS) -count=1 -coverprofile=coverage.out -covermode=atomic $(GO_PKGS) @go test -race -v $(GO_FLAGS) -count=1 -coverprofile=coverage.out -covermode=atomic $(GO_PKGS)
test_ci: test_ci:
@TEST_ENV=ci go test -race -v $(GO_FLAGS) -count=1 $(GO_PKGS) @go test -race -v $(GO_FLAGS) -count=1 $(GO_PKGS)
mocks: mocks:
@go generate ./... @go generate ./...

View File

@@ -151,6 +151,7 @@ The provided NewLogger uses the standard library's log package.
### Metrics ### Metrics
Metrics may be collected from the execution of each job. Metrics may be collected from the execution of each job.
- [**Monitor**](https://pkg.go.dev/github.com/go-co-op/gocron/v2#Monitor): - [**Monitor**](https://pkg.go.dev/github.com/go-co-op/gocron/v2#Monitor):
- [**MonitorStatus**](https://pkg.go.dev/github.com/go-co-op/gocron/v2#MonitorStatus) (includes status and error (if any) of the Job)
A monitor can be used to collect metrics for each job from a scheduler. A monitor can be used to collect metrics for each job from a scheduler.
- Implementations: [go-co-op monitors](https://github.com/go-co-op?q=-monitor&type=all&language=&sort=) - Implementations: [go-co-op monitors](https://github.com/go-co-op?q=-monitor&type=all&language=&sort=)
(don't see what you need? request on slack to get a repo created to contribute it!) (don't see what you need? request on slack to get a repo created to contribute it!)
@@ -168,8 +169,20 @@ We appreciate the support for free and open source software!
This project is supported by: This project is supported by:
- [Jetbrains](https://www.jetbrains.com/?from=gocron) [Jetbrains](https://www.jetbrains.com/?from=gocron)
- [Sentry](https://sentry.io/welcome/)
![JetBrains logo](https://resources.jetbrains.com/storage/products/company/brand/logos/jetbrains.png)
[Sentry](https://sentry.io/welcome/)
<p align="left">
<p align="left">
<a href="https://sentry.io/?utm_source=github&utm_medium=logo" target="_blank">
<img src="https://sentry-brand.storage.googleapis.com/sentry-wordmark-dark-280x84.png" alt="Sentry" width="280" height="84" />
</a>
</p>
</p>
## Star History ## Star History

View File

@@ -9,6 +9,7 @@ var (
ErrDailyJobAtTimeNil = fmt.Errorf("gocron: DailyJob: atTime within atTimes must not be nil") ErrDailyJobAtTimeNil = fmt.Errorf("gocron: DailyJob: atTime within atTimes must not be nil")
ErrDailyJobAtTimesNil = fmt.Errorf("gocron: DailyJob: atTimes must not be nil") ErrDailyJobAtTimesNil = fmt.Errorf("gocron: DailyJob: atTimes must not be nil")
ErrDailyJobHours = fmt.Errorf("gocron: DailyJob: atTimes hours must be between 0 and 23 inclusive") ErrDailyJobHours = fmt.Errorf("gocron: DailyJob: atTimes hours must be between 0 and 23 inclusive")
ErrDailyJobZeroInterval = fmt.Errorf("gocron: DailyJob: interval must be greater than 0")
ErrDailyJobMinutesSeconds = fmt.Errorf("gocron: DailyJob: atTimes minutes and seconds must be between 0 and 59 inclusive") ErrDailyJobMinutesSeconds = fmt.Errorf("gocron: DailyJob: atTimes minutes and seconds must be between 0 and 59 inclusive")
ErrDurationJobIntervalZero = fmt.Errorf("gocron: DurationJob: time interval is 0") ErrDurationJobIntervalZero = fmt.Errorf("gocron: DurationJob: time interval is 0")
ErrDurationRandomJobMinMax = fmt.Errorf("gocron: DurationRandomJob: minimum duration must be less than maximum duration") ErrDurationRandomJobMinMax = fmt.Errorf("gocron: DurationRandomJob: minimum duration must be less than maximum duration")
@@ -20,6 +21,7 @@ var (
ErrMonthlyJobAtTimesNil = fmt.Errorf("gocron: MonthlyJob: atTimes must not be nil") ErrMonthlyJobAtTimesNil = fmt.Errorf("gocron: MonthlyJob: atTimes must not be nil")
ErrMonthlyJobDaysNil = fmt.Errorf("gocron: MonthlyJob: daysOfTheMonth must not be nil") ErrMonthlyJobDaysNil = fmt.Errorf("gocron: MonthlyJob: daysOfTheMonth must not be nil")
ErrMonthlyJobHours = fmt.Errorf("gocron: MonthlyJob: atTimes hours must be between 0 and 23 inclusive") ErrMonthlyJobHours = fmt.Errorf("gocron: MonthlyJob: atTimes hours must be between 0 and 23 inclusive")
ErrMonthlyJobZeroInterval = fmt.Errorf("gocron: MonthlyJob: interval must be greater than 0")
ErrMonthlyJobMinutesSeconds = fmt.Errorf("gocron: MonthlyJob: atTimes minutes and seconds must be between 0 and 59 inclusive") ErrMonthlyJobMinutesSeconds = fmt.Errorf("gocron: MonthlyJob: atTimes minutes and seconds must be between 0 and 59 inclusive")
ErrNewJobTaskNil = fmt.Errorf("gocron: NewJob: Task must not be nil") ErrNewJobTaskNil = fmt.Errorf("gocron: NewJob: Task must not be nil")
ErrNewJobTaskNotFunc = fmt.Errorf("gocron: NewJob: Task.Function must be of kind reflect.Func") ErrNewJobTaskNotFunc = fmt.Errorf("gocron: NewJob: Task.Function must be of kind reflect.Func")
@@ -33,9 +35,11 @@ var (
ErrWeeklyJobAtTimesNil = fmt.Errorf("gocron: WeeklyJob: atTimes must not be nil") ErrWeeklyJobAtTimesNil = fmt.Errorf("gocron: WeeklyJob: atTimes must not be nil")
ErrWeeklyJobDaysOfTheWeekNil = fmt.Errorf("gocron: WeeklyJob: daysOfTheWeek must not be nil") ErrWeeklyJobDaysOfTheWeekNil = fmt.Errorf("gocron: WeeklyJob: daysOfTheWeek must not be nil")
ErrWeeklyJobHours = fmt.Errorf("gocron: WeeklyJob: atTimes hours must be between 0 and 23 inclusive") ErrWeeklyJobHours = fmt.Errorf("gocron: WeeklyJob: atTimes hours must be between 0 and 23 inclusive")
ErrWeeklyJobZeroInterval = fmt.Errorf("gocron: WeeklyJob: interval must be greater than 0")
ErrWeeklyJobMinutesSeconds = fmt.Errorf("gocron: WeeklyJob: atTimes minutes and seconds must be between 0 and 59 inclusive") ErrWeeklyJobMinutesSeconds = fmt.Errorf("gocron: WeeklyJob: atTimes minutes and seconds must be between 0 and 59 inclusive")
ErrPanicRecovered = fmt.Errorf("gocron: panic recovered") ErrPanicRecovered = fmt.Errorf("gocron: panic recovered")
ErrWithClockNil = fmt.Errorf("gocron: WithClock: clock must not be nil") ErrWithClockNil = fmt.Errorf("gocron: WithClock: clock must not be nil")
ErrWithContextNil = fmt.Errorf("gocron: WithContext: context must not be nil")
ErrWithDistributedElectorNil = fmt.Errorf("gocron: WithDistributedElector: elector must not be nil") ErrWithDistributedElectorNil = fmt.Errorf("gocron: WithDistributedElector: elector must not be nil")
ErrWithDistributedLockerNil = fmt.Errorf("gocron: WithDistributedLocker: locker must not be nil") ErrWithDistributedLockerNil = fmt.Errorf("gocron: WithDistributedLocker: locker must not be nil")
ErrWithDistributedJobLockerNil = fmt.Errorf("gocron: WithDistributedJobLocker: locker must not be nil") ErrWithDistributedJobLockerNil = fmt.Errorf("gocron: WithDistributedJobLocker: locker must not be nil")

View File

@@ -31,8 +31,13 @@ type executor struct {
// used to request jobs from the scheduler // used to request jobs from the scheduler
jobOutRequest chan jobOutRequest jobOutRequest chan jobOutRequest
// sends out job needs to update the next runs
jobUpdateNextRuns chan uuid.UUID
// used by the executor to receive a stop signal from the scheduler // used by the executor to receive a stop signal from the scheduler
stopCh chan struct{} stopCh chan struct{}
// ensure that stop runs before the next call to start and only runs once
stopOnce *sync.Once
// the timeout value when stopping // the timeout value when stopping
stopTimeout time.Duration stopTimeout time.Duration
// used to signal that the executor has completed shutdown // used to signal that the executor has completed shutdown
@@ -49,6 +54,8 @@ type executor struct {
locker Locker locker Locker
// monitor for reporting metrics // monitor for reporting metrics
monitor Monitor monitor Monitor
// monitorStatus for reporting metrics
monitorStatus MonitorStatus
} }
type jobIn struct { type jobIn struct {
@@ -83,6 +90,7 @@ func (e *executor) start() {
// any other uses within the executor should create a context // any other uses within the executor should create a context
// using the executor context as parent. // using the executor context as parent.
e.ctx, e.cancel = context.WithCancel(context.Background()) e.ctx, e.cancel = context.WithCancel(context.Background())
e.stopOnce = &sync.Once{}
// the standardJobsWg tracks // the standardJobsWg tracks
standardJobsWg := &waitGroupWithMutex{} standardJobsWg := &waitGroupWithMutex{}
@@ -126,7 +134,7 @@ func (e *executor) start() {
// spin off into a goroutine to unblock the executor and // spin off into a goroutine to unblock the executor and
// allow for processing for more work // allow for processing for more work
go func() { go func(executorCtx context.Context) {
// make sure to cancel the above context per the docs // make sure to cancel the above context per the docs
// // Canceling this context releases resources associated with it, so code should // // Canceling this context releases resources associated with it, so code should
// // call cancel as soon as the operations running in this Context complete. // // call cancel as soon as the operations running in this Context complete.
@@ -206,8 +214,7 @@ func (e *executor) start() {
} }
} else { } else {
select { select {
case <-e.stopCh: case <-executorCtx.Done():
e.stop(standardJobsWg, singletonJobsWg, limitModeJobsWg)
return return
default: default:
} }
@@ -223,7 +230,7 @@ func (e *executor) start() {
}(*j) }(*j)
} }
} }
}() }(e.ctx)
case <-e.stopCh: case <-e.stopCh:
e.stop(standardJobsWg, singletonJobsWg, limitModeJobsWg) e.stop(standardJobsWg, singletonJobsWg, limitModeJobsWg)
return return
@@ -245,6 +252,14 @@ func (e *executor) sendOutForRescheduling(jIn *jobIn) {
jIn.shouldSendOut = false jIn.shouldSendOut = false
} }
func (e *executor) sendOutForNextRunUpdate(jIn *jobIn) {
select {
case e.jobUpdateNextRuns <- jIn.id:
case <-e.ctx.Done():
return
}
}
func (e *executor) limitModeRunner(name string, in chan jobIn, wg *waitGroupWithMutex, limitMode LimitMode, rescheduleLimiter chan struct{}) { func (e *executor) limitModeRunner(name string, in chan jobIn, wg *waitGroupWithMutex, limitMode LimitMode, rescheduleLimiter chan struct{}) {
e.logger.Debug("gocron: limitModeRunner starting", "name", name) e.logger.Debug("gocron: limitModeRunner starting", "name", name)
for { for {
@@ -368,27 +383,42 @@ func (e *executor) runJob(j internalJob, jIn jobIn) {
e.incrementJobCounter(j, Skip) e.incrementJobCounter(j, Skip)
return return
} }
} else if j.locker != nil { } else if !j.disabledLocker && j.locker != nil {
lock, err := j.locker.Lock(j.ctx, j.name) lock, err := j.locker.Lock(j.ctx, j.name)
if err != nil { if err != nil {
_ = callJobFuncWithParams(j.afterLockError, j.id, j.name, err) _ = callJobFuncWithParams(j.afterLockError, j.id, j.name, err)
e.sendOutForRescheduling(&jIn) e.sendOutForRescheduling(&jIn)
e.incrementJobCounter(j, Skip) e.incrementJobCounter(j, Skip)
e.sendOutForNextRunUpdate(&jIn)
return return
} }
defer func() { _ = lock.Unlock(j.ctx) }() defer func() { _ = lock.Unlock(j.ctx) }()
} else if e.locker != nil { } else if !j.disabledLocker && e.locker != nil {
lock, err := e.locker.Lock(j.ctx, j.name) lock, err := e.locker.Lock(j.ctx, j.name)
if err != nil { if err != nil {
_ = callJobFuncWithParams(j.afterLockError, j.id, j.name, err) _ = callJobFuncWithParams(j.afterLockError, j.id, j.name, err)
e.sendOutForRescheduling(&jIn) e.sendOutForRescheduling(&jIn)
e.incrementJobCounter(j, Skip) e.incrementJobCounter(j, Skip)
e.sendOutForNextRunUpdate(&jIn)
return return
} }
defer func() { _ = lock.Unlock(j.ctx) }() defer func() { _ = lock.Unlock(j.ctx) }()
} }
_ = callJobFuncWithParams(j.beforeJobRuns, j.id, j.name) _ = callJobFuncWithParams(j.beforeJobRuns, j.id, j.name)
err := callJobFuncWithParams(j.beforeJobRunsSkipIfBeforeFuncErrors, j.id, j.name)
if err != nil {
e.sendOutForRescheduling(&jIn)
select {
case e.jobsOutCompleted <- j.id:
case <-e.ctx.Done():
}
return
}
e.sendOutForRescheduling(&jIn) e.sendOutForRescheduling(&jIn)
select { select {
case e.jobsOutCompleted <- j.id: case e.jobsOutCompleted <- j.id:
@@ -396,14 +426,20 @@ func (e *executor) runJob(j internalJob, jIn jobIn) {
} }
startTime := time.Now() startTime := time.Now()
err := e.callJobWithRecover(j) if j.afterJobRunsWithPanic != nil {
err = e.callJobWithRecover(j)
} else {
err = callJobFuncWithParams(j.function, j.parameters...)
}
e.recordJobTiming(startTime, time.Now(), j) e.recordJobTiming(startTime, time.Now(), j)
if err != nil { if err != nil {
_ = callJobFuncWithParams(j.afterJobRunsWithError, j.id, j.name, err) _ = callJobFuncWithParams(j.afterJobRunsWithError, j.id, j.name, err)
e.incrementJobCounter(j, Fail) e.incrementJobCounter(j, Fail)
e.recordJobTimingWithStatus(startTime, time.Now(), j, Fail, err)
} else { } else {
_ = callJobFuncWithParams(j.afterJobRuns, j.id, j.name) _ = callJobFuncWithParams(j.afterJobRuns, j.id, j.name)
e.incrementJobCounter(j, Success) e.incrementJobCounter(j, Success)
e.recordJobTimingWithStatus(startTime, time.Now(), j, Success, nil)
} }
} }
@@ -426,6 +462,12 @@ func (e *executor) recordJobTiming(start time.Time, end time.Time, j internalJob
} }
} }
func (e *executor) recordJobTimingWithStatus(start time.Time, end time.Time, j internalJob, status JobStatus, err error) {
if e.monitorStatus != nil {
e.monitorStatus.RecordJobTimingWithStatus(start, end, j.id, j.name, j.tags, status, err)
}
}
func (e *executor) incrementJobCounter(j internalJob, status JobStatus) { func (e *executor) incrementJobCounter(j internalJob, status JobStatus) {
if e.monitor != nil { if e.monitor != nil {
e.monitor.IncrementJob(j.id, j.name, j.tags, status) e.monitor.IncrementJob(j.id, j.name, j.tags, status)
@@ -433,6 +475,7 @@ func (e *executor) incrementJobCounter(j internalJob, status JobStatus) {
} }
func (e *executor) stop(standardJobsWg, singletonJobsWg, limitModeJobsWg *waitGroupWithMutex) { func (e *executor) stop(standardJobsWg, singletonJobsWg, limitModeJobsWg *waitGroupWithMutex) {
e.stopOnce.Do(func() {
e.logger.Debug("gocron: stopping executor") e.logger.Debug("gocron: stopping executor")
// we've been asked to stop. This is either because the scheduler has been told // we've been asked to stop. This is either because the scheduler has been told
// to stop all jobs or the scheduler has been asked to completely shutdown. // to stop all jobs or the scheduler has been asked to completely shutdown.
@@ -515,4 +558,5 @@ func (e *executor) stop(standardJobsWg, singletonJobsWg, limitModeJobsWg *waitGr
if e.limitMode != nil { if e.limitMode != nil {
e.limitMode.started = false e.limitMode.started = false
} }
})
} }

View File

@@ -6,23 +6,25 @@ import (
"errors" "errors"
"fmt" "fmt"
"math/rand" "math/rand"
"slices"
"strings" "strings"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jonboulle/clockwork" "github.com/jonboulle/clockwork"
"github.com/robfig/cron/v3" "github.com/robfig/cron/v3"
"golang.org/x/exp/slices"
) )
// internalJob stores the information needed by the scheduler // internalJob stores the information needed by the scheduler
// to manage scheduling, starting and stopping the job // to manage scheduling, starting and stopping the job
type internalJob struct { type internalJob struct {
ctx context.Context ctx context.Context
parentCtx context.Context
cancel context.CancelFunc cancel context.CancelFunc
id uuid.UUID id uuid.UUID
name string name string
tags []string tags []string
cron Cron
jobSchedule jobSchedule
// as some jobs may queue up, it's possible to // as some jobs may queue up, it's possible to
@@ -42,9 +44,11 @@ type internalJob struct {
// event listeners // event listeners
afterJobRuns func(jobID uuid.UUID, jobName string) afterJobRuns func(jobID uuid.UUID, jobName string)
beforeJobRuns func(jobID uuid.UUID, jobName string) beforeJobRuns func(jobID uuid.UUID, jobName string)
beforeJobRunsSkipIfBeforeFuncErrors func(jobID uuid.UUID, jobName string) error
afterJobRunsWithError func(jobID uuid.UUID, jobName string, err error) afterJobRunsWithError func(jobID uuid.UUID, jobName string, err error)
afterJobRunsWithPanic func(jobID uuid.UUID, jobName string, recoverData any) afterJobRunsWithPanic func(jobID uuid.UUID, jobName string, recoverData any)
afterLockError func(jobID uuid.UUID, jobName string, err error) afterLockError func(jobID uuid.UUID, jobName string, err error)
disabledLocker bool
locker Locker locker Locker
} }
@@ -80,6 +84,10 @@ type task struct {
type Task func() task type Task func() task
// NewTask provides the job's task function and parameters. // NewTask provides the job's task function and parameters.
// If you set the first argument of your Task func to be a context.Context,
// gocron will pass in a context (either the default Job context, or one
// provided via WithContext) to the job and will cancel the context on shutdown.
// This allows you to listen for and handle cancellation within your job.
func NewTask(function any, parameters ...any) Task { func NewTask(function any, parameters ...any) Task {
return func() task { return func() task {
return task{ return task{
@@ -97,6 +105,20 @@ type limitRunsTo struct {
runCount uint runCount uint
} }
// -----------------------------------------------
// -----------------------------------------------
// --------------- Custom Cron -------------------
// -----------------------------------------------
// -----------------------------------------------
// Cron defines the interface that must be
// implemented to provide a custom cron implementation for
// the job. Pass in the implementation using the JobOption WithCronImplementation.
type Cron interface {
IsValid(crontab string, location *time.Location, now time.Time) error
Next(lastRun time.Time) time.Time
}
// ----------------------------------------------- // -----------------------------------------------
// ----------------------------------------------- // -----------------------------------------------
// --------------- Job Variants ------------------ // --------------- Job Variants ------------------
@@ -109,21 +131,29 @@ type JobDefinition interface {
setup(j *internalJob, l *time.Location, now time.Time) error setup(j *internalJob, l *time.Location, now time.Time) error
} }
var _ JobDefinition = (*cronJobDefinition)(nil) // Default cron implementation
type cronJobDefinition struct { func newDefaultCronImplementation(withSeconds bool) Cron {
crontab string return &defaultCron{
withSeconds: withSeconds,
}
}
var _ Cron = (*defaultCron)(nil)
type defaultCron struct {
cronSchedule cron.Schedule
withSeconds bool withSeconds bool
} }
func (c cronJobDefinition) setup(j *internalJob, location *time.Location, now time.Time) error { func (c *defaultCron) IsValid(crontab string, location *time.Location, now time.Time) error {
var withLocation string var withLocation string
if strings.HasPrefix(c.crontab, "TZ=") || strings.HasPrefix(c.crontab, "CRON_TZ=") { if strings.HasPrefix(crontab, "TZ=") || strings.HasPrefix(crontab, "CRON_TZ=") {
withLocation = c.crontab withLocation = crontab
} else { } else {
// since the user didn't provide a timezone default to the location // since the user didn't provide a timezone default to the location
// passed in by the scheduler. Default: time.Local // passed in by the scheduler. Default: time.Local
withLocation = fmt.Sprintf("CRON_TZ=%s %s", location.String(), c.crontab) withLocation = fmt.Sprintf("CRON_TZ=%s %s", location.String(), crontab)
} }
var ( var (
@@ -143,8 +173,32 @@ func (c cronJobDefinition) setup(j *internalJob, location *time.Location, now ti
if cronSchedule.Next(now).IsZero() { if cronSchedule.Next(now).IsZero() {
return ErrCronJobInvalid return ErrCronJobInvalid
} }
c.cronSchedule = cronSchedule
return nil
}
j.jobSchedule = &cronJob{cronSchedule: cronSchedule} func (c *defaultCron) Next(lastRun time.Time) time.Time {
return c.cronSchedule.Next(lastRun)
}
// default cron job implementation
var _ JobDefinition = (*cronJobDefinition)(nil)
type cronJobDefinition struct {
crontab string
cron Cron
}
func (c cronJobDefinition) setup(j *internalJob, location *time.Location, now time.Time) error {
if j.cron != nil {
c.cron = j.cron
}
if err := c.cron.IsValid(c.crontab, location, now); err != nil {
return err
}
j.jobSchedule = &cronJob{crontab: c.crontab, cronSchedule: c.cron}
return nil return nil
} }
@@ -157,7 +211,7 @@ func (c cronJobDefinition) setup(j *internalJob, location *time.Location, now ti
func CronJob(crontab string, withSeconds bool) JobDefinition { func CronJob(crontab string, withSeconds bool) JobDefinition {
return cronJobDefinition{ return cronJobDefinition{
crontab: crontab, crontab: crontab,
withSeconds: withSeconds, cron: newDefaultCronImplementation(withSeconds),
} }
} }
@@ -252,6 +306,10 @@ func (d dailyJobDefinition) setup(j *internalJob, location *time.Location, _ tim
return ErrDailyJobMinutesSeconds return ErrDailyJobMinutesSeconds
} }
if d.interval == 0 {
return ErrDailyJobZeroInterval
}
ds := dailyJob{ ds := dailyJob{
interval: d.interval, interval: d.interval,
atTimes: atTimesDate, atTimes: atTimesDate,
@@ -270,6 +328,9 @@ type weeklyJobDefinition struct {
func (w weeklyJobDefinition) setup(j *internalJob, location *time.Location, _ time.Time) error { func (w weeklyJobDefinition) setup(j *internalJob, location *time.Location, _ time.Time) error {
var ws weeklyJob var ws weeklyJob
if w.interval == 0 {
return ErrWeeklyJobZeroInterval
}
ws.interval = w.interval ws.interval = w.interval
if w.daysOfTheWeek == nil { if w.daysOfTheWeek == nil {
@@ -304,8 +365,7 @@ type Weekdays func() []time.Weekday
// NewWeekdays provide the days of the week the job should run. // NewWeekdays provide the days of the week the job should run.
func NewWeekdays(weekday time.Weekday, weekdays ...time.Weekday) Weekdays { func NewWeekdays(weekday time.Weekday, weekdays ...time.Weekday) Weekdays {
return func() []time.Weekday { return func() []time.Weekday {
weekdays = append(weekdays, weekday) return append([]time.Weekday{weekday}, weekdays...)
return weekdays
} }
} }
@@ -335,6 +395,9 @@ type monthlyJobDefinition struct {
func (m monthlyJobDefinition) setup(j *internalJob, location *time.Location, _ time.Time) error { func (m monthlyJobDefinition) setup(j *internalJob, location *time.Location, _ time.Time) error {
var ms monthlyJob var ms monthlyJob
if m.interval == 0 {
return ErrMonthlyJobZeroInterval
}
ms.interval = m.interval ms.interval = m.interval
if m.daysOfTheMonth == nil { if m.daysOfTheMonth == nil {
@@ -353,11 +416,9 @@ func (m monthlyJobDefinition) setup(j *internalJob, location *time.Location, _ t
} }
} }
daysStart = removeSliceDuplicatesInt(daysStart) daysStart = removeSliceDuplicatesInt(daysStart)
slices.Sort(daysStart)
ms.days = daysStart ms.days = daysStart
daysEnd = removeSliceDuplicatesInt(daysEnd) daysEnd = removeSliceDuplicatesInt(daysEnd)
slices.Sort(daysEnd)
ms.daysFromEnd = daysEnd ms.daysFromEnd = daysEnd
atTimesDate, err := convertAtTimesToDateTime(m.atTimes, location) atTimesDate, err := convertAtTimesToDateTime(m.atTimes, location)
@@ -390,8 +451,7 @@ type DaysOfTheMonth func() days
// -5 == 5 days before the end of the month. // -5 == 5 days before the end of the month.
func NewDaysOfTheMonth(day int, moreDays ...int) DaysOfTheMonth { func NewDaysOfTheMonth(day int, moreDays ...int) DaysOfTheMonth {
return func() days { return func() days {
moreDays = append(moreDays, day) return append([]int{day}, moreDays...)
return moreDays
} }
} }
@@ -403,6 +463,14 @@ func (a atTime) time(location *time.Location) time.Time {
return time.Date(0, 0, 0, int(a.hours), int(a.minutes), int(a.seconds), 0, location) return time.Date(0, 0, 0, int(a.hours), int(a.minutes), int(a.seconds), 0, location)
} }
// TimeFromAtTime is a helper function to allow converting AtTime into a time.Time value
// Note: the time.Time value will have zero values for all Time fields except Hours, Minutes, Seconds.
//
// For example: time.Date(0, 0, 0, 1, 1, 1, 0, time.UTC)
func TimeFromAtTime(at AtTime, loc *time.Location) time.Time {
return at().time(loc)
}
// AtTime defines a function that returns the internal atTime // AtTime defines a function that returns the internal atTime
type AtTime func() atTime type AtTime func() atTime
@@ -421,8 +489,7 @@ type AtTimes func() []AtTime
// the job should be run // the job should be run
func NewAtTimes(atTime AtTime, atTimes ...AtTime) AtTimes { func NewAtTimes(atTime AtTime, atTimes ...AtTime) AtTimes {
return func() []AtTime { return func() []AtTime {
atTimes = append(atTimes, atTime) return append([]AtTime{atTime}, atTimes...)
return atTimes
} }
} }
@@ -541,6 +608,16 @@ func WithDistributedJobLocker(locker Locker) JobOption {
} }
} }
// WithDisabledDistributedJobLocker disables the distributed job locker.
// This is useful when a global distributed locker has been set on the scheduler
// level using WithDistributedLocker and need to be disabled for specific jobs.
func WithDisabledDistributedJobLocker(disabled bool) JobOption {
return func(j *internalJob, _ time.Time) error {
j.disabledLocker = disabled
return nil
}
}
// WithEventListeners sets the event listeners that should be // WithEventListeners sets the event listeners that should be
// run for the job. // run for the job.
func WithEventListeners(eventListeners ...EventListener) JobOption { func WithEventListeners(eventListeners ...EventListener) JobOption {
@@ -578,6 +655,15 @@ func WithName(name string) JobOption {
} }
} }
// WithCronImplementation sets the custom Cron implementation for the job.
// This is only utilized for the CronJob type.
func WithCronImplementation(c Cron) JobOption {
return func(j *internalJob, _ time.Time) error {
j.cron = c
return nil
}
}
// WithSingletonMode keeps the job from running again if it is already running. // WithSingletonMode keeps the job from running again if it is already running.
// This is useful for jobs that should not overlap, and that occasionally // This is useful for jobs that should not overlap, and that occasionally
// (but not consistently) run longer than the interval between job runs. // (but not consistently) run longer than the interval between job runs.
@@ -676,6 +762,22 @@ func WithIdentifier(id uuid.UUID) JobOption {
} }
} }
// WithContext sets the parent context for the job.
// If you set the first argument of your Task func to be a context.Context,
// gocron will pass in the provided context to the job and will cancel the
// context on shutdown. If you cancel the context the job will no longer be
// scheduled as well. This allows you to both control the job via a context
// and listen for and handle cancellation within your job.
func WithContext(ctx context.Context) JobOption {
return func(j *internalJob, _ time.Time) error {
if ctx == nil {
return ErrWithContextNil
}
j.parentCtx = ctx
return nil
}
}
// ----------------------------------------------- // -----------------------------------------------
// ----------------------------------------------- // -----------------------------------------------
// ------------- Job Event Listeners ------------- // ------------- Job Event Listeners -------------
@@ -698,6 +800,19 @@ func BeforeJobRuns(eventListenerFunc func(jobID uuid.UUID, jobName string)) Even
} }
} }
// BeforeJobRunsSkipIfBeforeFuncErrors is used to listen for when a job is about to run and
// then runs the provided function. If the provided function returns an error, the job will be
// rescheduled and the current run will be skipped.
func BeforeJobRunsSkipIfBeforeFuncErrors(eventListenerFunc func(jobID uuid.UUID, jobName string) error) EventListener {
return func(j *internalJob) error {
if eventListenerFunc == nil {
return ErrEventListenerFuncNil
}
j.beforeJobRunsSkipIfBeforeFuncErrors = eventListenerFunc
return nil
}
}
// AfterJobRuns is used to listen for when a job has run // AfterJobRuns is used to listen for when a job has run
// without an error, and then run the provided function. // without an error, and then run the provided function.
func AfterJobRuns(eventListenerFunc func(jobID uuid.UUID, jobName string)) EventListener { func AfterJobRuns(eventListenerFunc func(jobID uuid.UUID, jobName string)) EventListener {
@@ -759,7 +874,8 @@ type jobSchedule interface {
var _ jobSchedule = (*cronJob)(nil) var _ jobSchedule = (*cronJob)(nil)
type cronJob struct { type cronJob struct {
cronSchedule cron.Schedule crontab string
cronSchedule Cron
} }
func (j *cronJob) next(lastRun time.Time) time.Time { func (j *cronJob) next(lastRun time.Time) time.Time {
@@ -803,7 +919,7 @@ func (d dailyJob) next(lastRun time.Time) time.Time {
} }
firstPass = false firstPass = false
startNextDay := time.Date(lastRun.Year(), lastRun.Month(), lastRun.Day()+int(d.interval), 0, 0, 0, lastRun.Nanosecond(), lastRun.Location()) startNextDay := time.Date(lastRun.Year(), lastRun.Month(), lastRun.Day()+int(d.interval), 0, 0, 0, 0, lastRun.Location())
return d.nextDay(startNextDay, firstPass) return d.nextDay(startNextDay, firstPass)
} }
@@ -811,7 +927,7 @@ func (d dailyJob) nextDay(lastRun time.Time, firstPass bool) time.Time {
for _, at := range d.atTimes { for _, at := range d.atTimes {
// sub the at time hour/min/sec onto the lastScheduledRun's values // sub the at time hour/min/sec onto the lastScheduledRun's values
// to use in checks to see if we've got our next run time // to use in checks to see if we've got our next run time
atDate := time.Date(lastRun.Year(), lastRun.Month(), lastRun.Day(), at.Hour(), at.Minute(), at.Second(), lastRun.Nanosecond(), lastRun.Location()) atDate := time.Date(lastRun.Year(), lastRun.Month(), lastRun.Day(), at.Hour(), at.Minute(), at.Second(), 0, lastRun.Location())
if firstPass && atDate.After(lastRun) { if firstPass && atDate.After(lastRun) {
// checking to see if it is after i.e. greater than, // checking to see if it is after i.e. greater than,
@@ -857,7 +973,7 @@ func (w weeklyJob) nextWeekDayAtTime(lastRun time.Time, firstPass bool) time.Tim
for _, at := range w.atTimes { for _, at := range w.atTimes {
// sub the at time hour/min/sec onto the lastScheduledRun's values // sub the at time hour/min/sec onto the lastScheduledRun's values
// to use in checks to see if we've got our next run time // to use in checks to see if we've got our next run time
atDate := time.Date(lastRun.Year(), lastRun.Month(), lastRun.Day()+int(weekDayDiff), at.Hour(), at.Minute(), at.Second(), lastRun.Nanosecond(), lastRun.Location()) atDate := time.Date(lastRun.Year(), lastRun.Month(), lastRun.Day()+int(weekDayDiff), at.Hour(), at.Minute(), at.Second(), 0, lastRun.Location())
if firstPass && atDate.After(lastRun) { if firstPass && atDate.After(lastRun) {
// checking to see if it is after i.e. greater than, // checking to see if it is after i.e. greater than,
@@ -925,7 +1041,7 @@ func (m monthlyJob) nextMonthDayAtTime(lastRun time.Time, days []int, firstPass
for _, at := range m.atTimes { for _, at := range m.atTimes {
// sub the day, and the at time hour/min/sec onto the lastScheduledRun's values // sub the day, and the at time hour/min/sec onto the lastScheduledRun's values
// to use in checks to see if we've got our next run time // to use in checks to see if we've got our next run time
atDate := time.Date(lastRun.Year(), lastRun.Month(), day, at.Hour(), at.Minute(), at.Second(), lastRun.Nanosecond(), lastRun.Location()) atDate := time.Date(lastRun.Year(), lastRun.Month(), day, at.Hour(), at.Minute(), at.Second(), 0, lastRun.Location())
if atDate.Month() != lastRun.Month() { if atDate.Month() != lastRun.Month() {
// this check handles if we're setting a day not in the current month // this check handles if we're setting a day not in the current month
@@ -1089,12 +1205,14 @@ func (j job) RunNow() error {
defer cancel() defer cancel()
resp := make(chan error, 1) resp := make(chan error, 1)
t := time.NewTimer(100 * time.Millisecond)
select { select {
case j.runJobRequest <- runJobRequest{ case j.runJobRequest <- runJobRequest{
id: j.id, id: j.id,
outChan: resp, outChan: resp,
}: }:
case <-time.After(100 * time.Millisecond): t.Stop()
case <-t.C:
return ErrJobRunNowFailed return ErrJobRunNowFailed
} }
var err error var err error

View File

@@ -26,3 +26,11 @@ type Monitor interface {
// to handle instantiating and recording the value // to handle instantiating and recording the value
RecordJobTiming(startTime, endTime time.Time, id uuid.UUID, name string, tags []string) RecordJobTiming(startTime, endTime time.Time, id uuid.UUID, name string, tags []string)
} }
// MonitorStatus extends RecordJobTiming with the job status.
type MonitorStatus interface {
Monitor
// RecordJobTimingWithStatus will provide details about the job, its status, error and the timing and expects the underlying implementation
// to handle instantiating and recording the value
RecordJobTimingWithStatus(startTime, endTime time.Time, id uuid.UUID, name string, tags []string, status JobStatus, err error)
}

View File

@@ -5,11 +5,12 @@ import (
"context" "context"
"reflect" "reflect"
"runtime" "runtime"
"slices"
"strings"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jonboulle/clockwork" "github.com/jonboulle/clockwork"
"golang.org/x/exp/slices"
) )
var _ Scheduler = (*scheduler)(nil) var _ Scheduler = (*scheduler)(nil)
@@ -21,6 +22,10 @@ type Scheduler interface {
// NewJob creates a new job in the Scheduler. The job is scheduled per the provided // NewJob creates a new job in the Scheduler. The job is scheduled per the provided
// definition when the Scheduler is started. If the Scheduler is already running // definition when the Scheduler is started. If the Scheduler is already running
// the job will be scheduled when the Scheduler is started. // the job will be scheduled when the Scheduler is started.
// If you set the first argument of your Task func to be a context.Context,
// gocron will pass in a context (either the default Job context, or one
// provided via WithContext) to the job and will cancel the context on shutdown.
// This allows you to listen for and handle cancellation within your job.
NewJob(JobDefinition, Task, ...JobOption) (Job, error) NewJob(JobDefinition, Task, ...JobOption) (Job, error)
// RemoveByTags removes all jobs that have at least one of the provided tags. // RemoveByTags removes all jobs that have at least one of the provided tags.
RemoveByTags(...string) RemoveByTags(...string)
@@ -133,9 +138,10 @@ func NewScheduler(options ...SchedulerOption) (Scheduler, error) {
jobsIn: make(chan jobIn), jobsIn: make(chan jobIn),
jobsOutForRescheduling: make(chan uuid.UUID), jobsOutForRescheduling: make(chan uuid.UUID),
jobUpdateNextRuns: make(chan uuid.UUID),
jobsOutCompleted: make(chan uuid.UUID), jobsOutCompleted: make(chan uuid.UUID),
jobOutRequest: make(chan jobOutRequest, 1000), jobOutRequest: make(chan jobOutRequest, 1000),
done: make(chan error), done: make(chan error, 1),
} }
s := &scheduler{ s := &scheduler{
@@ -171,7 +177,8 @@ func NewScheduler(options ...SchedulerOption) (Scheduler, error) {
select { select {
case id := <-s.exec.jobsOutForRescheduling: case id := <-s.exec.jobsOutForRescheduling:
s.selectExecJobsOutForRescheduling(id) s.selectExecJobsOutForRescheduling(id)
case id := <-s.exec.jobUpdateNextRuns:
s.updateNextScheduled(id)
case id := <-s.exec.jobsOutCompleted: case id := <-s.exec.jobsOutCompleted:
s.selectExecJobsOutCompleted(id) s.selectExecJobsOutCompleted(id)
@@ -233,20 +240,34 @@ func (s *scheduler) stopScheduler() {
for _, j := range s.jobs { for _, j := range s.jobs {
j.stop() j.stop()
} }
for id, j := range s.jobs { for _, j := range s.jobs {
<-j.ctx.Done() <-j.ctx.Done()
j.ctx, j.cancel = context.WithCancel(s.shutdownCtx)
s.jobs[id] = j
} }
var err error var err error
if s.started { if s.started {
t := time.NewTimer(s.exec.stopTimeout + 1*time.Second)
select { select {
case err = <-s.exec.done: case err = <-s.exec.done:
case <-time.After(s.exec.stopTimeout + 1*time.Second): t.Stop()
case <-t.C:
err = ErrStopExecutorTimedOut err = ErrStopExecutorTimedOut
} }
} }
for id, j := range s.jobs {
oldCtx := j.ctx
if j.parentCtx == nil {
j.parentCtx = s.shutdownCtx
}
j.ctx, j.cancel = context.WithCancel(j.parentCtx)
// also replace the old context with the new one in the parameters
if len(j.parameters) > 0 && j.parameters[0] == oldCtx {
j.parameters[0] = j.ctx
}
s.jobs[id] = j
}
s.stopErrCh <- err s.stopErrCh <- err
s.started = false s.started = false
s.logger.Debug("gocron: scheduler stopped") s.logger.Debug("gocron: scheduler stopped")
@@ -261,14 +282,7 @@ func (s *scheduler) selectAllJobsOutRequest(out allJobsOutRequest) {
} }
slices.SortFunc(outJobs, func(a, b Job) int { slices.SortFunc(outJobs, func(a, b Job) int {
aID, bID := a.ID().String(), b.ID().String() aID, bID := a.ID().String(), b.ID().String()
switch { return strings.Compare(aID, bID)
case aID < bID:
return -1
case aID > bID:
return 1
default:
return 0
}
}) })
select { select {
case <-s.shutdownCtx.Done(): case <-s.shutdownCtx.Done():
@@ -329,7 +343,7 @@ func (s *scheduler) selectExecJobsOutForRescheduling(id uuid.UUID) {
return return
} }
scheduleFrom := j.lastRun var scheduleFrom time.Time
if len(j.nextScheduled) > 0 { if len(j.nextScheduled) > 0 {
// always grab the last element in the slice as that is the furthest // always grab the last element in the slice as that is the furthest
// out in the future and the time from which we want to calculate // out in the future and the time from which we want to calculate
@@ -360,6 +374,15 @@ func (s *scheduler) selectExecJobsOutForRescheduling(id uuid.UUID) {
} }
} }
if slices.Contains(j.nextScheduled, next) {
// if the next value is a duplicate of what's already in the nextScheduled slice, for example:
// - the job is being rescheduled off the same next run value as before
// increment to the next, next value
for slices.Contains(j.nextScheduled, next) {
next = j.next(next)
}
}
// Clean up any existing timer to prevent leaks // Clean up any existing timer to prevent leaks
if j.timer != nil { if j.timer != nil {
j.timer.Stop() j.timer.Stop()
@@ -384,6 +407,22 @@ func (s *scheduler) selectExecJobsOutForRescheduling(id uuid.UUID) {
s.jobs[id] = j s.jobs[id] = j
} }
func (s *scheduler) updateNextScheduled(id uuid.UUID) {
j, ok := s.jobs[id]
if !ok {
return
}
var newNextScheduled []time.Time
for _, t := range j.nextScheduled {
if t.Before(s.now()) {
continue
}
newNextScheduled = append(newNextScheduled, t)
}
j.nextScheduled = newNextScheduled
s.jobs[id] = j
}
func (s *scheduler) selectExecJobsOutCompleted(id uuid.UUID) { func (s *scheduler) selectExecJobsOutCompleted(id uuid.UUID) {
j, ok := s.jobs[id] j, ok := s.jobs[id]
if !ok { if !ok {
@@ -646,8 +685,6 @@ func (s *scheduler) addOrUpdateJob(id uuid.UUID, definition JobDefinition, taskW
j.id = id j.id = id
} }
j.ctx, j.cancel = context.WithCancel(s.shutdownCtx)
if taskWrapper == nil { if taskWrapper == nil {
return nil, ErrNewJobTaskNil return nil, ErrNewJobTaskNil
} }
@@ -662,10 +699,6 @@ func (s *scheduler) addOrUpdateJob(id uuid.UUID, definition JobDefinition, taskW
return nil, ErrNewJobTaskNotFunc return nil, ErrNewJobTaskNotFunc
} }
if err := s.verifyParameterType(taskFunc, tsk); err != nil {
return nil, err
}
j.name = runtime.FuncForPC(taskFunc.Pointer()).Name() j.name = runtime.FuncForPC(taskFunc.Pointer()).Name()
j.function = tsk.function j.function = tsk.function
j.parameters = tsk.parameters j.parameters = tsk.parameters
@@ -684,6 +717,28 @@ func (s *scheduler) addOrUpdateJob(id uuid.UUID, definition JobDefinition, taskW
} }
} }
if j.parentCtx == nil {
j.parentCtx = s.shutdownCtx
}
j.ctx, j.cancel = context.WithCancel(j.parentCtx)
if !taskFunc.IsZero() && taskFunc.Type().NumIn() > 0 {
// if the first parameter is a context.Context and params have no context.Context, add current ctx to the params
if taskFunc.Type().In(0) == reflect.TypeOf((*context.Context)(nil)).Elem() {
if len(tsk.parameters) == 0 {
tsk.parameters = []any{j.ctx}
j.parameters = []any{j.ctx}
} else if _, ok := tsk.parameters[0].(context.Context); !ok {
tsk.parameters = append([]any{j.ctx}, tsk.parameters...)
j.parameters = append([]any{j.ctx}, j.parameters...)
}
}
}
if err := s.verifyParameterType(taskFunc, tsk); err != nil {
return nil, err
}
if err := definition.setup(&j, s.location, s.exec.clock.Now()); err != nil { if err := definition.setup(&j, s.location, s.exec.clock.Now()); err != nil {
return nil, err return nil, err
} }
@@ -741,20 +796,27 @@ func (s *scheduler) StopJobs() error {
return nil return nil
case s.stopCh <- struct{}{}: case s.stopCh <- struct{}{}:
} }
t := time.NewTimer(s.exec.stopTimeout + 2*time.Second)
select { select {
case err := <-s.stopErrCh: case err := <-s.stopErrCh:
t.Stop()
return err return err
case <-time.After(s.exec.stopTimeout + 2*time.Second): case <-t.C:
return ErrStopSchedulerTimedOut return ErrStopSchedulerTimedOut
} }
} }
func (s *scheduler) Shutdown() error { func (s *scheduler) Shutdown() error {
s.shutdownCancel() s.shutdownCancel()
t := time.NewTimer(s.exec.stopTimeout + 2*time.Second)
select { select {
case err := <-s.stopErrCh: case err := <-s.stopErrCh:
t.Stop()
return err return err
case <-time.After(s.exec.stopTimeout + 2*time.Second): case <-t.C:
return ErrStopSchedulerTimedOut return ErrStopSchedulerTimedOut
} }
} }
@@ -809,6 +871,8 @@ func WithDistributedElector(elector Elector) SchedulerOption {
// WithDistributedLocker sets the locker to be used by multiple // WithDistributedLocker sets the locker to be used by multiple
// Scheduler instances to ensure that only one instance of each // Scheduler instances to ensure that only one instance of each
// job is run. // job is run.
// To disable this global locker for specific jobs, see
// WithDisabledDistributedJobLocker.
func WithDistributedLocker(locker Locker) SchedulerOption { func WithDistributedLocker(locker Locker) SchedulerOption {
return func(s *scheduler) error { return func(s *scheduler) error {
if locker == nil { if locker == nil {
@@ -945,3 +1009,14 @@ func WithMonitor(monitor Monitor) SchedulerOption {
return nil return nil
} }
} }
// WithMonitorStatus sets the metrics provider to be used by the Scheduler.
func WithMonitorStatus(monitor MonitorStatus) SchedulerOption {
return func(s *scheduler) error {
if monitor == nil {
return ErrWithMonitorNil
}
s.exec.monitorStatus = monitor
return nil
}
}

View File

@@ -3,12 +3,11 @@ package gocron
import ( import (
"context" "context"
"reflect" "reflect"
"slices"
"sync" "sync"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
) )
func callJobFuncWithParams(jobFunc any, params ...any) error { func callJobFuncWithParams(jobFunc any, params ...any) error {
@@ -63,12 +62,8 @@ func requestJobCtx(ctx context.Context, id uuid.UUID, ch chan jobOutRequest) *in
} }
func removeSliceDuplicatesInt(in []int) []int { func removeSliceDuplicatesInt(in []int) []int {
m := make(map[int]struct{}) slices.Sort(in)
return slices.Compact(in)
for _, i := range in {
m[i] = struct{}{}
}
return maps.Keys(m)
} }
func convertAtTimesToDateTime(atTimes AtTimes, location *time.Location) ([]time.Time, error) { func convertAtTimesToDateTime(atTimes AtTimes, location *time.Location) ([]time.Time, error) {

View File

@@ -36,6 +36,7 @@ Now you can easily test `myFunc` with a `FakeClock`:
```go ```go
func TestMyFunc(t *testing.T) { func TestMyFunc(t *testing.T) {
ctx := context.Background()
c := clockwork.NewFakeClock() c := clockwork.NewFakeClock()
// Start our sleepy function // Start our sleepy function
@@ -46,8 +47,12 @@ func TestMyFunc(t *testing.T) {
wg.Done() wg.Done()
}() }()
// Ensure we wait until myFunc is sleeping // Ensure we wait until myFunc is waiting on the clock.
c.BlockUntil(1) // Use a context to avoid blocking forever if something
// goes wrong.
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
c.BlockUntilContext(ctx, 1)
assertState() assertState()

19
vendor/github.com/jonboulle/clockwork/SECURITY.md generated vendored Normal file
View File

@@ -0,0 +1,19 @@
# Security Policy
If you have discovered a security vulnerability in this project, please report it
privately. **Do not disclose it as a public issue.** This gives me time to work with you
to fix the issue before public exposure, reducing the chance that the exploit will be
used before a patch is released.
You may submit the report in the following ways:
- send an email to ???@???; and/or
- send a [private vulnerability report](https://github.com/jonboulle/clockwork/security/advisories/new)
Please provide the following information in your report:
- A description of the vulnerability and its impact
- How to reproduce the issue
This project is maintained by a single maintainer on a reasonable-effort basis. As such,
please give me 90 days to work on a fix before public exposure.

View File

@@ -1,8 +1,10 @@
// Package clockwork contains a simple fake clock for Go.
package clockwork package clockwork
import ( import (
"context" "context"
"sort" "errors"
"slices"
"sync" "sync"
"time" "time"
) )
@@ -14,49 +16,18 @@ type Clock interface {
Sleep(d time.Duration) Sleep(d time.Duration)
Now() time.Time Now() time.Time
Since(t time.Time) time.Duration Since(t time.Time) time.Duration
Until(t time.Time) time.Duration
NewTicker(d time.Duration) Ticker NewTicker(d time.Duration) Ticker
NewTimer(d time.Duration) Timer NewTimer(d time.Duration) Timer
AfterFunc(d time.Duration, f func()) Timer AfterFunc(d time.Duration, f func()) Timer
} }
// FakeClock provides an interface for a clock which can be manually advanced
// through time.
//
// FakeClock maintains a list of "waiters," which consists of all callers
// waiting on the underlying clock (i.e. Tickers and Timers including callers of
// Sleep or After). Users can call BlockUntil to block until the clock has an
// expected number of waiters.
type FakeClock interface {
Clock
// Advance advances the FakeClock to a new point in time, ensuring any existing
// waiters are notified appropriately before returning.
Advance(d time.Duration)
// BlockUntil blocks until the FakeClock has the given number of waiters.
BlockUntil(waiters int)
}
// NewRealClock returns a Clock which simply delegates calls to the actual time // NewRealClock returns a Clock which simply delegates calls to the actual time
// package; it should be used by packages in production. // package; it should be used by packages in production.
func NewRealClock() Clock { func NewRealClock() Clock {
return &realClock{} return &realClock{}
} }
// NewFakeClock returns a FakeClock implementation which can be
// manually advanced through time for testing. The initial time of the
// FakeClock will be the current system time.
//
// Tests that require a deterministic time must use NewFakeClockAt.
func NewFakeClock() FakeClock {
return NewFakeClockAt(time.Now())
}
// NewFakeClockAt returns a FakeClock initialised at the given time.Time.
func NewFakeClockAt(t time.Time) FakeClock {
return &fakeClock{
time: t,
}
}
type realClock struct{} type realClock struct{}
func (rc *realClock) After(d time.Duration) <-chan time.Time { func (rc *realClock) After(d time.Duration) <-chan time.Time {
@@ -75,6 +46,10 @@ func (rc *realClock) Since(t time.Time) time.Duration {
return rc.Now().Sub(t) return rc.Now().Sub(t)
} }
func (rc *realClock) Until(t time.Time) time.Duration {
return t.Sub(rc.Now())
}
func (rc *realClock) NewTicker(d time.Duration) Ticker { func (rc *realClock) NewTicker(d time.Duration) Ticker {
return realTicker{time.NewTicker(d)} return realTicker{time.NewTicker(d)}
} }
@@ -87,7 +62,14 @@ func (rc *realClock) AfterFunc(d time.Duration, f func()) Timer {
return realTimer{time.AfterFunc(d, f)} return realTimer{time.AfterFunc(d, f)}
} }
type fakeClock struct { // FakeClock provides an interface for a clock which can be manually advanced
// through time.
//
// FakeClock maintains a list of "waiters," which consists of all callers
// waiting on the underlying clock (i.e. Tickers and Timers including callers of
// Sleep or After). Users can call BlockUntil to block until the clock has an
// expected number of waiters.
type FakeClock struct {
// l protects all attributes of the clock, including all attributes of all // l protects all attributes of the clock, including all attributes of all
// waiters and blockers. // waiters and blockers.
l sync.RWMutex l sync.RWMutex
@@ -96,11 +78,27 @@ type fakeClock struct {
time time.Time time time.Time
} }
// NewFakeClock returns a FakeClock implementation which can be
// manually advanced through time for testing. The initial time of the
// FakeClock will be the current system time.
//
// Tests that require a deterministic time must use NewFakeClockAt.
func NewFakeClock() *FakeClock {
return NewFakeClockAt(time.Now())
}
// NewFakeClockAt returns a FakeClock initialised at the given time.Time.
func NewFakeClockAt(t time.Time) *FakeClock {
return &FakeClock{
time: t,
}
}
// blocker is a caller of BlockUntil. // blocker is a caller of BlockUntil.
type blocker struct { type blocker struct {
count int count int
// ch is closed when the underlying clock has the specificed number of blockers. // ch is closed when the underlying clock has the specified number of blockers.
ch chan struct{} ch chan struct{}
} }
@@ -111,23 +109,23 @@ type expirer interface {
expire(now time.Time) (next *time.Duration) expire(now time.Time) (next *time.Duration)
// Get and set the expiration time. // Get and set the expiration time.
expiry() time.Time expiration() time.Time
setExpiry(time.Time) setExpiration(time.Time)
} }
// After mimics [time.After]; it waits for the given duration to elapse on the // After mimics [time.After]; it waits for the given duration to elapse on the
// fakeClock, then sends the current time on the returned channel. // fakeClock, then sends the current time on the returned channel.
func (fc *fakeClock) After(d time.Duration) <-chan time.Time { func (fc *FakeClock) After(d time.Duration) <-chan time.Time {
return fc.NewTimer(d).Chan() return fc.NewTimer(d).Chan()
} }
// Sleep blocks until the given duration has passed on the fakeClock. // Sleep blocks until the given duration has passed on the fakeClock.
func (fc *fakeClock) Sleep(d time.Duration) { func (fc *FakeClock) Sleep(d time.Duration) {
<-fc.After(d) <-fc.After(d)
} }
// Now returns the current time of the fakeClock // Now returns the current time of the fakeClock
func (fc *fakeClock) Now() time.Time { func (fc *FakeClock) Now() time.Time {
fc.l.RLock() fc.l.RLock()
defer fc.l.RUnlock() defer fc.l.RUnlock()
return fc.time return fc.time
@@ -135,61 +133,73 @@ func (fc *fakeClock) Now() time.Time {
// Since returns the duration that has passed since the given time on the // Since returns the duration that has passed since the given time on the
// fakeClock. // fakeClock.
func (fc *fakeClock) Since(t time.Time) time.Duration { func (fc *FakeClock) Since(t time.Time) time.Duration {
return fc.Now().Sub(t) return fc.Now().Sub(t)
} }
// NewTicker returns a Ticker that will expire only after calls to // Until returns the duration that has to pass from the given time on the fakeClock
// fakeClock.Advance() have moved the clock past the given duration. // to reach the given time.
func (fc *fakeClock) NewTicker(d time.Duration) Ticker { func (fc *FakeClock) Until(t time.Time) time.Duration {
var ft *fakeTicker return t.Sub(fc.Now())
ft = &fakeTicker{
firer: newFirer(),
d: d,
reset: func(d time.Duration) { fc.set(ft, d) },
stop: func() { fc.stop(ft) },
} }
fc.set(ft, d)
// NewTicker returns a Ticker that will expire only after calls to
// FakeClock.Advance() have moved the clock past the given duration.
//
// The duration d must be greater than zero; if not, NewTicker will panic.
func (fc *FakeClock) NewTicker(d time.Duration) Ticker {
// Maintain parity with
// https://cs.opensource.google/go/go/+/refs/tags/go1.20.3:src/time/tick.go;l=23-25
if d <= 0 {
panic(errors.New("non-positive interval for NewTicker"))
}
ft := newFakeTicker(fc, d)
fc.l.Lock()
defer fc.l.Unlock()
fc.setExpirer(ft, d)
return ft return ft
} }
// NewTimer returns a Timer that will fire only after calls to // NewTimer returns a Timer that will fire only after calls to
// fakeClock.Advance() have moved the clock past the given duration. // fakeClock.Advance() have moved the clock past the given duration.
func (fc *fakeClock) NewTimer(d time.Duration) Timer { func (fc *FakeClock) NewTimer(d time.Duration) Timer {
return fc.newTimer(d, nil) t, _ := fc.newTimer(d, nil)
return t
} }
// AfterFunc mimics [time.AfterFunc]; it returns a Timer that will invoke the // AfterFunc mimics [time.AfterFunc]; it returns a Timer that will invoke the
// given function only after calls to fakeClock.Advance() have moved the clock // given function only after calls to fakeClock.Advance() have moved the clock
// past the given duration. // past the given duration.
func (fc *fakeClock) AfterFunc(d time.Duration, f func()) Timer { func (fc *FakeClock) AfterFunc(d time.Duration, f func()) Timer {
return fc.newTimer(d, f) t, _ := fc.newTimer(d, f)
return t
} }
// newTimer returns a new timer, using an optional afterFunc. // newTimer returns a new timer using an optional afterFunc and the time that
func (fc *fakeClock) newTimer(d time.Duration, afterfunc func()) *fakeTimer { // timer expires.
var ft *fakeTimer func (fc *FakeClock) newTimer(d time.Duration, afterfunc func()) (*fakeTimer, time.Time) {
ft = &fakeTimer{ ft := newFakeTimer(fc, afterfunc)
firer: newFirer(),
reset: func(d time.Duration) bool {
fc.l.Lock() fc.l.Lock()
defer fc.l.Unlock() defer fc.l.Unlock()
// fc.l must be held across the calls to stopExpirer & setExpirer.
stopped := fc.stopExpirer(ft)
fc.setExpirer(ft, d) fc.setExpirer(ft, d)
return stopped return ft, ft.expiration()
},
stop: func() bool { return fc.stop(ft) },
afterFunc: afterfunc,
} }
fc.set(ft, d)
// newTimerAtTime is like newTimer, but uses a time instead of a duration.
//
// It is used to ensure FakeClock's lock is held constant through calling
// fc.After(t.Sub(fc.Now())). It should not be exposed externally.
func (fc *FakeClock) newTimerAtTime(t time.Time, afterfunc func()) *fakeTimer {
ft := newFakeTimer(fc, afterfunc)
fc.l.Lock()
defer fc.l.Unlock()
fc.setExpirer(ft, t.Sub(fc.time))
return ft return ft
} }
// Advance advances fakeClock to a new point in time, ensuring waiters and // Advance advances fakeClock to a new point in time, ensuring waiters and
// blockers are notified appropriately before returning. // blockers are notified appropriately before returning.
func (fc *fakeClock) Advance(d time.Duration) { func (fc *FakeClock) Advance(d time.Duration) {
fc.l.Lock() fc.l.Lock()
defer fc.l.Unlock() defer fc.l.Unlock()
end := fc.time.Add(d) end := fc.time.Add(d)
@@ -198,38 +208,34 @@ func (fc *fakeClock) Advance(d time.Duration) {
// //
// We don't iterate because the callback of the waiter might register a new // We don't iterate because the callback of the waiter might register a new
// waiter, so the list of waiters might change as we execute this. // waiter, so the list of waiters might change as we execute this.
for len(fc.waiters) > 0 && !end.Before(fc.waiters[0].expiry()) { for len(fc.waiters) > 0 && !end.Before(fc.waiters[0].expiration()) {
w := fc.waiters[0] w := fc.waiters[0]
fc.waiters = fc.waiters[1:] fc.waiters = fc.waiters[1:]
// Use the waiter's expriation as the current time for this expiration. // Use the waiter's expiration as the current time for this expiration.
now := w.expiry() now := w.expiration()
fc.time = now fc.time = now
if d := w.expire(now); d != nil { if d := w.expire(now); d != nil {
// Set the new exipration if needed. // Set the new expiration if needed.
fc.setExpirer(w, *d) fc.setExpirer(w, *d)
} }
} }
fc.time = end fc.time = end
} }
// BlockUntil blocks until the fakeClock has the given number of waiters. // BlockUntil blocks until the FakeClock has the given number of waiters.
// //
// Prefer BlockUntilContext, which offers context cancellation to prevent // Prefer BlockUntilContext in new code, which offers context cancellation to
// deadlock. // prevent deadlock.
// //
// Deprecation warning: This function might be deprecated in later versions. // Deprecated: New code should prefer BlockUntilContext.
func (fc *fakeClock) BlockUntil(n int) { func (fc *FakeClock) BlockUntil(n int) {
b := fc.newBlocker(n) fc.BlockUntilContext(context.TODO(), n)
if b == nil {
return
}
<-b.ch
} }
// BlockUntilContext blocks until the fakeClock has the given number of waiters // BlockUntilContext blocks until the fakeClock has the given number of waiters
// or the context is cancelled. // or the context is cancelled.
func (fc *fakeClock) BlockUntilContext(ctx context.Context, n int) error { func (fc *FakeClock) BlockUntilContext(ctx context.Context, n int) error {
b := fc.newBlocker(n) b := fc.newBlocker(n)
if b == nil { if b == nil {
return nil return nil
@@ -243,7 +249,7 @@ func (fc *fakeClock) BlockUntilContext(ctx context.Context, n int) error {
} }
} }
func (fc *fakeClock) newBlocker(n int) *blocker { func (fc *FakeClock) newBlocker(n int) *blocker {
fc.l.Lock() fc.l.Lock()
defer fc.l.Unlock() defer fc.l.Unlock()
// Fast path: we already have >= n waiters. // Fast path: we already have >= n waiters.
@@ -260,7 +266,7 @@ func (fc *fakeClock) newBlocker(n int) *blocker {
} }
// stop stops an expirer, returning true if the expirer was stopped. // stop stops an expirer, returning true if the expirer was stopped.
func (fc *fakeClock) stop(e expirer) bool { func (fc *FakeClock) stop(e expirer) bool {
fc.l.Lock() fc.l.Lock()
defer fc.l.Unlock() defer fc.l.Unlock()
return fc.stopExpirer(e) return fc.stopExpirer(e)
@@ -269,81 +275,45 @@ func (fc *fakeClock) stop(e expirer) bool {
// stopExpirer stops an expirer, returning true if the expirer was stopped. // stopExpirer stops an expirer, returning true if the expirer was stopped.
// //
// The caller must hold fc.l. // The caller must hold fc.l.
func (fc *fakeClock) stopExpirer(e expirer) bool { func (fc *FakeClock) stopExpirer(e expirer) bool {
for i, t := range fc.waiters { idx := slices.Index(fc.waiters, e)
if t == e { if idx == -1 {
// Remove element, maintaining order. return false
copy(fc.waiters[i:], fc.waiters[i+1:]) }
// Remove element, maintaining order, setting inaccessible elements to nil so
// they can be garbage collected.
copy(fc.waiters[idx:], fc.waiters[idx+1:])
fc.waiters[len(fc.waiters)-1] = nil fc.waiters[len(fc.waiters)-1] = nil
fc.waiters = fc.waiters[:len(fc.waiters)-1] fc.waiters = fc.waiters[:len(fc.waiters)-1]
return true return true
} }
}
return false
}
// set sets an expirer to expire at a future point in time.
func (fc *fakeClock) set(e expirer, d time.Duration) {
fc.l.Lock()
defer fc.l.Unlock()
fc.setExpirer(e, d)
}
// setExpirer sets an expirer to expire at a future point in time. // setExpirer sets an expirer to expire at a future point in time.
// //
// The caller must hold fc.l. // The caller must hold fc.l.
func (fc *fakeClock) setExpirer(e expirer, d time.Duration) { func (fc *FakeClock) setExpirer(e expirer, d time.Duration) {
if d.Nanoseconds() <= 0 { if d.Nanoseconds() <= 0 {
// special case - trigger immediately, never reset. // Special case for timers with duration <= 0: trigger immediately, never
// reset.
// //
// TODO: Explain what cases this covers. // Tickers never get here, they panic if d is < 0.
e.expire(fc.time) e.expire(fc.time)
return return
} }
// Add the expirer to the set of waiters and notify any blockers. // Add the expirer to the set of waiters and notify any blockers.
e.setExpiry(fc.time.Add(d)) e.setExpiration(fc.time.Add(d))
fc.waiters = append(fc.waiters, e) fc.waiters = append(fc.waiters, e)
sort.Slice(fc.waiters, func(i int, j int) bool { slices.SortFunc(fc.waiters, func(a, b expirer) int {
return fc.waiters[i].expiry().Before(fc.waiters[j].expiry()) return a.expiration().Compare(b.expiration())
}) })
// Notify blockers of our new waiter. // Notify blockers of our new waiter.
var blocked []*blocker
count := len(fc.waiters) count := len(fc.waiters)
for _, b := range fc.blockers { fc.blockers = slices.DeleteFunc(fc.blockers, func(b *blocker) bool {
if b.count <= count { if b.count <= count {
close(b.ch) close(b.ch)
continue return true
} }
blocked = append(blocked, b) return false
} })
fc.blockers = blocked
}
// firer is used by fakeTimer and fakeTicker used to help implement expirer.
type firer struct {
// The channel associated with the firer, used to send expriation times.
c chan time.Time
// The time when the firer expires. Only meaningful if the firer is currently
// one of a fakeClock's waiters.
exp time.Time
}
func newFirer() firer {
return firer{c: make(chan time.Time, 1)}
}
func (f *firer) Chan() <-chan time.Time {
return f.c
}
// expiry implements expirer.
func (f *firer) expiry() time.Time {
return f.exp
}
// setExpiry implements expirer.
func (f *firer) setExpiry(t time.Time) {
f.exp = t
} }

View File

@@ -2,24 +2,168 @@ package clockwork
import ( import (
"context" "context"
"fmt"
"sync"
"time"
) )
// contextKey is private to this package so we can ensure uniqueness here. This // contextKey is private to this package so we can ensure uniqueness here. This
// type identifies context values provided by this package. // type identifies context values provided by this package.
type contextKey string type contextKey string
// keyClock provides a clock for injecting during tests. If absent, a real clock should be used. // keyClock provides a clock for injecting during tests. If absent, a real clock
// should be used.
var keyClock = contextKey("clock") // clockwork.Clock var keyClock = contextKey("clock") // clockwork.Clock
// AddToContext creates a derived context that references the specified clock. // AddToContext creates a derived context that references the specified clock.
//
// Be aware this doesn't change the behavior of standard library functions, such
// as [context.WithTimeout] or [context.WithDeadline]. For this reason, users
// should prefer passing explicit [clockwork.Clock] variables rather can passing
// the clock via the context.
func AddToContext(ctx context.Context, clock Clock) context.Context { func AddToContext(ctx context.Context, clock Clock) context.Context {
return context.WithValue(ctx, keyClock, clock) return context.WithValue(ctx, keyClock, clock)
} }
// FromContext extracts a clock from the context. If not present, a real clock is returned. // FromContext extracts a clock from the context. If not present, a real clock
// is returned.
func FromContext(ctx context.Context) Clock { func FromContext(ctx context.Context) Clock {
if clock, ok := ctx.Value(keyClock).(Clock); ok { if clock, ok := ctx.Value(keyClock).(Clock); ok {
return clock return clock
} }
return NewRealClock() return NewRealClock()
} }
// ErrFakeClockDeadlineExceeded is the error returned by [context.Context] when
// the deadline passes on a context which uses a [FakeClock].
//
// It wraps a [context.DeadlineExceeded] error, i.e.:
//
// // The following is true for any Context whose deadline has been exceeded,
// // including contexts made with clockwork.WithDeadline or clockwork.WithTimeout.
//
// errors.Is(ctx.Err(), context.DeadlineExceeded)
//
// // The following can only be true for contexts made
// // with clockwork.WithDeadline or clockwork.WithTimeout.
//
// errors.Is(ctx.Err(), clockwork.ErrFakeClockDeadlineExceeded)
var ErrFakeClockDeadlineExceeded error = fmt.Errorf("clockwork.FakeClock: %w", context.DeadlineExceeded)
// WithDeadline returns a context with a deadline based on a [FakeClock].
//
// The returned context ignores parent cancelation if the parent was cancelled
// with a [context.DeadlineExceeded] error. Any other error returned by the
// parent is treated normally, cancelling the returned context.
//
// If the parent is cancelled with a [context.DeadlineExceeded] error, the only
// way to then cancel the returned context is by calling the returned
// context.CancelFunc.
func WithDeadline(parent context.Context, clock Clock, t time.Time) (context.Context, context.CancelFunc) {
if fc, ok := clock.(*FakeClock); ok {
return newFakeClockContext(parent, t, fc.newTimerAtTime(t, nil).Chan())
}
return context.WithDeadline(parent, t)
}
// WithTimeout returns a context with a timeout based on a [FakeClock].
//
// The returned context follows the same behaviors as [WithDeadline].
func WithTimeout(parent context.Context, clock Clock, d time.Duration) (context.Context, context.CancelFunc) {
if fc, ok := clock.(*FakeClock); ok {
t, deadline := fc.newTimer(d, nil)
return newFakeClockContext(parent, deadline, t.Chan())
}
return context.WithTimeout(parent, d)
}
// fakeClockContext implements context.Context, using a fake clock for its
// deadline.
//
// It ignores parent cancellation if the parent is cancelled with
// context.DeadlineExceeded.
type fakeClockContext struct {
parent context.Context
deadline time.Time // The user-facing deadline based on the fake clock's time.
// Tracks timeout/deadline cancellation.
timerDone <-chan time.Time
// Tracks manual calls to the cancel function.
cancel func() // Closes cancelCalled wrapped in a sync.Once.
cancelCalled chan struct{}
// The user-facing data from the context.Context interface.
ctxDone chan struct{} // Returned by Done().
err error // nil until ctxDone is ready to be closed.
}
func newFakeClockContext(parent context.Context, deadline time.Time, timer <-chan time.Time) (context.Context, context.CancelFunc) {
cancelCalled := make(chan struct{})
ctx := &fakeClockContext{
parent: parent,
deadline: deadline,
timerDone: timer,
cancelCalled: cancelCalled,
ctxDone: make(chan struct{}),
cancel: sync.OnceFunc(func() {
close(cancelCalled)
}),
}
ready := make(chan struct{}, 1)
go ctx.runCancel(ready)
<-ready // Wait until the cancellation goroutine is running.
return ctx, ctx.cancel
}
func (c *fakeClockContext) Deadline() (time.Time, bool) {
return c.deadline, true
}
func (c *fakeClockContext) Done() <-chan struct{} {
return c.ctxDone
}
func (c *fakeClockContext) Err() error {
<-c.Done() // Don't return the error before it is ready.
return c.err
}
func (c *fakeClockContext) Value(key any) any {
return c.parent.Value(key)
}
// runCancel runs the fakeClockContext's cancel goroutine and returns the
// fakeClockContext's cancel function.
//
// fakeClockContext is then cancelled when any of the following occur:
//
// - The fakeClockContext.done channel is closed by its timer.
// - The returned CancelFunc is executed.
// - The fakeClockContext's parent context is cancelled with an error other
// than context.DeadlineExceeded.
func (c *fakeClockContext) runCancel(ready chan struct{}) {
parentDone := c.parent.Done()
// Close ready when done, just in case the ready signal races with other
// branches of our select statement below.
defer close(ready)
for c.err == nil {
select {
case <-c.timerDone:
c.err = ErrFakeClockDeadlineExceeded
case <-c.cancelCalled:
c.err = context.Canceled
case <-parentDone:
c.err = c.parent.Err()
case ready <- struct{}{}:
// Signals the cancellation goroutine has begun, in an attempt to minimize
// race conditions related to goroutine startup time.
ready = nil // This case statement can only fire once.
}
}
close(c.ctxDone)
return
}

View File

@@ -19,7 +19,12 @@ func (r realTicker) Chan() <-chan time.Time {
} }
type fakeTicker struct { type fakeTicker struct {
firer // The channel associated with the firer, used to send expiration times.
c chan time.Time
// The time when the ticker expires. Only meaningful if the ticker is currently
// one of a FakeClock's waiters.
exp time.Time
// reset and stop provide the implementation of the respective exported // reset and stop provide the implementation of the respective exported
// functions. // functions.
@@ -30,13 +35,27 @@ type fakeTicker struct {
d time.Duration d time.Duration
} }
func (f *fakeTicker) Reset(d time.Duration) { func newFakeTicker(fc *FakeClock, d time.Duration) *fakeTicker {
f.reset(d) var ft *fakeTicker
ft = &fakeTicker{
c: make(chan time.Time, 1),
d: d,
reset: func(d time.Duration) {
fc.l.Lock()
defer fc.l.Unlock()
ft.d = d
fc.setExpirer(ft, d)
},
stop: func() { fc.stop(ft) },
}
return ft
} }
func (f *fakeTicker) Stop() { func (f *fakeTicker) Chan() <-chan time.Time { return f.c }
f.stop()
} func (f *fakeTicker) Reset(d time.Duration) { f.reset(d) }
func (f *fakeTicker) Stop() { f.stop() }
func (f *fakeTicker) expire(now time.Time) *time.Duration { func (f *fakeTicker) expire(now time.Time) *time.Duration {
// Never block on expiration. // Never block on expiration.
@@ -46,3 +65,7 @@ func (f *fakeTicker) expire(now time.Time) *time.Duration {
} }
return &f.d return &f.d
} }
func (f *fakeTicker) expiration() time.Time { return f.exp }
func (f *fakeTicker) setExpiration(t time.Time) { f.exp = t }

View File

@@ -18,9 +18,14 @@ func (r realTimer) Chan() <-chan time.Time {
} }
type fakeTimer struct { type fakeTimer struct {
firer // The channel associated with the firer, used to send expiration times.
c chan time.Time
// reset and stop provide the implmenetation of the respective exported // The time when the firer expires. Only meaningful if the firer is currently
// one of a FakeClock's waiters.
exp time.Time
// reset and stop provide the implementation of the respective exported
// functions. // functions.
reset func(d time.Duration) bool reset func(d time.Duration) bool
stop func() bool stop func() bool
@@ -30,13 +35,30 @@ type fakeTimer struct {
afterFunc func() afterFunc func()
} }
func (f *fakeTimer) Reset(d time.Duration) bool { func newFakeTimer(fc *FakeClock, afterfunc func()) *fakeTimer {
return f.reset(d) var ft *fakeTimer
ft = &fakeTimer{
c: make(chan time.Time, 1),
reset: func(d time.Duration) bool {
fc.l.Lock()
defer fc.l.Unlock()
// fc.l must be held across the calls to stopExpirer & setExpirer.
stopped := fc.stopExpirer(ft)
fc.setExpirer(ft, d)
return stopped
},
stop: func() bool { return fc.stop(ft) },
afterFunc: afterfunc,
}
return ft
} }
func (f *fakeTimer) Stop() bool { func (f *fakeTimer) Chan() <-chan time.Time { return f.c }
return f.stop()
} func (f *fakeTimer) Reset(d time.Duration) bool { return f.reset(d) }
func (f *fakeTimer) Stop() bool { return f.stop() }
func (f *fakeTimer) expire(now time.Time) *time.Duration { func (f *fakeTimer) expire(now time.Time) *time.Duration {
if f.afterFunc != nil { if f.afterFunc != nil {
@@ -51,3 +73,7 @@ func (f *fakeTimer) expire(now time.Time) *time.Duration {
} }
return nil return nil
} }
func (f *fakeTimer) expiration() time.Time { return f.exp }
func (f *fakeTimer) setExpiration(t time.Time) { f.exp = t }

27
vendor/golang.org/x/exp/LICENSE generated vendored
View File

@@ -1,27 +0,0 @@
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

22
vendor/golang.org/x/exp/PATENTS generated vendored
View File

@@ -1,22 +0,0 @@
Additional IP Rights Grant (Patents)
"This implementation" means the copyrightable works distributed by
Google as part of the Go project.
Google hereby grants to You a perpetual, worldwide, non-exclusive,
no-charge, royalty-free, irrevocable (except as stated in this section)
patent license to make, have made, use, offer to sell, sell, import,
transfer and otherwise run, modify and propagate the contents of this
implementation of Go, where such license applies only to those patent
claims, both currently owned or controlled by Google and acquired in
the future, licensable by Google that are necessarily infringed by this
implementation of Go. This grant does not include claims that would be
infringed only as a consequence of further modification of this
implementation. If you or your agent or exclusive licensee institute or
order or agree to the institution of patent litigation against any
entity (including a cross-claim or counterclaim in a lawsuit) alleging
that this implementation of Go or any code incorporated within this
implementation of Go constitutes direct or contributory patent
infringement, or inducement of patent infringement, then any patent
rights granted to you under this License for this implementation of Go
shall terminate as of the date such litigation is filed.

View File

@@ -1,50 +0,0 @@
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package constraints defines a set of useful constraints to be used
// with type parameters.
package constraints
// Signed is a constraint that permits any signed integer type.
// If future releases of Go add new predeclared signed integer types,
// this constraint will be modified to include them.
type Signed interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
// Unsigned is a constraint that permits any unsigned integer type.
// If future releases of Go add new predeclared unsigned integer types,
// this constraint will be modified to include them.
type Unsigned interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
// Integer is a constraint that permits any integer type.
// If future releases of Go add new predeclared integer types,
// this constraint will be modified to include them.
type Integer interface {
Signed | Unsigned
}
// Float is a constraint that permits any floating-point type.
// If future releases of Go add new predeclared floating-point types,
// this constraint will be modified to include them.
type Float interface {
~float32 | ~float64
}
// Complex is a constraint that permits any complex numeric type.
// If future releases of Go add new predeclared complex numeric types,
// this constraint will be modified to include them.
type Complex interface {
~complex64 | ~complex128
}
// Ordered is a constraint that permits any ordered type: any type
// that supports the operators < <= >= >.
// If future releases of Go add new ordered types,
// this constraint will be modified to include them.
type Ordered interface {
Integer | Float | ~string
}

94
vendor/golang.org/x/exp/maps/maps.go generated vendored
View File

@@ -1,94 +0,0 @@
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package maps defines various functions useful with maps of any type.
package maps
// Keys returns the keys of the map m.
// The keys will be in an indeterminate order.
func Keys[M ~map[K]V, K comparable, V any](m M) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
// Values returns the values of the map m.
// The values will be in an indeterminate order.
func Values[M ~map[K]V, K comparable, V any](m M) []V {
r := make([]V, 0, len(m))
for _, v := range m {
r = append(r, v)
}
return r
}
// Equal reports whether two maps contain the same key/value pairs.
// Values are compared using ==.
func Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool {
if len(m1) != len(m2) {
return false
}
for k, v1 := range m1 {
if v2, ok := m2[k]; !ok || v1 != v2 {
return false
}
}
return true
}
// EqualFunc is like Equal, but compares values using eq.
// Keys are still compared with ==.
func EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool {
if len(m1) != len(m2) {
return false
}
for k, v1 := range m1 {
if v2, ok := m2[k]; !ok || !eq(v1, v2) {
return false
}
}
return true
}
// Clear removes all entries from m, leaving it empty.
func Clear[M ~map[K]V, K comparable, V any](m M) {
for k := range m {
delete(m, k)
}
}
// Clone returns a copy of m. This is a shallow clone:
// the new keys and values are set using ordinary assignment.
func Clone[M ~map[K]V, K comparable, V any](m M) M {
// Preserve nil in case it matters.
if m == nil {
return nil
}
r := make(M, len(m))
for k, v := range m {
r[k] = v
}
return r
}
// Copy copies all key/value pairs in src adding them to dst.
// When a key in src is already present in dst,
// the value in dst will be overwritten by the value associated
// with the key in src.
func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) {
for k, v := range src {
dst[k] = v
}
}
// DeleteFunc deletes any key/value pairs from m for which del returns true.
func DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool) {
for k, v := range m {
if del(k, v) {
delete(m, k)
}
}
}

View File

@@ -1,44 +0,0 @@
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package slices
import "golang.org/x/exp/constraints"
// min is a version of the predeclared function from the Go 1.21 release.
func min[T constraints.Ordered](a, b T) T {
if a < b || isNaN(a) {
return a
}
return b
}
// max is a version of the predeclared function from the Go 1.21 release.
func max[T constraints.Ordered](a, b T) T {
if a > b || isNaN(a) {
return a
}
return b
}
// cmpLess is a copy of cmp.Less from the Go 1.21 release.
func cmpLess[T constraints.Ordered](x, y T) bool {
return (isNaN(x) && !isNaN(y)) || x < y
}
// cmpCompare is a copy of cmp.Compare from the Go 1.21 release.
func cmpCompare[T constraints.Ordered](x, y T) int {
xNaN := isNaN(x)
yNaN := isNaN(y)
if xNaN && yNaN {
return 0
}
if xNaN || x < y {
return -1
}
if yNaN || x > y {
return +1
}
return 0
}

View File

@@ -1,515 +0,0 @@
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package slices defines various functions useful with slices of any type.
package slices
import (
"unsafe"
"golang.org/x/exp/constraints"
)
// Equal reports whether two slices are equal: the same length and all
// elements equal. If the lengths are different, Equal returns false.
// Otherwise, the elements are compared in increasing index order, and the
// comparison stops at the first unequal pair.
// Floating point NaNs are not considered equal.
func Equal[S ~[]E, E comparable](s1, s2 S) bool {
if len(s1) != len(s2) {
return false
}
for i := range s1 {
if s1[i] != s2[i] {
return false
}
}
return true
}
// EqualFunc reports whether two slices are equal using an equality
// function on each pair of elements. If the lengths are different,
// EqualFunc returns false. Otherwise, the elements are compared in
// increasing index order, and the comparison stops at the first index
// for which eq returns false.
func EqualFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, eq func(E1, E2) bool) bool {
if len(s1) != len(s2) {
return false
}
for i, v1 := range s1 {
v2 := s2[i]
if !eq(v1, v2) {
return false
}
}
return true
}
// Compare compares the elements of s1 and s2, using [cmp.Compare] on each pair
// of elements. The elements are compared sequentially, starting at index 0,
// until one element is not equal to the other.
// The result of comparing the first non-matching elements is returned.
// If both slices are equal until one of them ends, the shorter slice is
// considered less than the longer one.
// The result is 0 if s1 == s2, -1 if s1 < s2, and +1 if s1 > s2.
func Compare[S ~[]E, E constraints.Ordered](s1, s2 S) int {
for i, v1 := range s1 {
if i >= len(s2) {
return +1
}
v2 := s2[i]
if c := cmpCompare(v1, v2); c != 0 {
return c
}
}
if len(s1) < len(s2) {
return -1
}
return 0
}
// CompareFunc is like [Compare] but uses a custom comparison function on each
// pair of elements.
// The result is the first non-zero result of cmp; if cmp always
// returns 0 the result is 0 if len(s1) == len(s2), -1 if len(s1) < len(s2),
// and +1 if len(s1) > len(s2).
func CompareFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, cmp func(E1, E2) int) int {
for i, v1 := range s1 {
if i >= len(s2) {
return +1
}
v2 := s2[i]
if c := cmp(v1, v2); c != 0 {
return c
}
}
if len(s1) < len(s2) {
return -1
}
return 0
}
// Index returns the index of the first occurrence of v in s,
// or -1 if not present.
func Index[S ~[]E, E comparable](s S, v E) int {
for i := range s {
if v == s[i] {
return i
}
}
return -1
}
// IndexFunc returns the first index i satisfying f(s[i]),
// or -1 if none do.
func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int {
for i := range s {
if f(s[i]) {
return i
}
}
return -1
}
// Contains reports whether v is present in s.
func Contains[S ~[]E, E comparable](s S, v E) bool {
return Index(s, v) >= 0
}
// ContainsFunc reports whether at least one
// element e of s satisfies f(e).
func ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool {
return IndexFunc(s, f) >= 0
}
// Insert inserts the values v... into s at index i,
// returning the modified slice.
// The elements at s[i:] are shifted up to make room.
// In the returned slice r, r[i] == v[0],
// and r[i+len(v)] == value originally at r[i].
// Insert panics if i is out of range.
// This function is O(len(s) + len(v)).
func Insert[S ~[]E, E any](s S, i int, v ...E) S {
m := len(v)
if m == 0 {
return s
}
n := len(s)
if i == n {
return append(s, v...)
}
if n+m > cap(s) {
// Use append rather than make so that we bump the size of
// the slice up to the next storage class.
// This is what Grow does but we don't call Grow because
// that might copy the values twice.
s2 := append(s[:i], make(S, n+m-i)...)
copy(s2[i:], v)
copy(s2[i+m:], s[i:])
return s2
}
s = s[:n+m]
// before:
// s: aaaaaaaabbbbccccccccdddd
// ^ ^ ^ ^
// i i+m n n+m
// after:
// s: aaaaaaaavvvvbbbbcccccccc
// ^ ^ ^ ^
// i i+m n n+m
//
// a are the values that don't move in s.
// v are the values copied in from v.
// b and c are the values from s that are shifted up in index.
// d are the values that get overwritten, never to be seen again.
if !overlaps(v, s[i+m:]) {
// Easy case - v does not overlap either the c or d regions.
// (It might be in some of a or b, or elsewhere entirely.)
// The data we copy up doesn't write to v at all, so just do it.
copy(s[i+m:], s[i:])
// Now we have
// s: aaaaaaaabbbbbbbbcccccccc
// ^ ^ ^ ^
// i i+m n n+m
// Note the b values are duplicated.
copy(s[i:], v)
// Now we have
// s: aaaaaaaavvvvbbbbcccccccc
// ^ ^ ^ ^
// i i+m n n+m
// That's the result we want.
return s
}
// The hard case - v overlaps c or d. We can't just shift up
// the data because we'd move or clobber the values we're trying
// to insert.
// So instead, write v on top of d, then rotate.
copy(s[n:], v)
// Now we have
// s: aaaaaaaabbbbccccccccvvvv
// ^ ^ ^ ^
// i i+m n n+m
rotateRight(s[i:], m)
// Now we have
// s: aaaaaaaavvvvbbbbcccccccc
// ^ ^ ^ ^
// i i+m n n+m
// That's the result we want.
return s
}
// clearSlice sets all elements up to the length of s to the zero value of E.
// We may use the builtin clear func instead, and remove clearSlice, when upgrading
// to Go 1.21+.
func clearSlice[S ~[]E, E any](s S) {
var zero E
for i := range s {
s[i] = zero
}
}
// Delete removes the elements s[i:j] from s, returning the modified slice.
// Delete panics if j > len(s) or s[i:j] is not a valid slice of s.
// Delete is O(len(s)-i), so if many items must be deleted, it is better to
// make a single call deleting them all together than to delete one at a time.
// Delete zeroes the elements s[len(s)-(j-i):len(s)].
func Delete[S ~[]E, E any](s S, i, j int) S {
_ = s[i:j:len(s)] // bounds check
if i == j {
return s
}
oldlen := len(s)
s = append(s[:i], s[j:]...)
clearSlice(s[len(s):oldlen]) // zero/nil out the obsolete elements, for GC
return s
}
// DeleteFunc removes any elements from s for which del returns true,
// returning the modified slice.
// DeleteFunc zeroes the elements between the new length and the original length.
func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S {
i := IndexFunc(s, del)
if i == -1 {
return s
}
// Don't start copying elements until we find one to delete.
for j := i + 1; j < len(s); j++ {
if v := s[j]; !del(v) {
s[i] = v
i++
}
}
clearSlice(s[i:]) // zero/nil out the obsolete elements, for GC
return s[:i]
}
// Replace replaces the elements s[i:j] by the given v, and returns the
// modified slice. Replace panics if s[i:j] is not a valid slice of s.
// When len(v) < (j-i), Replace zeroes the elements between the new length and the original length.
func Replace[S ~[]E, E any](s S, i, j int, v ...E) S {
_ = s[i:j] // verify that i:j is a valid subslice
if i == j {
return Insert(s, i, v...)
}
if j == len(s) {
return append(s[:i], v...)
}
tot := len(s[:i]) + len(v) + len(s[j:])
if tot > cap(s) {
// Too big to fit, allocate and copy over.
s2 := append(s[:i], make(S, tot-i)...) // See Insert
copy(s2[i:], v)
copy(s2[i+len(v):], s[j:])
return s2
}
r := s[:tot]
if i+len(v) <= j {
// Easy, as v fits in the deleted portion.
copy(r[i:], v)
if i+len(v) != j {
copy(r[i+len(v):], s[j:])
}
clearSlice(s[tot:]) // zero/nil out the obsolete elements, for GC
return r
}
// We are expanding (v is bigger than j-i).
// The situation is something like this:
// (example has i=4,j=8,len(s)=16,len(v)=6)
// s: aaaaxxxxbbbbbbbbyy
// ^ ^ ^ ^
// i j len(s) tot
// a: prefix of s
// x: deleted range
// b: more of s
// y: area to expand into
if !overlaps(r[i+len(v):], v) {
// Easy, as v is not clobbered by the first copy.
copy(r[i+len(v):], s[j:])
copy(r[i:], v)
return r
}
// This is a situation where we don't have a single place to which
// we can copy v. Parts of it need to go to two different places.
// We want to copy the prefix of v into y and the suffix into x, then
// rotate |y| spots to the right.
//
// v[2:] v[:2]
// | |
// s: aaaavvvvbbbbbbbbvv
// ^ ^ ^ ^
// i j len(s) tot
//
// If either of those two destinations don't alias v, then we're good.
y := len(v) - (j - i) // length of y portion
if !overlaps(r[i:j], v) {
copy(r[i:j], v[y:])
copy(r[len(s):], v[:y])
rotateRight(r[i:], y)
return r
}
if !overlaps(r[len(s):], v) {
copy(r[len(s):], v[:y])
copy(r[i:j], v[y:])
rotateRight(r[i:], y)
return r
}
// Now we know that v overlaps both x and y.
// That means that the entirety of b is *inside* v.
// So we don't need to preserve b at all; instead we
// can copy v first, then copy the b part of v out of
// v to the right destination.
k := startIdx(v, s[j:])
copy(r[i:], v)
copy(r[i+len(v):], r[i+k:])
return r
}
// Clone returns a copy of the slice.
// The elements are copied using assignment, so this is a shallow clone.
func Clone[S ~[]E, E any](s S) S {
// Preserve nil in case it matters.
if s == nil {
return nil
}
return append(S([]E{}), s...)
}
// Compact replaces consecutive runs of equal elements with a single copy.
// This is like the uniq command found on Unix.
// Compact modifies the contents of the slice s and returns the modified slice,
// which may have a smaller length.
// Compact zeroes the elements between the new length and the original length.
func Compact[S ~[]E, E comparable](s S) S {
if len(s) < 2 {
return s
}
i := 1
for k := 1; k < len(s); k++ {
if s[k] != s[k-1] {
if i != k {
s[i] = s[k]
}
i++
}
}
clearSlice(s[i:]) // zero/nil out the obsolete elements, for GC
return s[:i]
}
// CompactFunc is like [Compact] but uses an equality function to compare elements.
// For runs of elements that compare equal, CompactFunc keeps the first one.
// CompactFunc zeroes the elements between the new length and the original length.
func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S {
if len(s) < 2 {
return s
}
i := 1
for k := 1; k < len(s); k++ {
if !eq(s[k], s[k-1]) {
if i != k {
s[i] = s[k]
}
i++
}
}
clearSlice(s[i:]) // zero/nil out the obsolete elements, for GC
return s[:i]
}
// Grow increases the slice's capacity, if necessary, to guarantee space for
// another n elements. After Grow(n), at least n elements can be appended
// to the slice without another allocation. If n is negative or too large to
// allocate the memory, Grow panics.
func Grow[S ~[]E, E any](s S, n int) S {
if n < 0 {
panic("cannot be negative")
}
if n -= cap(s) - len(s); n > 0 {
// TODO(https://go.dev/issue/53888): Make using []E instead of S
// to workaround a compiler bug where the runtime.growslice optimization
// does not take effect. Revert when the compiler is fixed.
s = append([]E(s)[:cap(s)], make([]E, n)...)[:len(s)]
}
return s
}
// Clip removes unused capacity from the slice, returning s[:len(s):len(s)].
func Clip[S ~[]E, E any](s S) S {
return s[:len(s):len(s)]
}
// Rotation algorithm explanation:
//
// rotate left by 2
// start with
// 0123456789
// split up like this
// 01 234567 89
// swap first 2 and last 2
// 89 234567 01
// join first parts
// 89234567 01
// recursively rotate first left part by 2
// 23456789 01
// join at the end
// 2345678901
//
// rotate left by 8
// start with
// 0123456789
// split up like this
// 01 234567 89
// swap first 2 and last 2
// 89 234567 01
// join last parts
// 89 23456701
// recursively rotate second part left by 6
// 89 01234567
// join at the end
// 8901234567
// TODO: There are other rotate algorithms.
// This algorithm has the desirable property that it moves each element exactly twice.
// The triple-reverse algorithm is simpler and more cache friendly, but takes more writes.
// The follow-cycles algorithm can be 1-write but it is not very cache friendly.
// rotateLeft rotates b left by n spaces.
// s_final[i] = s_orig[i+r], wrapping around.
func rotateLeft[E any](s []E, r int) {
for r != 0 && r != len(s) {
if r*2 <= len(s) {
swap(s[:r], s[len(s)-r:])
s = s[:len(s)-r]
} else {
swap(s[:len(s)-r], s[r:])
s, r = s[len(s)-r:], r*2-len(s)
}
}
}
func rotateRight[E any](s []E, r int) {
rotateLeft(s, len(s)-r)
}
// swap swaps the contents of x and y. x and y must be equal length and disjoint.
func swap[E any](x, y []E) {
for i := 0; i < len(x); i++ {
x[i], y[i] = y[i], x[i]
}
}
// overlaps reports whether the memory ranges a[0:len(a)] and b[0:len(b)] overlap.
func overlaps[E any](a, b []E) bool {
if len(a) == 0 || len(b) == 0 {
return false
}
elemSize := unsafe.Sizeof(a[0])
if elemSize == 0 {
return false
}
// TODO: use a runtime/unsafe facility once one becomes available. See issue 12445.
// Also see crypto/internal/alias/alias.go:AnyOverlap
return uintptr(unsafe.Pointer(&a[0])) <= uintptr(unsafe.Pointer(&b[len(b)-1]))+(elemSize-1) &&
uintptr(unsafe.Pointer(&b[0])) <= uintptr(unsafe.Pointer(&a[len(a)-1]))+(elemSize-1)
}
// startIdx returns the index in haystack where the needle starts.
// prerequisite: the needle must be aliased entirely inside the haystack.
func startIdx[E any](haystack, needle []E) int {
p := &needle[0]
for i := range haystack {
if p == &haystack[i] {
return i
}
}
// TODO: what if the overlap is by a non-integral number of Es?
panic("needle not found")
}
// Reverse reverses the elements of the slice in place.
func Reverse[S ~[]E, E any](s S) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}

View File

@@ -1,197 +0,0 @@
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run $GOROOT/src/sort/gen_sort_variants.go -exp
package slices
import (
"math/bits"
"golang.org/x/exp/constraints"
)
// Sort sorts a slice of any ordered type in ascending order.
// When sorting floating-point numbers, NaNs are ordered before other values.
func Sort[S ~[]E, E constraints.Ordered](x S) {
n := len(x)
pdqsortOrdered(x, 0, n, bits.Len(uint(n)))
}
// SortFunc sorts the slice x in ascending order as determined by the cmp
// function. This sort is not guaranteed to be stable.
// cmp(a, b) should return a negative number when a < b, a positive number when
// a > b and zero when a == b or when a is not comparable to b in the sense
// of the formal definition of Strict Weak Ordering.
//
// SortFunc requires that cmp is a strict weak ordering.
// See https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings.
// To indicate 'uncomparable', return 0 from the function.
func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int) {
n := len(x)
pdqsortCmpFunc(x, 0, n, bits.Len(uint(n)), cmp)
}
// SortStableFunc sorts the slice x while keeping the original order of equal
// elements, using cmp to compare elements in the same way as [SortFunc].
func SortStableFunc[S ~[]E, E any](x S, cmp func(a, b E) int) {
stableCmpFunc(x, len(x), cmp)
}
// IsSorted reports whether x is sorted in ascending order.
func IsSorted[S ~[]E, E constraints.Ordered](x S) bool {
for i := len(x) - 1; i > 0; i-- {
if cmpLess(x[i], x[i-1]) {
return false
}
}
return true
}
// IsSortedFunc reports whether x is sorted in ascending order, with cmp as the
// comparison function as defined by [SortFunc].
func IsSortedFunc[S ~[]E, E any](x S, cmp func(a, b E) int) bool {
for i := len(x) - 1; i > 0; i-- {
if cmp(x[i], x[i-1]) < 0 {
return false
}
}
return true
}
// Min returns the minimal value in x. It panics if x is empty.
// For floating-point numbers, Min propagates NaNs (any NaN value in x
// forces the output to be NaN).
func Min[S ~[]E, E constraints.Ordered](x S) E {
if len(x) < 1 {
panic("slices.Min: empty list")
}
m := x[0]
for i := 1; i < len(x); i++ {
m = min(m, x[i])
}
return m
}
// MinFunc returns the minimal value in x, using cmp to compare elements.
// It panics if x is empty. If there is more than one minimal element
// according to the cmp function, MinFunc returns the first one.
func MinFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E {
if len(x) < 1 {
panic("slices.MinFunc: empty list")
}
m := x[0]
for i := 1; i < len(x); i++ {
if cmp(x[i], m) < 0 {
m = x[i]
}
}
return m
}
// Max returns the maximal value in x. It panics if x is empty.
// For floating-point E, Max propagates NaNs (any NaN value in x
// forces the output to be NaN).
func Max[S ~[]E, E constraints.Ordered](x S) E {
if len(x) < 1 {
panic("slices.Max: empty list")
}
m := x[0]
for i := 1; i < len(x); i++ {
m = max(m, x[i])
}
return m
}
// MaxFunc returns the maximal value in x, using cmp to compare elements.
// It panics if x is empty. If there is more than one maximal element
// according to the cmp function, MaxFunc returns the first one.
func MaxFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E {
if len(x) < 1 {
panic("slices.MaxFunc: empty list")
}
m := x[0]
for i := 1; i < len(x); i++ {
if cmp(x[i], m) > 0 {
m = x[i]
}
}
return m
}
// BinarySearch searches for target in a sorted slice and returns the position
// where target is found, or the position where target would appear in the
// sort order; it also returns a bool saying whether the target is really found
// in the slice. The slice must be sorted in increasing order.
func BinarySearch[S ~[]E, E constraints.Ordered](x S, target E) (int, bool) {
// Inlining is faster than calling BinarySearchFunc with a lambda.
n := len(x)
// Define x[-1] < target and x[n] >= target.
// Invariant: x[i-1] < target, x[j] >= target.
i, j := 0, n
for i < j {
h := int(uint(i+j) >> 1) // avoid overflow when computing h
// i ≤ h < j
if cmpLess(x[h], target) {
i = h + 1 // preserves x[i-1] < target
} else {
j = h // preserves x[j] >= target
}
}
// i == j, x[i-1] < target, and x[j] (= x[i]) >= target => answer is i.
return i, i < n && (x[i] == target || (isNaN(x[i]) && isNaN(target)))
}
// BinarySearchFunc works like [BinarySearch], but uses a custom comparison
// function. The slice must be sorted in increasing order, where "increasing"
// is defined by cmp. cmp should return 0 if the slice element matches
// the target, a negative number if the slice element precedes the target,
// or a positive number if the slice element follows the target.
// cmp must implement the same ordering as the slice, such that if
// cmp(a, t) < 0 and cmp(b, t) >= 0, then a must precede b in the slice.
func BinarySearchFunc[S ~[]E, E, T any](x S, target T, cmp func(E, T) int) (int, bool) {
n := len(x)
// Define cmp(x[-1], target) < 0 and cmp(x[n], target) >= 0 .
// Invariant: cmp(x[i - 1], target) < 0, cmp(x[j], target) >= 0.
i, j := 0, n
for i < j {
h := int(uint(i+j) >> 1) // avoid overflow when computing h
// i ≤ h < j
if cmp(x[h], target) < 0 {
i = h + 1 // preserves cmp(x[i - 1], target) < 0
} else {
j = h // preserves cmp(x[j], target) >= 0
}
}
// i == j, cmp(x[i-1], target) < 0, and cmp(x[j], target) (= cmp(x[i], target)) >= 0 => answer is i.
return i, i < n && cmp(x[i], target) == 0
}
type sortedHint int // hint for pdqsort when choosing the pivot
const (
unknownHint sortedHint = iota
increasingHint
decreasingHint
)
// xorshift paper: https://www.jstatsoft.org/article/view/v008i14/xorshift.pdf
type xorshift uint64
func (r *xorshift) Next() uint64 {
*r ^= *r << 13
*r ^= *r >> 17
*r ^= *r << 5
return uint64(*r)
}
func nextPowerOfTwo(length int) uint {
return 1 << bits.Len(uint(length))
}
// isNaN reports whether x is a NaN without requiring the math package.
// This will always return false if T is not floating-point.
func isNaN[T constraints.Ordered](x T) bool {
return x != x
}

View File

@@ -1,479 +0,0 @@
// Code generated by gen_sort_variants.go; DO NOT EDIT.
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package slices
// insertionSortCmpFunc sorts data[a:b] using insertion sort.
func insertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
for i := a + 1; i < b; i++ {
for j := i; j > a && (cmp(data[j], data[j-1]) < 0); j-- {
data[j], data[j-1] = data[j-1], data[j]
}
}
}
// siftDownCmpFunc implements the heap property on data[lo:hi].
// first is an offset into the array where the root of the heap lies.
func siftDownCmpFunc[E any](data []E, lo, hi, first int, cmp func(a, b E) int) {
root := lo
for {
child := 2*root + 1
if child >= hi {
break
}
if child+1 < hi && (cmp(data[first+child], data[first+child+1]) < 0) {
child++
}
if !(cmp(data[first+root], data[first+child]) < 0) {
return
}
data[first+root], data[first+child] = data[first+child], data[first+root]
root = child
}
}
func heapSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
first := a
lo := 0
hi := b - a
// Build heap with greatest element at top.
for i := (hi - 1) / 2; i >= 0; i-- {
siftDownCmpFunc(data, i, hi, first, cmp)
}
// Pop elements, largest first, into end of data.
for i := hi - 1; i >= 0; i-- {
data[first], data[first+i] = data[first+i], data[first]
siftDownCmpFunc(data, lo, i, first, cmp)
}
}
// pdqsortCmpFunc sorts data[a:b].
// The algorithm based on pattern-defeating quicksort(pdqsort), but without the optimizations from BlockQuicksort.
// pdqsort paper: https://arxiv.org/pdf/2106.05123.pdf
// C++ implementation: https://github.com/orlp/pdqsort
// Rust implementation: https://docs.rs/pdqsort/latest/pdqsort/
// limit is the number of allowed bad (very unbalanced) pivots before falling back to heapsort.
func pdqsortCmpFunc[E any](data []E, a, b, limit int, cmp func(a, b E) int) {
const maxInsertion = 12
var (
wasBalanced = true // whether the last partitioning was reasonably balanced
wasPartitioned = true // whether the slice was already partitioned
)
for {
length := b - a
if length <= maxInsertion {
insertionSortCmpFunc(data, a, b, cmp)
return
}
// Fall back to heapsort if too many bad choices were made.
if limit == 0 {
heapSortCmpFunc(data, a, b, cmp)
return
}
// If the last partitioning was imbalanced, we need to breaking patterns.
if !wasBalanced {
breakPatternsCmpFunc(data, a, b, cmp)
limit--
}
pivot, hint := choosePivotCmpFunc(data, a, b, cmp)
if hint == decreasingHint {
reverseRangeCmpFunc(data, a, b, cmp)
// The chosen pivot was pivot-a elements after the start of the array.
// After reversing it is pivot-a elements before the end of the array.
// The idea came from Rust's implementation.
pivot = (b - 1) - (pivot - a)
hint = increasingHint
}
// The slice is likely already sorted.
if wasBalanced && wasPartitioned && hint == increasingHint {
if partialInsertionSortCmpFunc(data, a, b, cmp) {
return
}
}
// Probably the slice contains many duplicate elements, partition the slice into
// elements equal to and elements greater than the pivot.
if a > 0 && !(cmp(data[a-1], data[pivot]) < 0) {
mid := partitionEqualCmpFunc(data, a, b, pivot, cmp)
a = mid
continue
}
mid, alreadyPartitioned := partitionCmpFunc(data, a, b, pivot, cmp)
wasPartitioned = alreadyPartitioned
leftLen, rightLen := mid-a, b-mid
balanceThreshold := length / 8
if leftLen < rightLen {
wasBalanced = leftLen >= balanceThreshold
pdqsortCmpFunc(data, a, mid, limit, cmp)
a = mid + 1
} else {
wasBalanced = rightLen >= balanceThreshold
pdqsortCmpFunc(data, mid+1, b, limit, cmp)
b = mid
}
}
}
// partitionCmpFunc does one quicksort partition.
// Let p = data[pivot]
// Moves elements in data[a:b] around, so that data[i]<p and data[j]>=p for i<newpivot and j>newpivot.
// On return, data[newpivot] = p
func partitionCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int, alreadyPartitioned bool) {
data[a], data[pivot] = data[pivot], data[a]
i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
for i <= j && (cmp(data[i], data[a]) < 0) {
i++
}
for i <= j && !(cmp(data[j], data[a]) < 0) {
j--
}
if i > j {
data[j], data[a] = data[a], data[j]
return j, true
}
data[i], data[j] = data[j], data[i]
i++
j--
for {
for i <= j && (cmp(data[i], data[a]) < 0) {
i++
}
for i <= j && !(cmp(data[j], data[a]) < 0) {
j--
}
if i > j {
break
}
data[i], data[j] = data[j], data[i]
i++
j--
}
data[j], data[a] = data[a], data[j]
return j, false
}
// partitionEqualCmpFunc partitions data[a:b] into elements equal to data[pivot] followed by elements greater than data[pivot].
// It assumed that data[a:b] does not contain elements smaller than the data[pivot].
func partitionEqualCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int) {
data[a], data[pivot] = data[pivot], data[a]
i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
for {
for i <= j && !(cmp(data[a], data[i]) < 0) {
i++
}
for i <= j && (cmp(data[a], data[j]) < 0) {
j--
}
if i > j {
break
}
data[i], data[j] = data[j], data[i]
i++
j--
}
return i
}
// partialInsertionSortCmpFunc partially sorts a slice, returns true if the slice is sorted at the end.
func partialInsertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) bool {
const (
maxSteps = 5 // maximum number of adjacent out-of-order pairs that will get shifted
shortestShifting = 50 // don't shift any elements on short arrays
)
i := a + 1
for j := 0; j < maxSteps; j++ {
for i < b && !(cmp(data[i], data[i-1]) < 0) {
i++
}
if i == b {
return true
}
if b-a < shortestShifting {
return false
}
data[i], data[i-1] = data[i-1], data[i]
// Shift the smaller one to the left.
if i-a >= 2 {
for j := i - 1; j >= 1; j-- {
if !(cmp(data[j], data[j-1]) < 0) {
break
}
data[j], data[j-1] = data[j-1], data[j]
}
}
// Shift the greater one to the right.
if b-i >= 2 {
for j := i + 1; j < b; j++ {
if !(cmp(data[j], data[j-1]) < 0) {
break
}
data[j], data[j-1] = data[j-1], data[j]
}
}
}
return false
}
// breakPatternsCmpFunc scatters some elements around in an attempt to break some patterns
// that might cause imbalanced partitions in quicksort.
func breakPatternsCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
length := b - a
if length >= 8 {
random := xorshift(length)
modulus := nextPowerOfTwo(length)
for idx := a + (length/4)*2 - 1; idx <= a+(length/4)*2+1; idx++ {
other := int(uint(random.Next()) & (modulus - 1))
if other >= length {
other -= length
}
data[idx], data[a+other] = data[a+other], data[idx]
}
}
}
// choosePivotCmpFunc chooses a pivot in data[a:b].
//
// [0,8): chooses a static pivot.
// [8,shortestNinther): uses the simple median-of-three method.
// [shortestNinther,∞): uses the Tukey ninther method.
func choosePivotCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) (pivot int, hint sortedHint) {
const (
shortestNinther = 50
maxSwaps = 4 * 3
)
l := b - a
var (
swaps int
i = a + l/4*1
j = a + l/4*2
k = a + l/4*3
)
if l >= 8 {
if l >= shortestNinther {
// Tukey ninther method, the idea came from Rust's implementation.
i = medianAdjacentCmpFunc(data, i, &swaps, cmp)
j = medianAdjacentCmpFunc(data, j, &swaps, cmp)
k = medianAdjacentCmpFunc(data, k, &swaps, cmp)
}
// Find the median among i, j, k and stores it into j.
j = medianCmpFunc(data, i, j, k, &swaps, cmp)
}
switch swaps {
case 0:
return j, increasingHint
case maxSwaps:
return j, decreasingHint
default:
return j, unknownHint
}
}
// order2CmpFunc returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a.
func order2CmpFunc[E any](data []E, a, b int, swaps *int, cmp func(a, b E) int) (int, int) {
if cmp(data[b], data[a]) < 0 {
*swaps++
return b, a
}
return a, b
}
// medianCmpFunc returns x where data[x] is the median of data[a],data[b],data[c], where x is a, b, or c.
func medianCmpFunc[E any](data []E, a, b, c int, swaps *int, cmp func(a, b E) int) int {
a, b = order2CmpFunc(data, a, b, swaps, cmp)
b, c = order2CmpFunc(data, b, c, swaps, cmp)
a, b = order2CmpFunc(data, a, b, swaps, cmp)
return b
}
// medianAdjacentCmpFunc finds the median of data[a - 1], data[a], data[a + 1] and stores the index into a.
func medianAdjacentCmpFunc[E any](data []E, a int, swaps *int, cmp func(a, b E) int) int {
return medianCmpFunc(data, a-1, a, a+1, swaps, cmp)
}
func reverseRangeCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) {
i := a
j := b - 1
for i < j {
data[i], data[j] = data[j], data[i]
i++
j--
}
}
func swapRangeCmpFunc[E any](data []E, a, b, n int, cmp func(a, b E) int) {
for i := 0; i < n; i++ {
data[a+i], data[b+i] = data[b+i], data[a+i]
}
}
func stableCmpFunc[E any](data []E, n int, cmp func(a, b E) int) {
blockSize := 20 // must be > 0
a, b := 0, blockSize
for b <= n {
insertionSortCmpFunc(data, a, b, cmp)
a = b
b += blockSize
}
insertionSortCmpFunc(data, a, n, cmp)
for blockSize < n {
a, b = 0, 2*blockSize
for b <= n {
symMergeCmpFunc(data, a, a+blockSize, b, cmp)
a = b
b += 2 * blockSize
}
if m := a + blockSize; m < n {
symMergeCmpFunc(data, a, m, n, cmp)
}
blockSize *= 2
}
}
// symMergeCmpFunc merges the two sorted subsequences data[a:m] and data[m:b] using
// the SymMerge algorithm from Pok-Son Kim and Arne Kutzner, "Stable Minimum
// Storage Merging by Symmetric Comparisons", in Susanne Albers and Tomasz
// Radzik, editors, Algorithms - ESA 2004, volume 3221 of Lecture Notes in
// Computer Science, pages 714-723. Springer, 2004.
//
// Let M = m-a and N = b-n. Wolog M < N.
// The recursion depth is bound by ceil(log(N+M)).
// The algorithm needs O(M*log(N/M + 1)) calls to data.Less.
// The algorithm needs O((M+N)*log(M)) calls to data.Swap.
//
// The paper gives O((M+N)*log(M)) as the number of assignments assuming a
// rotation algorithm which uses O(M+N+gcd(M+N)) assignments. The argumentation
// in the paper carries through for Swap operations, especially as the block
// swapping rotate uses only O(M+N) Swaps.
//
// symMerge assumes non-degenerate arguments: a < m && m < b.
// Having the caller check this condition eliminates many leaf recursion calls,
// which improves performance.
func symMergeCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) {
// Avoid unnecessary recursions of symMerge
// by direct insertion of data[a] into data[m:b]
// if data[a:m] only contains one element.
if m-a == 1 {
// Use binary search to find the lowest index i
// such that data[i] >= data[a] for m <= i < b.
// Exit the search loop with i == b in case no such index exists.
i := m
j := b
for i < j {
h := int(uint(i+j) >> 1)
if cmp(data[h], data[a]) < 0 {
i = h + 1
} else {
j = h
}
}
// Swap values until data[a] reaches the position before i.
for k := a; k < i-1; k++ {
data[k], data[k+1] = data[k+1], data[k]
}
return
}
// Avoid unnecessary recursions of symMerge
// by direct insertion of data[m] into data[a:m]
// if data[m:b] only contains one element.
if b-m == 1 {
// Use binary search to find the lowest index i
// such that data[i] > data[m] for a <= i < m.
// Exit the search loop with i == m in case no such index exists.
i := a
j := m
for i < j {
h := int(uint(i+j) >> 1)
if !(cmp(data[m], data[h]) < 0) {
i = h + 1
} else {
j = h
}
}
// Swap values until data[m] reaches the position i.
for k := m; k > i; k-- {
data[k], data[k-1] = data[k-1], data[k]
}
return
}
mid := int(uint(a+b) >> 1)
n := mid + m
var start, r int
if m > mid {
start = n - b
r = mid
} else {
start = a
r = m
}
p := n - 1
for start < r {
c := int(uint(start+r) >> 1)
if !(cmp(data[p-c], data[c]) < 0) {
start = c + 1
} else {
r = c
}
}
end := n - start
if start < m && m < end {
rotateCmpFunc(data, start, m, end, cmp)
}
if a < start && start < mid {
symMergeCmpFunc(data, a, start, mid, cmp)
}
if mid < end && end < b {
symMergeCmpFunc(data, mid, end, b, cmp)
}
}
// rotateCmpFunc rotates two consecutive blocks u = data[a:m] and v = data[m:b] in data:
// Data of the form 'x u v y' is changed to 'x v u y'.
// rotate performs at most b-a many calls to data.Swap,
// and it assumes non-degenerate arguments: a < m && m < b.
func rotateCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) {
i := m - a
j := b - m
for i != j {
if i > j {
swapRangeCmpFunc(data, m-i, m, j, cmp)
i -= j
} else {
swapRangeCmpFunc(data, m-i, m+j-i, i, cmp)
j -= i
}
}
// i == j
swapRangeCmpFunc(data, m-i, m, i, cmp)
}

View File

@@ -1,481 +0,0 @@
// Code generated by gen_sort_variants.go; DO NOT EDIT.
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package slices
import "golang.org/x/exp/constraints"
// insertionSortOrdered sorts data[a:b] using insertion sort.
func insertionSortOrdered[E constraints.Ordered](data []E, a, b int) {
for i := a + 1; i < b; i++ {
for j := i; j > a && cmpLess(data[j], data[j-1]); j-- {
data[j], data[j-1] = data[j-1], data[j]
}
}
}
// siftDownOrdered implements the heap property on data[lo:hi].
// first is an offset into the array where the root of the heap lies.
func siftDownOrdered[E constraints.Ordered](data []E, lo, hi, first int) {
root := lo
for {
child := 2*root + 1
if child >= hi {
break
}
if child+1 < hi && cmpLess(data[first+child], data[first+child+1]) {
child++
}
if !cmpLess(data[first+root], data[first+child]) {
return
}
data[first+root], data[first+child] = data[first+child], data[first+root]
root = child
}
}
func heapSortOrdered[E constraints.Ordered](data []E, a, b int) {
first := a
lo := 0
hi := b - a
// Build heap with greatest element at top.
for i := (hi - 1) / 2; i >= 0; i-- {
siftDownOrdered(data, i, hi, first)
}
// Pop elements, largest first, into end of data.
for i := hi - 1; i >= 0; i-- {
data[first], data[first+i] = data[first+i], data[first]
siftDownOrdered(data, lo, i, first)
}
}
// pdqsortOrdered sorts data[a:b].
// The algorithm based on pattern-defeating quicksort(pdqsort), but without the optimizations from BlockQuicksort.
// pdqsort paper: https://arxiv.org/pdf/2106.05123.pdf
// C++ implementation: https://github.com/orlp/pdqsort
// Rust implementation: https://docs.rs/pdqsort/latest/pdqsort/
// limit is the number of allowed bad (very unbalanced) pivots before falling back to heapsort.
func pdqsortOrdered[E constraints.Ordered](data []E, a, b, limit int) {
const maxInsertion = 12
var (
wasBalanced = true // whether the last partitioning was reasonably balanced
wasPartitioned = true // whether the slice was already partitioned
)
for {
length := b - a
if length <= maxInsertion {
insertionSortOrdered(data, a, b)
return
}
// Fall back to heapsort if too many bad choices were made.
if limit == 0 {
heapSortOrdered(data, a, b)
return
}
// If the last partitioning was imbalanced, we need to breaking patterns.
if !wasBalanced {
breakPatternsOrdered(data, a, b)
limit--
}
pivot, hint := choosePivotOrdered(data, a, b)
if hint == decreasingHint {
reverseRangeOrdered(data, a, b)
// The chosen pivot was pivot-a elements after the start of the array.
// After reversing it is pivot-a elements before the end of the array.
// The idea came from Rust's implementation.
pivot = (b - 1) - (pivot - a)
hint = increasingHint
}
// The slice is likely already sorted.
if wasBalanced && wasPartitioned && hint == increasingHint {
if partialInsertionSortOrdered(data, a, b) {
return
}
}
// Probably the slice contains many duplicate elements, partition the slice into
// elements equal to and elements greater than the pivot.
if a > 0 && !cmpLess(data[a-1], data[pivot]) {
mid := partitionEqualOrdered(data, a, b, pivot)
a = mid
continue
}
mid, alreadyPartitioned := partitionOrdered(data, a, b, pivot)
wasPartitioned = alreadyPartitioned
leftLen, rightLen := mid-a, b-mid
balanceThreshold := length / 8
if leftLen < rightLen {
wasBalanced = leftLen >= balanceThreshold
pdqsortOrdered(data, a, mid, limit)
a = mid + 1
} else {
wasBalanced = rightLen >= balanceThreshold
pdqsortOrdered(data, mid+1, b, limit)
b = mid
}
}
}
// partitionOrdered does one quicksort partition.
// Let p = data[pivot]
// Moves elements in data[a:b] around, so that data[i]<p and data[j]>=p for i<newpivot and j>newpivot.
// On return, data[newpivot] = p
func partitionOrdered[E constraints.Ordered](data []E, a, b, pivot int) (newpivot int, alreadyPartitioned bool) {
data[a], data[pivot] = data[pivot], data[a]
i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
for i <= j && cmpLess(data[i], data[a]) {
i++
}
for i <= j && !cmpLess(data[j], data[a]) {
j--
}
if i > j {
data[j], data[a] = data[a], data[j]
return j, true
}
data[i], data[j] = data[j], data[i]
i++
j--
for {
for i <= j && cmpLess(data[i], data[a]) {
i++
}
for i <= j && !cmpLess(data[j], data[a]) {
j--
}
if i > j {
break
}
data[i], data[j] = data[j], data[i]
i++
j--
}
data[j], data[a] = data[a], data[j]
return j, false
}
// partitionEqualOrdered partitions data[a:b] into elements equal to data[pivot] followed by elements greater than data[pivot].
// It assumed that data[a:b] does not contain elements smaller than the data[pivot].
func partitionEqualOrdered[E constraints.Ordered](data []E, a, b, pivot int) (newpivot int) {
data[a], data[pivot] = data[pivot], data[a]
i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned
for {
for i <= j && !cmpLess(data[a], data[i]) {
i++
}
for i <= j && cmpLess(data[a], data[j]) {
j--
}
if i > j {
break
}
data[i], data[j] = data[j], data[i]
i++
j--
}
return i
}
// partialInsertionSortOrdered partially sorts a slice, returns true if the slice is sorted at the end.
func partialInsertionSortOrdered[E constraints.Ordered](data []E, a, b int) bool {
const (
maxSteps = 5 // maximum number of adjacent out-of-order pairs that will get shifted
shortestShifting = 50 // don't shift any elements on short arrays
)
i := a + 1
for j := 0; j < maxSteps; j++ {
for i < b && !cmpLess(data[i], data[i-1]) {
i++
}
if i == b {
return true
}
if b-a < shortestShifting {
return false
}
data[i], data[i-1] = data[i-1], data[i]
// Shift the smaller one to the left.
if i-a >= 2 {
for j := i - 1; j >= 1; j-- {
if !cmpLess(data[j], data[j-1]) {
break
}
data[j], data[j-1] = data[j-1], data[j]
}
}
// Shift the greater one to the right.
if b-i >= 2 {
for j := i + 1; j < b; j++ {
if !cmpLess(data[j], data[j-1]) {
break
}
data[j], data[j-1] = data[j-1], data[j]
}
}
}
return false
}
// breakPatternsOrdered scatters some elements around in an attempt to break some patterns
// that might cause imbalanced partitions in quicksort.
func breakPatternsOrdered[E constraints.Ordered](data []E, a, b int) {
length := b - a
if length >= 8 {
random := xorshift(length)
modulus := nextPowerOfTwo(length)
for idx := a + (length/4)*2 - 1; idx <= a+(length/4)*2+1; idx++ {
other := int(uint(random.Next()) & (modulus - 1))
if other >= length {
other -= length
}
data[idx], data[a+other] = data[a+other], data[idx]
}
}
}
// choosePivotOrdered chooses a pivot in data[a:b].
//
// [0,8): chooses a static pivot.
// [8,shortestNinther): uses the simple median-of-three method.
// [shortestNinther,∞): uses the Tukey ninther method.
func choosePivotOrdered[E constraints.Ordered](data []E, a, b int) (pivot int, hint sortedHint) {
const (
shortestNinther = 50
maxSwaps = 4 * 3
)
l := b - a
var (
swaps int
i = a + l/4*1
j = a + l/4*2
k = a + l/4*3
)
if l >= 8 {
if l >= shortestNinther {
// Tukey ninther method, the idea came from Rust's implementation.
i = medianAdjacentOrdered(data, i, &swaps)
j = medianAdjacentOrdered(data, j, &swaps)
k = medianAdjacentOrdered(data, k, &swaps)
}
// Find the median among i, j, k and stores it into j.
j = medianOrdered(data, i, j, k, &swaps)
}
switch swaps {
case 0:
return j, increasingHint
case maxSwaps:
return j, decreasingHint
default:
return j, unknownHint
}
}
// order2Ordered returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a.
func order2Ordered[E constraints.Ordered](data []E, a, b int, swaps *int) (int, int) {
if cmpLess(data[b], data[a]) {
*swaps++
return b, a
}
return a, b
}
// medianOrdered returns x where data[x] is the median of data[a],data[b],data[c], where x is a, b, or c.
func medianOrdered[E constraints.Ordered](data []E, a, b, c int, swaps *int) int {
a, b = order2Ordered(data, a, b, swaps)
b, c = order2Ordered(data, b, c, swaps)
a, b = order2Ordered(data, a, b, swaps)
return b
}
// medianAdjacentOrdered finds the median of data[a - 1], data[a], data[a + 1] and stores the index into a.
func medianAdjacentOrdered[E constraints.Ordered](data []E, a int, swaps *int) int {
return medianOrdered(data, a-1, a, a+1, swaps)
}
func reverseRangeOrdered[E constraints.Ordered](data []E, a, b int) {
i := a
j := b - 1
for i < j {
data[i], data[j] = data[j], data[i]
i++
j--
}
}
func swapRangeOrdered[E constraints.Ordered](data []E, a, b, n int) {
for i := 0; i < n; i++ {
data[a+i], data[b+i] = data[b+i], data[a+i]
}
}
func stableOrdered[E constraints.Ordered](data []E, n int) {
blockSize := 20 // must be > 0
a, b := 0, blockSize
for b <= n {
insertionSortOrdered(data, a, b)
a = b
b += blockSize
}
insertionSortOrdered(data, a, n)
for blockSize < n {
a, b = 0, 2*blockSize
for b <= n {
symMergeOrdered(data, a, a+blockSize, b)
a = b
b += 2 * blockSize
}
if m := a + blockSize; m < n {
symMergeOrdered(data, a, m, n)
}
blockSize *= 2
}
}
// symMergeOrdered merges the two sorted subsequences data[a:m] and data[m:b] using
// the SymMerge algorithm from Pok-Son Kim and Arne Kutzner, "Stable Minimum
// Storage Merging by Symmetric Comparisons", in Susanne Albers and Tomasz
// Radzik, editors, Algorithms - ESA 2004, volume 3221 of Lecture Notes in
// Computer Science, pages 714-723. Springer, 2004.
//
// Let M = m-a and N = b-n. Wolog M < N.
// The recursion depth is bound by ceil(log(N+M)).
// The algorithm needs O(M*log(N/M + 1)) calls to data.Less.
// The algorithm needs O((M+N)*log(M)) calls to data.Swap.
//
// The paper gives O((M+N)*log(M)) as the number of assignments assuming a
// rotation algorithm which uses O(M+N+gcd(M+N)) assignments. The argumentation
// in the paper carries through for Swap operations, especially as the block
// swapping rotate uses only O(M+N) Swaps.
//
// symMerge assumes non-degenerate arguments: a < m && m < b.
// Having the caller check this condition eliminates many leaf recursion calls,
// which improves performance.
func symMergeOrdered[E constraints.Ordered](data []E, a, m, b int) {
// Avoid unnecessary recursions of symMerge
// by direct insertion of data[a] into data[m:b]
// if data[a:m] only contains one element.
if m-a == 1 {
// Use binary search to find the lowest index i
// such that data[i] >= data[a] for m <= i < b.
// Exit the search loop with i == b in case no such index exists.
i := m
j := b
for i < j {
h := int(uint(i+j) >> 1)
if cmpLess(data[h], data[a]) {
i = h + 1
} else {
j = h
}
}
// Swap values until data[a] reaches the position before i.
for k := a; k < i-1; k++ {
data[k], data[k+1] = data[k+1], data[k]
}
return
}
// Avoid unnecessary recursions of symMerge
// by direct insertion of data[m] into data[a:m]
// if data[m:b] only contains one element.
if b-m == 1 {
// Use binary search to find the lowest index i
// such that data[i] > data[m] for a <= i < m.
// Exit the search loop with i == m in case no such index exists.
i := a
j := m
for i < j {
h := int(uint(i+j) >> 1)
if !cmpLess(data[m], data[h]) {
i = h + 1
} else {
j = h
}
}
// Swap values until data[m] reaches the position i.
for k := m; k > i; k-- {
data[k], data[k-1] = data[k-1], data[k]
}
return
}
mid := int(uint(a+b) >> 1)
n := mid + m
var start, r int
if m > mid {
start = n - b
r = mid
} else {
start = a
r = m
}
p := n - 1
for start < r {
c := int(uint(start+r) >> 1)
if !cmpLess(data[p-c], data[c]) {
start = c + 1
} else {
r = c
}
}
end := n - start
if start < m && m < end {
rotateOrdered(data, start, m, end)
}
if a < start && start < mid {
symMergeOrdered(data, a, start, mid)
}
if mid < end && end < b {
symMergeOrdered(data, mid, end, b)
}
}
// rotateOrdered rotates two consecutive blocks u = data[a:m] and v = data[m:b] in data:
// Data of the form 'x u v y' is changed to 'x v u y'.
// rotate performs at most b-a many calls to data.Swap,
// and it assumes non-degenerate arguments: a < m && m < b.
func rotateOrdered[E constraints.Ordered](data []E, a, m, b int) {
i := m - a
j := b - m
for i != j {
if i > j {
swapRangeOrdered(data, m-i, m, j)
i -= j
} else {
swapRangeOrdered(data, m-i, m+j-i, i)
j -= i
}
}
// i == j
swapRangeOrdered(data, m-i, m, i)
}

View File

@@ -156,7 +156,7 @@ from the generated architecture-specific files listed below, and merge these
into a common file for each OS. into a common file for each OS.
The merge is performed in the following steps: The merge is performed in the following steps:
1. Construct the set of common code that is idential in all architecture-specific files. 1. Construct the set of common code that is identical in all architecture-specific files.
2. Write this common code to the merged file. 2. Write this common code to the merged file.
3. Remove the common code from all architecture-specific files. 3. Remove the common code from all architecture-specific files.

36
vendor/golang.org/x/sys/unix/auxv.go generated vendored Normal file
View File

@@ -0,0 +1,36 @@
// Copyright 2025 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build go1.21 && (aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos)
package unix
import (
"syscall"
"unsafe"
)
//go:linkname runtime_getAuxv runtime.getAuxv
func runtime_getAuxv() []uintptr
// Auxv returns the ELF auxiliary vector as a sequence of key/value pairs.
// The returned slice is always a fresh copy, owned by the caller.
// It returns an error on non-ELF platforms, or if the auxiliary vector cannot be accessed,
// which happens in some locked-down environments and build modes.
func Auxv() ([][2]uintptr, error) {
vec := runtime_getAuxv()
vecLen := len(vec)
if vecLen == 0 {
return nil, syscall.ENOENT
}
if vecLen%2 != 0 {
return nil, syscall.EINVAL
}
result := make([]uintptr, vecLen)
copy(result, vec)
return unsafe.Slice((*[2]uintptr)(unsafe.Pointer(&result[0])), vecLen/2), nil
}

13
vendor/golang.org/x/sys/unix/auxv_unsupported.go generated vendored Normal file
View File

@@ -0,0 +1,13 @@
// Copyright 2025 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !go1.21 && (aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos)
package unix
import "syscall"
func Auxv() ([][2]uintptr, error) {
return nil, syscall.ENOTSUP
}

View File

@@ -58,6 +58,102 @@ func IoctlGetEthtoolDrvinfo(fd int, ifname string) (*EthtoolDrvinfo, error) {
return &value, err return &value, err
} }
// IoctlGetEthtoolTsInfo fetches ethtool timestamping and PHC
// association for the network device specified by ifname.
func IoctlGetEthtoolTsInfo(fd int, ifname string) (*EthtoolTsInfo, error) {
ifr, err := NewIfreq(ifname)
if err != nil {
return nil, err
}
value := EthtoolTsInfo{Cmd: ETHTOOL_GET_TS_INFO}
ifrd := ifr.withData(unsafe.Pointer(&value))
err = ioctlIfreqData(fd, SIOCETHTOOL, &ifrd)
return &value, err
}
// IoctlGetHwTstamp retrieves the hardware timestamping configuration
// for the network device specified by ifname.
func IoctlGetHwTstamp(fd int, ifname string) (*HwTstampConfig, error) {
ifr, err := NewIfreq(ifname)
if err != nil {
return nil, err
}
value := HwTstampConfig{}
ifrd := ifr.withData(unsafe.Pointer(&value))
err = ioctlIfreqData(fd, SIOCGHWTSTAMP, &ifrd)
return &value, err
}
// IoctlSetHwTstamp updates the hardware timestamping configuration for
// the network device specified by ifname.
func IoctlSetHwTstamp(fd int, ifname string, cfg *HwTstampConfig) error {
ifr, err := NewIfreq(ifname)
if err != nil {
return err
}
ifrd := ifr.withData(unsafe.Pointer(cfg))
return ioctlIfreqData(fd, SIOCSHWTSTAMP, &ifrd)
}
// FdToClockID derives the clock ID from the file descriptor number
// - see clock_gettime(3), FD_TO_CLOCKID macros. The resulting ID is
// suitable for system calls like ClockGettime.
func FdToClockID(fd int) int32 { return int32((int(^fd) << 3) | 3) }
// IoctlPtpClockGetcaps returns the description of a given PTP device.
func IoctlPtpClockGetcaps(fd int) (*PtpClockCaps, error) {
var value PtpClockCaps
err := ioctlPtr(fd, PTP_CLOCK_GETCAPS2, unsafe.Pointer(&value))
return &value, err
}
// IoctlPtpSysOffsetPrecise returns a description of the clock
// offset compared to the system clock.
func IoctlPtpSysOffsetPrecise(fd int) (*PtpSysOffsetPrecise, error) {
var value PtpSysOffsetPrecise
err := ioctlPtr(fd, PTP_SYS_OFFSET_PRECISE2, unsafe.Pointer(&value))
return &value, err
}
// IoctlPtpSysOffsetExtended returns an extended description of the
// clock offset compared to the system clock. The samples parameter
// specifies the desired number of measurements.
func IoctlPtpSysOffsetExtended(fd int, samples uint) (*PtpSysOffsetExtended, error) {
value := PtpSysOffsetExtended{Samples: uint32(samples)}
err := ioctlPtr(fd, PTP_SYS_OFFSET_EXTENDED2, unsafe.Pointer(&value))
return &value, err
}
// IoctlPtpPinGetfunc returns the configuration of the specified
// I/O pin on given PTP device.
func IoctlPtpPinGetfunc(fd int, index uint) (*PtpPinDesc, error) {
value := PtpPinDesc{Index: uint32(index)}
err := ioctlPtr(fd, PTP_PIN_GETFUNC2, unsafe.Pointer(&value))
return &value, err
}
// IoctlPtpPinSetfunc updates configuration of the specified PTP
// I/O pin.
func IoctlPtpPinSetfunc(fd int, pd *PtpPinDesc) error {
return ioctlPtr(fd, PTP_PIN_SETFUNC2, unsafe.Pointer(pd))
}
// IoctlPtpPeroutRequest configures the periodic output mode of the
// PTP I/O pins.
func IoctlPtpPeroutRequest(fd int, r *PtpPeroutRequest) error {
return ioctlPtr(fd, PTP_PEROUT_REQUEST2, unsafe.Pointer(r))
}
// IoctlPtpExttsRequest configures the external timestamping mode
// of the PTP I/O pins.
func IoctlPtpExttsRequest(fd int, r *PtpExttsRequest) error {
return ioctlPtr(fd, PTP_EXTTS_REQUEST2, unsafe.Pointer(r))
}
// IoctlGetWatchdogInfo fetches information about a watchdog device from the // IoctlGetWatchdogInfo fetches information about a watchdog device from the
// Linux watchdog API. For more information, see: // Linux watchdog API. For more information, see:
// https://www.kernel.org/doc/html/latest/watchdog/watchdog-api.html. // https://www.kernel.org/doc/html/latest/watchdog/watchdog-api.html.

View File

@@ -158,6 +158,16 @@ includes_Linux='
#endif #endif
#define _GNU_SOURCE #define _GNU_SOURCE
// See the description in unix/linux/types.go
#if defined(__ARM_EABI__) || \
(defined(__mips__) && (_MIPS_SIM == _ABIO32)) || \
(defined(__powerpc__) && (!defined(__powerpc64__)))
# ifdef _TIME_BITS
# undef _TIME_BITS
# endif
# define _TIME_BITS 32
#endif
// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of // <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of
// these structures. We just include them copied from <bits/termios.h>. // these structures. We just include them copied from <bits/termios.h>.
#if defined(__powerpc__) #if defined(__powerpc__)
@@ -256,6 +266,7 @@ struct ltchars {
#include <linux/nsfs.h> #include <linux/nsfs.h>
#include <linux/perf_event.h> #include <linux/perf_event.h>
#include <linux/pps.h> #include <linux/pps.h>
#include <linux/ptp_clock.h>
#include <linux/ptrace.h> #include <linux/ptrace.h>
#include <linux/random.h> #include <linux/random.h>
#include <linux/reboot.h> #include <linux/reboot.h>
@@ -527,6 +538,7 @@ ccflags="$@"
$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MREMAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ || $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MREMAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ ||
$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ || $2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||
$2 ~ /^NFC_.*_(MAX)?SIZE$/ || $2 ~ /^NFC_.*_(MAX)?SIZE$/ ||
$2 ~ /^PTP_/ ||
$2 ~ /^RAW_PAYLOAD_/ || $2 ~ /^RAW_PAYLOAD_/ ||
$2 ~ /^[US]F_/ || $2 ~ /^[US]F_/ ||
$2 ~ /^TP_STATUS_/ || $2 ~ /^TP_STATUS_/ ||
@@ -656,7 +668,7 @@ errors=$(
signals=$( signals=$(
echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags | echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |
grep -v 'SIGSTKSIZE\|SIGSTKSZ\|SIGRT\|SIGMAX64' | grep -E -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |
sort sort
) )
@@ -666,7 +678,7 @@ echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
sort >_error.grep sort >_error.grep
echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags | echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' |
grep -v 'SIGSTKSIZE\|SIGSTKSZ\|SIGRT\|SIGMAX64' | grep -E -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |
sort >_signal.grep sort >_signal.grep
echo '// mkerrors.sh' "$@" echo '// mkerrors.sh' "$@"

View File

@@ -360,7 +360,7 @@ func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int,
var status _C_int var status _C_int
var r Pid_t var r Pid_t
err = ERESTART err = ERESTART
// AIX wait4 may return with ERESTART errno, while the processus is still // AIX wait4 may return with ERESTART errno, while the process is still
// active. // active.
for err == ERESTART { for err == ERESTART {
r, err = wait4(Pid_t(pid), &status, options, rusage) r, err = wait4(Pid_t(pid), &status, options, rusage)

View File

@@ -603,6 +603,149 @@ func Connectx(fd int, srcIf uint32, srcAddr, dstAddr Sockaddr, associd SaeAssocI
} }
// sys connectx(fd int, endpoints *SaEndpoints, associd SaeAssocID, flags uint32, iov []Iovec, n *uintptr, connid *SaeConnID) (err error) // sys connectx(fd int, endpoints *SaEndpoints, associd SaeAssocID, flags uint32, iov []Iovec, n *uintptr, connid *SaeConnID) (err error)
const minIovec = 8
func Readv(fd int, iovs [][]byte) (n int, err error) {
if !darwinKernelVersionMin(11, 0, 0) {
return 0, ENOSYS
}
iovecs := make([]Iovec, 0, minIovec)
iovecs = appendBytes(iovecs, iovs)
n, err = readv(fd, iovecs)
readvRacedetect(iovecs, n, err)
return n, err
}
func Preadv(fd int, iovs [][]byte, offset int64) (n int, err error) {
if !darwinKernelVersionMin(11, 0, 0) {
return 0, ENOSYS
}
iovecs := make([]Iovec, 0, minIovec)
iovecs = appendBytes(iovecs, iovs)
n, err = preadv(fd, iovecs, offset)
readvRacedetect(iovecs, n, err)
return n, err
}
func Writev(fd int, iovs [][]byte) (n int, err error) {
if !darwinKernelVersionMin(11, 0, 0) {
return 0, ENOSYS
}
iovecs := make([]Iovec, 0, minIovec)
iovecs = appendBytes(iovecs, iovs)
if raceenabled {
raceReleaseMerge(unsafe.Pointer(&ioSync))
}
n, err = writev(fd, iovecs)
writevRacedetect(iovecs, n)
return n, err
}
func Pwritev(fd int, iovs [][]byte, offset int64) (n int, err error) {
if !darwinKernelVersionMin(11, 0, 0) {
return 0, ENOSYS
}
iovecs := make([]Iovec, 0, minIovec)
iovecs = appendBytes(iovecs, iovs)
if raceenabled {
raceReleaseMerge(unsafe.Pointer(&ioSync))
}
n, err = pwritev(fd, iovecs, offset)
writevRacedetect(iovecs, n)
return n, err
}
func appendBytes(vecs []Iovec, bs [][]byte) []Iovec {
for _, b := range bs {
var v Iovec
v.SetLen(len(b))
if len(b) > 0 {
v.Base = &b[0]
} else {
v.Base = (*byte)(unsafe.Pointer(&_zero))
}
vecs = append(vecs, v)
}
return vecs
}
func writevRacedetect(iovecs []Iovec, n int) {
if !raceenabled {
return
}
for i := 0; n > 0 && i < len(iovecs); i++ {
m := int(iovecs[i].Len)
if m > n {
m = n
}
n -= m
if m > 0 {
raceReadRange(unsafe.Pointer(iovecs[i].Base), m)
}
}
}
func readvRacedetect(iovecs []Iovec, n int, err error) {
if !raceenabled {
return
}
for i := 0; n > 0 && i < len(iovecs); i++ {
m := int(iovecs[i].Len)
if m > n {
m = n
}
n -= m
if m > 0 {
raceWriteRange(unsafe.Pointer(iovecs[i].Base), m)
}
}
if err == nil {
raceAcquire(unsafe.Pointer(&ioSync))
}
}
func darwinMajorMinPatch() (maj, min, patch int, err error) {
var un Utsname
err = Uname(&un)
if err != nil {
return
}
var mmp [3]int
c := 0
Loop:
for _, b := range un.Release[:] {
switch {
case b >= '0' && b <= '9':
mmp[c] = 10*mmp[c] + int(b-'0')
case b == '.':
c++
if c > 2 {
return 0, 0, 0, ENOTSUP
}
case b == 0:
break Loop
default:
return 0, 0, 0, ENOTSUP
}
}
if c != 2 {
return 0, 0, 0, ENOTSUP
}
return mmp[0], mmp[1], mmp[2], nil
}
func darwinKernelVersionMin(maj, min, patch int) bool {
actualMaj, actualMin, actualPatch, err := darwinMajorMinPatch()
if err != nil {
return false
}
return actualMaj > maj || actualMaj == maj && (actualMin > min || actualMin == min && actualPatch >= patch)
}
//sys sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error) //sys sendfile(infd int, outfd int, offset int64, len *int64, hdtr unsafe.Pointer, flags int) (err error)
//sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error) //sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error)
@@ -705,3 +848,7 @@ func Connectx(fd int, srcIf uint32, srcAddr, dstAddr Sockaddr, associd SaeAssocI
//sys write(fd int, p []byte) (n int, err error) //sys write(fd int, p []byte) (n int, err error)
//sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error)
//sys munmap(addr uintptr, length uintptr) (err error) //sys munmap(addr uintptr, length uintptr) (err error)
//sys readv(fd int, iovecs []Iovec) (n int, err error)
//sys preadv(fd int, iovecs []Iovec, offset int64) (n int, err error)
//sys writev(fd int, iovecs []Iovec) (n int, err error)
//sys pwritev(fd int, iovecs []Iovec, offset int64) (n int, err error)

View File

@@ -246,6 +246,18 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e
return sendfile(outfd, infd, offset, count) return sendfile(outfd, infd, offset, count)
} }
func Dup3(oldfd, newfd, flags int) error {
if oldfd == newfd || flags&^O_CLOEXEC != 0 {
return EINVAL
}
how := F_DUP2FD
if flags&O_CLOEXEC != 0 {
how = F_DUP2FD_CLOEXEC
}
_, err := fcntl(oldfd, how, newfd)
return err
}
/* /*
* Exposed directly * Exposed directly
*/ */

View File

@@ -13,6 +13,7 @@ package unix
import ( import (
"encoding/binary" "encoding/binary"
"slices"
"strconv" "strconv"
"syscall" "syscall"
"time" "time"
@@ -417,7 +418,7 @@ func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
return nil, 0, EINVAL return nil, 0, EINVAL
} }
sa.raw.Family = AF_UNIX sa.raw.Family = AF_UNIX
for i := 0; i < n; i++ { for i := range n {
sa.raw.Path[i] = int8(name[i]) sa.raw.Path[i] = int8(name[i])
} }
// length is family (uint16), name, NUL. // length is family (uint16), name, NUL.
@@ -507,7 +508,7 @@ func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) {
psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm)) psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm))
psm[0] = byte(sa.PSM) psm[0] = byte(sa.PSM)
psm[1] = byte(sa.PSM >> 8) psm[1] = byte(sa.PSM >> 8)
for i := 0; i < len(sa.Addr); i++ { for i := range len(sa.Addr) {
sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i] sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i]
} }
cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid)) cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid))
@@ -589,11 +590,11 @@ func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) {
sa.raw.Family = AF_CAN sa.raw.Family = AF_CAN
sa.raw.Ifindex = int32(sa.Ifindex) sa.raw.Ifindex = int32(sa.Ifindex)
rx := (*[4]byte)(unsafe.Pointer(&sa.RxID)) rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
for i := 0; i < 4; i++ { for i := range 4 {
sa.raw.Addr[i] = rx[i] sa.raw.Addr[i] = rx[i]
} }
tx := (*[4]byte)(unsafe.Pointer(&sa.TxID)) tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
for i := 0; i < 4; i++ { for i := range 4 {
sa.raw.Addr[i+4] = tx[i] sa.raw.Addr[i+4] = tx[i]
} }
return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
@@ -618,11 +619,11 @@ func (sa *SockaddrCANJ1939) sockaddr() (unsafe.Pointer, _Socklen, error) {
sa.raw.Family = AF_CAN sa.raw.Family = AF_CAN
sa.raw.Ifindex = int32(sa.Ifindex) sa.raw.Ifindex = int32(sa.Ifindex)
n := (*[8]byte)(unsafe.Pointer(&sa.Name)) n := (*[8]byte)(unsafe.Pointer(&sa.Name))
for i := 0; i < 8; i++ { for i := range 8 {
sa.raw.Addr[i] = n[i] sa.raw.Addr[i] = n[i]
} }
p := (*[4]byte)(unsafe.Pointer(&sa.PGN)) p := (*[4]byte)(unsafe.Pointer(&sa.PGN))
for i := 0; i < 4; i++ { for i := range 4 {
sa.raw.Addr[i+8] = p[i] sa.raw.Addr[i+8] = p[i]
} }
sa.raw.Addr[12] = sa.Addr sa.raw.Addr[12] = sa.Addr
@@ -911,7 +912,7 @@ func (sa *SockaddrIUCV) sockaddr() (unsafe.Pointer, _Socklen, error) {
// These are EBCDIC encoded by the kernel, but we still need to pad them // These are EBCDIC encoded by the kernel, but we still need to pad them
// with blanks. Initializing with blanks allows the caller to feed in either // with blanks. Initializing with blanks allows the caller to feed in either
// a padded or an unpadded string. // a padded or an unpadded string.
for i := 0; i < 8; i++ { for i := range 8 {
sa.raw.Nodeid[i] = ' ' sa.raw.Nodeid[i] = ' '
sa.raw.User_id[i] = ' ' sa.raw.User_id[i] = ' '
sa.raw.Name[i] = ' ' sa.raw.Name[i] = ' '
@@ -1148,7 +1149,7 @@ func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
var user [8]byte var user [8]byte
var name [8]byte var name [8]byte
for i := 0; i < 8; i++ { for i := range 8 {
user[i] = byte(pp.User_id[i]) user[i] = byte(pp.User_id[i])
name[i] = byte(pp.Name[i]) name[i] = byte(pp.Name[i])
} }
@@ -1173,11 +1174,11 @@ func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
Ifindex: int(pp.Ifindex), Ifindex: int(pp.Ifindex),
} }
name := (*[8]byte)(unsafe.Pointer(&sa.Name)) name := (*[8]byte)(unsafe.Pointer(&sa.Name))
for i := 0; i < 8; i++ { for i := range 8 {
name[i] = pp.Addr[i] name[i] = pp.Addr[i]
} }
pgn := (*[4]byte)(unsafe.Pointer(&sa.PGN)) pgn := (*[4]byte)(unsafe.Pointer(&sa.PGN))
for i := 0; i < 4; i++ { for i := range 4 {
pgn[i] = pp.Addr[i+8] pgn[i] = pp.Addr[i+8]
} }
addr := (*[1]byte)(unsafe.Pointer(&sa.Addr)) addr := (*[1]byte)(unsafe.Pointer(&sa.Addr))
@@ -1188,11 +1189,11 @@ func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
Ifindex: int(pp.Ifindex), Ifindex: int(pp.Ifindex),
} }
rx := (*[4]byte)(unsafe.Pointer(&sa.RxID)) rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
for i := 0; i < 4; i++ { for i := range 4 {
rx[i] = pp.Addr[i] rx[i] = pp.Addr[i]
} }
tx := (*[4]byte)(unsafe.Pointer(&sa.TxID)) tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
for i := 0; i < 4; i++ { for i := range 4 {
tx[i] = pp.Addr[i+4] tx[i] = pp.Addr[i+4]
} }
return sa, nil return sa, nil
@@ -1295,6 +1296,48 @@ func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) {
return &value, err return &value, err
} }
// GetsockoptTCPCCVegasInfo returns algorithm specific congestion control information for a socket using the "vegas"
// algorithm.
//
// The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option:
//
// algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION)
func GetsockoptTCPCCVegasInfo(fd, level, opt int) (*TCPVegasInfo, error) {
var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment
vallen := _Socklen(SizeofTCPCCInfo)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
out := (*TCPVegasInfo)(unsafe.Pointer(&value[0]))
return out, err
}
// GetsockoptTCPCCDCTCPInfo returns algorithm specific congestion control information for a socket using the "dctp"
// algorithm.
//
// The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option:
//
// algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION)
func GetsockoptTCPCCDCTCPInfo(fd, level, opt int) (*TCPDCTCPInfo, error) {
var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment
vallen := _Socklen(SizeofTCPCCInfo)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
out := (*TCPDCTCPInfo)(unsafe.Pointer(&value[0]))
return out, err
}
// GetsockoptTCPCCBBRInfo returns algorithm specific congestion control information for a socket using the "bbr"
// algorithm.
//
// The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option:
//
// algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION)
func GetsockoptTCPCCBBRInfo(fd, level, opt int) (*TCPBBRInfo, error) {
var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment
vallen := _Socklen(SizeofTCPCCInfo)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
out := (*TCPBBRInfo)(unsafe.Pointer(&value[0]))
return out, err
}
// GetsockoptString returns the string value of the socket option opt for the // GetsockoptString returns the string value of the socket option opt for the
// socket associated with fd at the given socket level. // socket associated with fd at the given socket level.
func GetsockoptString(fd, level, opt int) (string, error) { func GetsockoptString(fd, level, opt int) (string, error) {
@@ -1818,6 +1861,7 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e
//sys ClockAdjtime(clockid int32, buf *Timex) (state int, err error) //sys ClockAdjtime(clockid int32, buf *Timex) (state int, err error)
//sys ClockGetres(clockid int32, res *Timespec) (err error) //sys ClockGetres(clockid int32, res *Timespec) (err error)
//sys ClockGettime(clockid int32, time *Timespec) (err error) //sys ClockGettime(clockid int32, time *Timespec) (err error)
//sys ClockSettime(clockid int32, time *Timespec) (err error)
//sys ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error) //sys ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error)
//sys Close(fd int) (err error) //sys Close(fd int) (err error)
//sys CloseRange(first uint, last uint, flags uint) (err error) //sys CloseRange(first uint, last uint, flags uint) (err error)
@@ -1959,7 +2003,26 @@ func Getpgrp() (pid int) {
//sysnb Getpid() (pid int) //sysnb Getpid() (pid int)
//sysnb Getppid() (ppid int) //sysnb Getppid() (ppid int)
//sys Getpriority(which int, who int) (prio int, err error) //sys Getpriority(which int, who int) (prio int, err error)
//sys Getrandom(buf []byte, flags int) (n int, err error)
func Getrandom(buf []byte, flags int) (n int, err error) {
vdsoRet, supported := vgetrandom(buf, uint32(flags))
if supported {
if vdsoRet < 0 {
return 0, errnoErr(syscall.Errno(-vdsoRet))
}
return vdsoRet, nil
}
var p *byte
if len(buf) > 0 {
p = &buf[0]
}
r, _, e := Syscall(SYS_GETRANDOM, uintptr(unsafe.Pointer(p)), uintptr(len(buf)), uintptr(flags))
if e != 0 {
return 0, errnoErr(e)
}
return int(r), nil
}
//sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Getrusage(who int, rusage *Rusage) (err error)
//sysnb Getsid(pid int) (sid int, err error) //sysnb Getsid(pid int) (sid int, err error)
//sysnb Gettid() (tid int) //sysnb Gettid() (tid int)
@@ -2154,10 +2217,7 @@ func readvRacedetect(iovecs []Iovec, n int, err error) {
return return
} }
for i := 0; n > 0 && i < len(iovecs); i++ { for i := 0; n > 0 && i < len(iovecs); i++ {
m := int(iovecs[i].Len) m := min(int(iovecs[i].Len), n)
if m > n {
m = n
}
n -= m n -= m
if m > 0 { if m > 0 {
raceWriteRange(unsafe.Pointer(iovecs[i].Base), m) raceWriteRange(unsafe.Pointer(iovecs[i].Base), m)
@@ -2208,10 +2268,7 @@ func writevRacedetect(iovecs []Iovec, n int) {
return return
} }
for i := 0; n > 0 && i < len(iovecs); i++ { for i := 0; n > 0 && i < len(iovecs); i++ {
m := int(iovecs[i].Len) m := min(int(iovecs[i].Len), n)
if m > n {
m = n
}
n -= m n -= m
if m > 0 { if m > 0 {
raceReadRange(unsafe.Pointer(iovecs[i].Base), m) raceReadRange(unsafe.Pointer(iovecs[i].Base), m)
@@ -2258,12 +2315,7 @@ func isGroupMember(gid int) bool {
return false return false
} }
for _, g := range groups { return slices.Contains(groups, gid)
if g == gid {
return true
}
}
return false
} }
func isCapDacOverrideSet() bool { func isCapDacOverrideSet() bool {

View File

@@ -182,3 +182,5 @@ func KexecFileLoad(kernelFd int, initrdFd int, cmdline string, flags int) error
} }
return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags) return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags)
} }
const SYS_FSTATAT = SYS_NEWFSTATAT

View File

@@ -214,3 +214,5 @@ func KexecFileLoad(kernelFd int, initrdFd int, cmdline string, flags int) error
} }
return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags) return kexecFileLoad(kernelFd, initrdFd, cmdlineLen, cmdline, flags)
} }
const SYS_FSTATAT = SYS_NEWFSTATAT

View File

@@ -187,3 +187,5 @@ func RISCVHWProbe(pairs []RISCVHWProbePairs, set *CPUSet, flags uint) (err error
} }
return riscvHWProbe(pairs, setSize, set, flags) return riscvHWProbe(pairs, setSize, set, flags)
} }
const SYS_FSTATAT = SYS_NEWFSTATAT

View File

@@ -1102,3 +1102,90 @@ func (s *Strioctl) SetInt(i int) {
func IoctlSetStrioctlRetInt(fd int, req int, s *Strioctl) (int, error) { func IoctlSetStrioctlRetInt(fd int, req int, s *Strioctl) (int, error) {
return ioctlPtrRet(fd, req, unsafe.Pointer(s)) return ioctlPtrRet(fd, req, unsafe.Pointer(s))
} }
// Ucred Helpers
// See ucred(3c) and getpeerucred(3c)
//sys getpeerucred(fd uintptr, ucred *uintptr) (err error)
//sys ucredFree(ucred uintptr) = ucred_free
//sys ucredGet(pid int) (ucred uintptr, err error) = ucred_get
//sys ucredGeteuid(ucred uintptr) (uid int) = ucred_geteuid
//sys ucredGetegid(ucred uintptr) (gid int) = ucred_getegid
//sys ucredGetruid(ucred uintptr) (uid int) = ucred_getruid
//sys ucredGetrgid(ucred uintptr) (gid int) = ucred_getrgid
//sys ucredGetsuid(ucred uintptr) (uid int) = ucred_getsuid
//sys ucredGetsgid(ucred uintptr) (gid int) = ucred_getsgid
//sys ucredGetpid(ucred uintptr) (pid int) = ucred_getpid
// Ucred is an opaque struct that holds user credentials.
type Ucred struct {
ucred uintptr
}
// We need to ensure that ucredFree is called on the underlying ucred
// when the Ucred is garbage collected.
func ucredFinalizer(u *Ucred) {
ucredFree(u.ucred)
}
func GetPeerUcred(fd uintptr) (*Ucred, error) {
var ucred uintptr
err := getpeerucred(fd, &ucred)
if err != nil {
return nil, err
}
result := &Ucred{
ucred: ucred,
}
// set the finalizer on the result so that the ucred will be freed
runtime.SetFinalizer(result, ucredFinalizer)
return result, nil
}
func UcredGet(pid int) (*Ucred, error) {
ucred, err := ucredGet(pid)
if err != nil {
return nil, err
}
result := &Ucred{
ucred: ucred,
}
// set the finalizer on the result so that the ucred will be freed
runtime.SetFinalizer(result, ucredFinalizer)
return result, nil
}
func (u *Ucred) Geteuid() int {
defer runtime.KeepAlive(u)
return ucredGeteuid(u.ucred)
}
func (u *Ucred) Getruid() int {
defer runtime.KeepAlive(u)
return ucredGetruid(u.ucred)
}
func (u *Ucred) Getsuid() int {
defer runtime.KeepAlive(u)
return ucredGetsuid(u.ucred)
}
func (u *Ucred) Getegid() int {
defer runtime.KeepAlive(u)
return ucredGetegid(u.ucred)
}
func (u *Ucred) Getrgid() int {
defer runtime.KeepAlive(u)
return ucredGetrgid(u.ucred)
}
func (u *Ucred) Getsgid() int {
defer runtime.KeepAlive(u)
return ucredGetsgid(u.ucred)
}
func (u *Ucred) Getpid() int {
defer runtime.KeepAlive(u)
return ucredGetpid(u.ucred)
}

View File

@@ -768,6 +768,15 @@ func Munmap(b []byte) (err error) {
return mapper.Munmap(b) return mapper.Munmap(b)
} }
func MmapPtr(fd int, offset int64, addr unsafe.Pointer, length uintptr, prot int, flags int) (ret unsafe.Pointer, err error) {
xaddr, err := mapper.mmap(uintptr(addr), length, prot, flags, fd, offset)
return unsafe.Pointer(xaddr), err
}
func MunmapPtr(addr unsafe.Pointer, length uintptr) (err error) {
return mapper.munmap(uintptr(addr), length)
}
//sys Gethostname(buf []byte) (err error) = SYS___GETHOSTNAME_A //sys Gethostname(buf []byte) (err error) = SYS___GETHOSTNAME_A
//sysnb Getgid() (gid int) //sysnb Getgid() (gid int)
//sysnb Getpid() (pid int) //sysnb Getpid() (pid int)
@@ -816,10 +825,10 @@ func Lstat(path string, stat *Stat_t) (err error) {
// for checking symlinks begins with $VERSION/ $SYSNAME/ $SYSSYMR/ $SYSSYMA/ // for checking symlinks begins with $VERSION/ $SYSNAME/ $SYSSYMR/ $SYSSYMA/
func isSpecialPath(path []byte) (v bool) { func isSpecialPath(path []byte) (v bool) {
var special = [4][8]byte{ var special = [4][8]byte{
[8]byte{'V', 'E', 'R', 'S', 'I', 'O', 'N', '/'}, {'V', 'E', 'R', 'S', 'I', 'O', 'N', '/'},
[8]byte{'S', 'Y', 'S', 'N', 'A', 'M', 'E', '/'}, {'S', 'Y', 'S', 'N', 'A', 'M', 'E', '/'},
[8]byte{'S', 'Y', 'S', 'S', 'Y', 'M', 'R', '/'}, {'S', 'Y', 'S', 'S', 'Y', 'M', 'R', '/'},
[8]byte{'S', 'Y', 'S', 'S', 'Y', 'M', 'A', '/'}} {'S', 'Y', 'S', 'S', 'Y', 'M', 'A', '/'}}
var i, j int var i, j int
for i = 0; i < len(special); i++ { for i = 0; i < len(special); i++ {
@@ -3115,3 +3124,90 @@ func legacy_Mkfifoat(dirfd int, path string, mode uint32) (err error) {
//sys Posix_openpt(oflag int) (fd int, err error) = SYS_POSIX_OPENPT //sys Posix_openpt(oflag int) (fd int, err error) = SYS_POSIX_OPENPT
//sys Grantpt(fildes int) (rc int, err error) = SYS_GRANTPT //sys Grantpt(fildes int) (rc int, err error) = SYS_GRANTPT
//sys Unlockpt(fildes int) (rc int, err error) = SYS_UNLOCKPT //sys Unlockpt(fildes int) (rc int, err error) = SYS_UNLOCKPT
func fcntlAsIs(fd uintptr, cmd int, arg uintptr) (val int, err error) {
runtime.EnterSyscall()
r0, e2, e1 := CallLeFuncWithErr(GetZosLibVec()+SYS_FCNTL<<4, uintptr(fd), uintptr(cmd), arg)
runtime.ExitSyscall()
val = int(r0)
if int64(r0) == -1 {
err = errnoErr2(e1, e2)
}
return
}
func Fcntl(fd uintptr, cmd int, op interface{}) (ret int, err error) {
switch op.(type) {
case *Flock_t:
err = FcntlFlock(fd, cmd, op.(*Flock_t))
if err != nil {
ret = -1
}
return
case int:
return FcntlInt(fd, cmd, op.(int))
case *F_cnvrt:
return fcntlAsIs(fd, cmd, uintptr(unsafe.Pointer(op.(*F_cnvrt))))
case unsafe.Pointer:
return fcntlAsIs(fd, cmd, uintptr(op.(unsafe.Pointer)))
default:
return -1, EINVAL
}
return
}
func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
if raceenabled {
raceReleaseMerge(unsafe.Pointer(&ioSync))
}
return sendfile(outfd, infd, offset, count)
}
func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
// TODO: use LE call instead if the call is implemented
originalOffset, err := Seek(infd, 0, SEEK_CUR)
if err != nil {
return -1, err
}
//start reading data from in_fd
if offset != nil {
_, err := Seek(infd, *offset, SEEK_SET)
if err != nil {
return -1, err
}
}
buf := make([]byte, count)
readBuf := make([]byte, 0)
var n int = 0
for i := 0; i < count; i += n {
n, err := Read(infd, buf)
if n == 0 {
if err != nil {
return -1, err
} else { // EOF
break
}
}
readBuf = append(readBuf, buf...)
buf = buf[0:0]
}
n2, err := Write(outfd, readBuf)
if err != nil {
return -1, err
}
//When sendfile() returns, this variable will be set to the
// offset of the byte following the last byte that was read.
if offset != nil {
*offset = *offset + int64(n)
// If offset is not NULL, then sendfile() does not modify the file
// offset of in_fd
_, err := Seek(infd, originalOffset, SEEK_SET)
if err != nil {
return -1, err
}
}
return n2, nil
}

13
vendor/golang.org/x/sys/unix/vgetrandom_linux.go generated vendored Normal file
View File

@@ -0,0 +1,13 @@
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build linux && go1.24
package unix
import _ "unsafe"
//go:linkname vgetrandom runtime.vgetrandom
//go:noescape
func vgetrandom(p []byte, flags uint32) (ret int, supported bool)

11
vendor/golang.org/x/sys/unix/vgetrandom_unsupported.go generated vendored Normal file
View File

@@ -0,0 +1,11 @@
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !linux || !go1.24
package unix
func vgetrandom(p []byte, flags uint32) (ret int, supported bool) {
return -1, false
}

View File

@@ -321,6 +321,9 @@ const (
AUDIT_INTEGRITY_STATUS = 0x70a AUDIT_INTEGRITY_STATUS = 0x70a
AUDIT_IPC = 0x517 AUDIT_IPC = 0x517
AUDIT_IPC_SET_PERM = 0x51f AUDIT_IPC_SET_PERM = 0x51f
AUDIT_IPE_ACCESS = 0x58c
AUDIT_IPE_CONFIG_CHANGE = 0x58d
AUDIT_IPE_POLICY_LOAD = 0x58e
AUDIT_KERNEL = 0x7d0 AUDIT_KERNEL = 0x7d0
AUDIT_KERNEL_OTHER = 0x524 AUDIT_KERNEL_OTHER = 0x524
AUDIT_KERN_MODULE = 0x532 AUDIT_KERN_MODULE = 0x532
@@ -489,12 +492,14 @@ const (
BPF_F_ID = 0x20 BPF_F_ID = 0x20
BPF_F_NETFILTER_IP_DEFRAG = 0x1 BPF_F_NETFILTER_IP_DEFRAG = 0x1
BPF_F_QUERY_EFFECTIVE = 0x1 BPF_F_QUERY_EFFECTIVE = 0x1
BPF_F_REDIRECT_FLAGS = 0x19
BPF_F_REPLACE = 0x4 BPF_F_REPLACE = 0x4
BPF_F_SLEEPABLE = 0x10 BPF_F_SLEEPABLE = 0x10
BPF_F_STRICT_ALIGNMENT = 0x1 BPF_F_STRICT_ALIGNMENT = 0x1
BPF_F_TEST_REG_INVARIANTS = 0x80 BPF_F_TEST_REG_INVARIANTS = 0x80
BPF_F_TEST_RND_HI32 = 0x4 BPF_F_TEST_RND_HI32 = 0x4
BPF_F_TEST_RUN_ON_CPU = 0x1 BPF_F_TEST_RUN_ON_CPU = 0x1
BPF_F_TEST_SKB_CHECKSUM_COMPLETE = 0x4
BPF_F_TEST_STATE_FREQ = 0x8 BPF_F_TEST_STATE_FREQ = 0x8
BPF_F_TEST_XDP_LIVE_FRAMES = 0x2 BPF_F_TEST_XDP_LIVE_FRAMES = 0x2
BPF_F_XDP_DEV_BOUND_ONLY = 0x40 BPF_F_XDP_DEV_BOUND_ONLY = 0x40
@@ -1165,6 +1170,7 @@ const (
EXTA = 0xe EXTA = 0xe
EXTB = 0xf EXTB = 0xf
F2FS_SUPER_MAGIC = 0xf2f52010 F2FS_SUPER_MAGIC = 0xf2f52010
FALLOC_FL_ALLOCATE_RANGE = 0x0
FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_COLLAPSE_RANGE = 0x8
FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_INSERT_RANGE = 0x20
FALLOC_FL_KEEP_SIZE = 0x1 FALLOC_FL_KEEP_SIZE = 0x1
@@ -1239,6 +1245,7 @@ const (
FAN_REPORT_DFID_NAME = 0xc00 FAN_REPORT_DFID_NAME = 0xc00
FAN_REPORT_DFID_NAME_TARGET = 0x1e00 FAN_REPORT_DFID_NAME_TARGET = 0x1e00
FAN_REPORT_DIR_FID = 0x400 FAN_REPORT_DIR_FID = 0x400
FAN_REPORT_FD_ERROR = 0x2000
FAN_REPORT_FID = 0x200 FAN_REPORT_FID = 0x200
FAN_REPORT_NAME = 0x800 FAN_REPORT_NAME = 0x800
FAN_REPORT_PIDFD = 0x80 FAN_REPORT_PIDFD = 0x80
@@ -1324,8 +1331,10 @@ const (
FUSE_SUPER_MAGIC = 0x65735546 FUSE_SUPER_MAGIC = 0x65735546
FUTEXFS_SUPER_MAGIC = 0xbad1dea FUTEXFS_SUPER_MAGIC = 0xbad1dea
F_ADD_SEALS = 0x409 F_ADD_SEALS = 0x409
F_CREATED_QUERY = 0x404
F_DUPFD = 0x0 F_DUPFD = 0x0
F_DUPFD_CLOEXEC = 0x406 F_DUPFD_CLOEXEC = 0x406
F_DUPFD_QUERY = 0x403
F_EXLCK = 0x4 F_EXLCK = 0x4
F_GETFD = 0x1 F_GETFD = 0x1
F_GETFL = 0x3 F_GETFL = 0x3
@@ -1545,6 +1554,7 @@ const (
IPPROTO_ROUTING = 0x2b IPPROTO_ROUTING = 0x2b
IPPROTO_RSVP = 0x2e IPPROTO_RSVP = 0x2e
IPPROTO_SCTP = 0x84 IPPROTO_SCTP = 0x84
IPPROTO_SMC = 0x100
IPPROTO_TCP = 0x6 IPPROTO_TCP = 0x6
IPPROTO_TP = 0x1d IPPROTO_TP = 0x1d
IPPROTO_UDP = 0x11 IPPROTO_UDP = 0x11
@@ -1617,6 +1627,8 @@ const (
IPV6_UNICAST_IF = 0x4c IPV6_UNICAST_IF = 0x4c
IPV6_USER_FLOW = 0xe IPV6_USER_FLOW = 0xe
IPV6_V6ONLY = 0x1a IPV6_V6ONLY = 0x1a
IPV6_VERSION = 0x60
IPV6_VERSION_MASK = 0xf0
IPV6_XFRM_POLICY = 0x23 IPV6_XFRM_POLICY = 0x23
IP_ADD_MEMBERSHIP = 0x23 IP_ADD_MEMBERSHIP = 0x23
IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_ADD_SOURCE_MEMBERSHIP = 0x27
@@ -1798,6 +1810,8 @@ const (
LANDLOCK_ACCESS_NET_BIND_TCP = 0x1 LANDLOCK_ACCESS_NET_BIND_TCP = 0x1
LANDLOCK_ACCESS_NET_CONNECT_TCP = 0x2 LANDLOCK_ACCESS_NET_CONNECT_TCP = 0x2
LANDLOCK_CREATE_RULESET_VERSION = 0x1 LANDLOCK_CREATE_RULESET_VERSION = 0x1
LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET = 0x1
LANDLOCK_SCOPE_SIGNAL = 0x2
LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_OFF = 0x0
LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef
LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_HALT = 0xcdef0123
@@ -1859,6 +1873,7 @@ const (
MADV_UNMERGEABLE = 0xd MADV_UNMERGEABLE = 0xd
MADV_WILLNEED = 0x3 MADV_WILLNEED = 0x3
MADV_WIPEONFORK = 0x12 MADV_WIPEONFORK = 0x12
MAP_DROPPABLE = 0x8
MAP_FILE = 0x0 MAP_FILE = 0x0
MAP_FIXED = 0x10 MAP_FIXED = 0x10
MAP_FIXED_NOREPLACE = 0x100000 MAP_FIXED_NOREPLACE = 0x100000
@@ -1922,6 +1937,8 @@ const (
MNT_EXPIRE = 0x4 MNT_EXPIRE = 0x4
MNT_FORCE = 0x1 MNT_FORCE = 0x1
MNT_ID_REQ_SIZE_VER0 = 0x18 MNT_ID_REQ_SIZE_VER0 = 0x18
MNT_ID_REQ_SIZE_VER1 = 0x20
MNT_NS_INFO_SIZE_VER0 = 0x10
MODULE_INIT_COMPRESSED_FILE = 0x4 MODULE_INIT_COMPRESSED_FILE = 0x4
MODULE_INIT_IGNORE_MODVERSIONS = 0x1 MODULE_INIT_IGNORE_MODVERSIONS = 0x1
MODULE_INIT_IGNORE_VERMAGIC = 0x2 MODULE_INIT_IGNORE_VERMAGIC = 0x2
@@ -1957,6 +1974,7 @@ const (
MSG_PEEK = 0x2 MSG_PEEK = 0x2
MSG_PROXY = 0x10 MSG_PROXY = 0x10
MSG_RST = 0x1000 MSG_RST = 0x1000
MSG_SOCK_DEVMEM = 0x2000000
MSG_SYN = 0x400 MSG_SYN = 0x400
MSG_TRUNC = 0x20 MSG_TRUNC = 0x20
MSG_TRYHARD = 0x4 MSG_TRYHARD = 0x4
@@ -2073,6 +2091,7 @@ const (
NFC_ATR_REQ_MAXSIZE = 0x40 NFC_ATR_REQ_MAXSIZE = 0x40
NFC_ATR_RES_GB_MAXSIZE = 0x2f NFC_ATR_RES_GB_MAXSIZE = 0x2f
NFC_ATR_RES_MAXSIZE = 0x40 NFC_ATR_RES_MAXSIZE = 0x40
NFC_ATS_MAXSIZE = 0x14
NFC_COMM_ACTIVE = 0x0 NFC_COMM_ACTIVE = 0x0
NFC_COMM_PASSIVE = 0x1 NFC_COMM_PASSIVE = 0x1
NFC_DEVICE_NAME_MAXSIZE = 0x8 NFC_DEVICE_NAME_MAXSIZE = 0x8
@@ -2153,6 +2172,7 @@ const (
NFNL_SUBSYS_QUEUE = 0x3 NFNL_SUBSYS_QUEUE = 0x3
NFNL_SUBSYS_ULOG = 0x4 NFNL_SUBSYS_ULOG = 0x4
NFS_SUPER_MAGIC = 0x6969 NFS_SUPER_MAGIC = 0x6969
NFT_BITWISE_BOOL = 0x0
NFT_CHAIN_FLAGS = 0x7 NFT_CHAIN_FLAGS = 0x7
NFT_CHAIN_MAXNAMELEN = 0x100 NFT_CHAIN_MAXNAMELEN = 0x100
NFT_CT_MAX = 0x17 NFT_CT_MAX = 0x17
@@ -2187,7 +2207,7 @@ const (
NFT_REG_SIZE = 0x10 NFT_REG_SIZE = 0x10
NFT_REJECT_ICMPX_MAX = 0x3 NFT_REJECT_ICMPX_MAX = 0x3
NFT_RT_MAX = 0x4 NFT_RT_MAX = 0x4
NFT_SECMARK_CTX_MAXLEN = 0x100 NFT_SECMARK_CTX_MAXLEN = 0x1000
NFT_SET_MAXNAMELEN = 0x100 NFT_SET_MAXNAMELEN = 0x100
NFT_SOCKET_MAX = 0x3 NFT_SOCKET_MAX = 0x3
NFT_TABLE_F_MASK = 0x7 NFT_TABLE_F_MASK = 0x7
@@ -2356,9 +2376,11 @@ const (
PERF_MEM_LVLNUM_IO = 0xa PERF_MEM_LVLNUM_IO = 0xa
PERF_MEM_LVLNUM_L1 = 0x1 PERF_MEM_LVLNUM_L1 = 0x1
PERF_MEM_LVLNUM_L2 = 0x2 PERF_MEM_LVLNUM_L2 = 0x2
PERF_MEM_LVLNUM_L2_MHB = 0x5
PERF_MEM_LVLNUM_L3 = 0x3 PERF_MEM_LVLNUM_L3 = 0x3
PERF_MEM_LVLNUM_L4 = 0x4 PERF_MEM_LVLNUM_L4 = 0x4
PERF_MEM_LVLNUM_LFB = 0xc PERF_MEM_LVLNUM_LFB = 0xc
PERF_MEM_LVLNUM_MSC = 0x6
PERF_MEM_LVLNUM_NA = 0xf PERF_MEM_LVLNUM_NA = 0xf
PERF_MEM_LVLNUM_PMEM = 0xe PERF_MEM_LVLNUM_PMEM = 0xe
PERF_MEM_LVLNUM_RAM = 0xd PERF_MEM_LVLNUM_RAM = 0xd
@@ -2431,6 +2453,7 @@ const (
PRIO_PGRP = 0x1 PRIO_PGRP = 0x1
PRIO_PROCESS = 0x0 PRIO_PROCESS = 0x0
PRIO_USER = 0x2 PRIO_USER = 0x2
PROCFS_IOCTL_MAGIC = 'f'
PROC_SUPER_MAGIC = 0x9fa0 PROC_SUPER_MAGIC = 0x9fa0
PROT_EXEC = 0x4 PROT_EXEC = 0x4
PROT_GROWSDOWN = 0x1000000 PROT_GROWSDOWN = 0x1000000
@@ -2478,6 +2501,7 @@ const (
PR_GET_PDEATHSIG = 0x2 PR_GET_PDEATHSIG = 0x2
PR_GET_SECCOMP = 0x15 PR_GET_SECCOMP = 0x15
PR_GET_SECUREBITS = 0x1b PR_GET_SECUREBITS = 0x1b
PR_GET_SHADOW_STACK_STATUS = 0x4a
PR_GET_SPECULATION_CTRL = 0x34 PR_GET_SPECULATION_CTRL = 0x34
PR_GET_TAGGED_ADDR_CTRL = 0x38 PR_GET_TAGGED_ADDR_CTRL = 0x38
PR_GET_THP_DISABLE = 0x2a PR_GET_THP_DISABLE = 0x2a
@@ -2486,6 +2510,7 @@ const (
PR_GET_TIMING = 0xd PR_GET_TIMING = 0xd
PR_GET_TSC = 0x19 PR_GET_TSC = 0x19
PR_GET_UNALIGN = 0x5 PR_GET_UNALIGN = 0x5
PR_LOCK_SHADOW_STACK_STATUS = 0x4c
PR_MCE_KILL = 0x21 PR_MCE_KILL = 0x21
PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_CLEAR = 0x0
PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_DEFAULT = 0x2
@@ -2512,6 +2537,8 @@ const (
PR_PAC_GET_ENABLED_KEYS = 0x3d PR_PAC_GET_ENABLED_KEYS = 0x3d
PR_PAC_RESET_KEYS = 0x36 PR_PAC_RESET_KEYS = 0x36
PR_PAC_SET_ENABLED_KEYS = 0x3c PR_PAC_SET_ENABLED_KEYS = 0x3c
PR_PMLEN_MASK = 0x7f000000
PR_PMLEN_SHIFT = 0x18
PR_PPC_DEXCR_CTRL_CLEAR = 0x4 PR_PPC_DEXCR_CTRL_CLEAR = 0x4
PR_PPC_DEXCR_CTRL_CLEAR_ONEXEC = 0x10 PR_PPC_DEXCR_CTRL_CLEAR_ONEXEC = 0x10
PR_PPC_DEXCR_CTRL_EDITABLE = 0x1 PR_PPC_DEXCR_CTRL_EDITABLE = 0x1
@@ -2579,6 +2606,7 @@ const (
PR_SET_PTRACER = 0x59616d61 PR_SET_PTRACER = 0x59616d61
PR_SET_SECCOMP = 0x16 PR_SET_SECCOMP = 0x16
PR_SET_SECUREBITS = 0x1c PR_SET_SECUREBITS = 0x1c
PR_SET_SHADOW_STACK_STATUS = 0x4b
PR_SET_SPECULATION_CTRL = 0x35 PR_SET_SPECULATION_CTRL = 0x35
PR_SET_SYSCALL_USER_DISPATCH = 0x3b PR_SET_SYSCALL_USER_DISPATCH = 0x3b
PR_SET_TAGGED_ADDR_CTRL = 0x37 PR_SET_TAGGED_ADDR_CTRL = 0x37
@@ -2589,6 +2617,9 @@ const (
PR_SET_UNALIGN = 0x6 PR_SET_UNALIGN = 0x6
PR_SET_VMA = 0x53564d41 PR_SET_VMA = 0x53564d41
PR_SET_VMA_ANON_NAME = 0x0 PR_SET_VMA_ANON_NAME = 0x0
PR_SHADOW_STACK_ENABLE = 0x1
PR_SHADOW_STACK_PUSH = 0x4
PR_SHADOW_STACK_WRITE = 0x2
PR_SME_GET_VL = 0x40 PR_SME_GET_VL = 0x40
PR_SME_SET_VL = 0x3f PR_SME_SET_VL = 0x3f
PR_SME_SET_VL_ONEXEC = 0x40000 PR_SME_SET_VL_ONEXEC = 0x40000
@@ -2620,6 +2651,28 @@ const (
PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_NOPRINT = 0x1
PR_UNALIGN_SIGBUS = 0x2 PR_UNALIGN_SIGBUS = 0x2
PSTOREFS_MAGIC = 0x6165676c PSTOREFS_MAGIC = 0x6165676c
PTP_CLK_MAGIC = '='
PTP_ENABLE_FEATURE = 0x1
PTP_EXTTS_EDGES = 0x6
PTP_EXTTS_EVENT_VALID = 0x1
PTP_EXTTS_V1_VALID_FLAGS = 0x7
PTP_EXTTS_VALID_FLAGS = 0x1f
PTP_EXT_OFFSET = 0x10
PTP_FALLING_EDGE = 0x4
PTP_MAX_SAMPLES = 0x19
PTP_PEROUT_DUTY_CYCLE = 0x2
PTP_PEROUT_ONE_SHOT = 0x1
PTP_PEROUT_PHASE = 0x4
PTP_PEROUT_V1_VALID_FLAGS = 0x0
PTP_PEROUT_VALID_FLAGS = 0x7
PTP_PIN_GETFUNC = 0xc0603d06
PTP_PIN_GETFUNC2 = 0xc0603d0f
PTP_RISING_EDGE = 0x2
PTP_STRICT_FLAGS = 0x8
PTP_SYS_OFFSET_EXTENDED = 0xc4c03d09
PTP_SYS_OFFSET_EXTENDED2 = 0xc4c03d12
PTP_SYS_OFFSET_PRECISE = 0xc0403d08
PTP_SYS_OFFSET_PRECISE2 = 0xc0403d11
PTRACE_ATTACH = 0x10 PTRACE_ATTACH = 0x10
PTRACE_CONT = 0x7 PTRACE_CONT = 0x7
PTRACE_DETACH = 0x11 PTRACE_DETACH = 0x11
@@ -2876,7 +2929,6 @@ const (
RTM_NEWNEXTHOP = 0x68 RTM_NEWNEXTHOP = 0x68
RTM_NEWNEXTHOPBUCKET = 0x74 RTM_NEWNEXTHOPBUCKET = 0x74
RTM_NEWNSID = 0x58 RTM_NEWNSID = 0x58
RTM_NEWNVLAN = 0x70
RTM_NEWPREFIX = 0x34 RTM_NEWPREFIX = 0x34
RTM_NEWQDISC = 0x24 RTM_NEWQDISC = 0x24
RTM_NEWROUTE = 0x18 RTM_NEWROUTE = 0x18
@@ -2885,6 +2937,7 @@ const (
RTM_NEWTCLASS = 0x28 RTM_NEWTCLASS = 0x28
RTM_NEWTFILTER = 0x2c RTM_NEWTFILTER = 0x2c
RTM_NEWTUNNEL = 0x78 RTM_NEWTUNNEL = 0x78
RTM_NEWVLAN = 0x70
RTM_NR_FAMILIES = 0x1b RTM_NR_FAMILIES = 0x1b
RTM_NR_MSGTYPES = 0x6c RTM_NR_MSGTYPES = 0x6c
RTM_SETDCB = 0x4f RTM_SETDCB = 0x4f
@@ -2933,15 +2986,17 @@ const (
RUSAGE_SELF = 0x0 RUSAGE_SELF = 0x0
RUSAGE_THREAD = 0x1 RUSAGE_THREAD = 0x1
RWF_APPEND = 0x10 RWF_APPEND = 0x10
RWF_ATOMIC = 0x40
RWF_DSYNC = 0x2 RWF_DSYNC = 0x2
RWF_HIPRI = 0x1 RWF_HIPRI = 0x1
RWF_NOAPPEND = 0x20 RWF_NOAPPEND = 0x20
RWF_NOWAIT = 0x8 RWF_NOWAIT = 0x8
RWF_SUPPORTED = 0x3f RWF_SUPPORTED = 0x7f
RWF_SYNC = 0x4 RWF_SYNC = 0x4
RWF_WRITE_LIFE_NOT_SET = 0x0 RWF_WRITE_LIFE_NOT_SET = 0x0
SCHED_BATCH = 0x3 SCHED_BATCH = 0x3
SCHED_DEADLINE = 0x6 SCHED_DEADLINE = 0x6
SCHED_EXT = 0x7
SCHED_FIFO = 0x1 SCHED_FIFO = 0x1
SCHED_FLAG_ALL = 0x7f SCHED_FLAG_ALL = 0x7f
SCHED_FLAG_DL_OVERRUN = 0x4 SCHED_FLAG_DL_OVERRUN = 0x4
@@ -3210,6 +3265,7 @@ const (
STATX_ATTR_MOUNT_ROOT = 0x2000 STATX_ATTR_MOUNT_ROOT = 0x2000
STATX_ATTR_NODUMP = 0x40 STATX_ATTR_NODUMP = 0x40
STATX_ATTR_VERITY = 0x100000 STATX_ATTR_VERITY = 0x100000
STATX_ATTR_WRITE_ATOMIC = 0x400000
STATX_BASIC_STATS = 0x7ff STATX_BASIC_STATS = 0x7ff
STATX_BLOCKS = 0x400 STATX_BLOCKS = 0x400
STATX_BTIME = 0x800 STATX_BTIME = 0x800
@@ -3226,6 +3282,7 @@ const (
STATX_SUBVOL = 0x8000 STATX_SUBVOL = 0x8000
STATX_TYPE = 0x1 STATX_TYPE = 0x1
STATX_UID = 0x8 STATX_UID = 0x8
STATX_WRITE_ATOMIC = 0x10000
STATX__RESERVED = 0x80000000 STATX__RESERVED = 0x80000000
SYNC_FILE_RANGE_WAIT_AFTER = 0x4 SYNC_FILE_RANGE_WAIT_AFTER = 0x4
SYNC_FILE_RANGE_WAIT_BEFORE = 0x1 SYNC_FILE_RANGE_WAIT_BEFORE = 0x1
@@ -3624,6 +3681,7 @@ const (
XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000 XDP_UMEM_PGOFF_COMPLETION_RING = 0x180000000
XDP_UMEM_PGOFF_FILL_RING = 0x100000000 XDP_UMEM_PGOFF_FILL_RING = 0x100000000
XDP_UMEM_REG = 0x4 XDP_UMEM_REG = 0x4
XDP_UMEM_TX_METADATA_LEN = 0x4
XDP_UMEM_TX_SW_CSUM = 0x2 XDP_UMEM_TX_SW_CSUM = 0x2
XDP_UMEM_UNALIGNED_CHUNK_FLAG = 0x1 XDP_UMEM_UNALIGNED_CHUNK_FLAG = 0x1
XDP_USE_NEED_WAKEUP = 0x8 XDP_USE_NEED_WAKEUP = 0x8

View File

@@ -109,12 +109,15 @@ const (
HIDIOCGRAWINFO = 0x80084803 HIDIOCGRAWINFO = 0x80084803
HIDIOCGRDESC = 0x90044802 HIDIOCGRDESC = 0x90044802
HIDIOCGRDESCSIZE = 0x80044801 HIDIOCGRDESCSIZE = 0x80044801
HIDIOCREVOKE = 0x4004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x8000 IEXTEN = 0x8000
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x800 IN_NONBLOCK = 0x800
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9
IPV6_FLOWINFO_MASK = 0xffffff0f
IPV6_FLOWLABEL_MASK = 0xffff0f00
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -153,9 +156,14 @@ const (
NFDBITS = 0x20 NFDBITS = 0x20
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x8008b705
NS_GET_NSTYPE = 0xb703 NS_GET_NSTYPE = 0xb703
NS_GET_OWNER_UID = 0xb704 NS_GET_OWNER_UID = 0xb704
NS_GET_PARENT = 0xb702 NS_GET_PARENT = 0xb702
NS_GET_PID_FROM_PIDNS = 0x8004b706
NS_GET_PID_IN_PIDNS = 0x8004b708
NS_GET_TGID_FROM_PIDNS = 0x8004b707
NS_GET_TGID_IN_PIDNS = 0x8004b709
NS_GET_USERNS = 0xb701 NS_GET_USERNS = 0xb701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -232,6 +240,20 @@ const (
PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCUNBRIDGECHAN = 0x7434
PPPIOCXFERUNIT = 0x744e PPPIOCXFERUNIT = 0x744e
PR_SET_PTRACER_ANY = 0xffffffff PR_SET_PTRACER_ANY = 0xffffffff
PTP_CLOCK_GETCAPS = 0x80503d01
PTP_CLOCK_GETCAPS2 = 0x80503d0a
PTP_ENABLE_PPS = 0x40043d04
PTP_ENABLE_PPS2 = 0x40043d0d
PTP_EXTTS_REQUEST = 0x40103d02
PTP_EXTTS_REQUEST2 = 0x40103d0b
PTP_MASK_CLEAR_ALL = 0x3d13
PTP_MASK_EN_SINGLE = 0x40043d14
PTP_PEROUT_REQUEST = 0x40383d03
PTP_PEROUT_REQUEST2 = 0x40383d0c
PTP_PIN_SETFUNC = 0x40603d07
PTP_PIN_SETFUNC2 = 0x40603d10
PTP_SYS_OFFSET = 0x43403d05
PTP_SYS_OFFSET2 = 0x43403d0e
PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS = 0xe
PTRACE_GETFPXREGS = 0x12 PTRACE_GETFPXREGS = 0x12
PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA = 0x19
@@ -278,10 +300,13 @@ const (
RTC_WIE_ON = 0x700f RTC_WIE_ON = 0x700f
RTC_WKALM_RD = 0x80287010 RTC_WKALM_RD = 0x80287010
RTC_WKALM_SET = 0x4028700f RTC_WKALM_SET = 0x4028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103
@@ -316,6 +341,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x27 SO_DOMAIN = 0x27
SO_DONTROUTE = 0x5 SO_DONTROUTE = 0x5
SO_ERROR = 0x4 SO_ERROR = 0x4

View File

@@ -109,12 +109,15 @@ const (
HIDIOCGRAWINFO = 0x80084803 HIDIOCGRAWINFO = 0x80084803
HIDIOCGRDESC = 0x90044802 HIDIOCGRDESC = 0x90044802
HIDIOCGRDESCSIZE = 0x80044801 HIDIOCGRDESCSIZE = 0x80044801
HIDIOCREVOKE = 0x4004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x8000 IEXTEN = 0x8000
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x800 IN_NONBLOCK = 0x800
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9
IPV6_FLOWINFO_MASK = 0xffffff0f
IPV6_FLOWLABEL_MASK = 0xffff0f00
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -153,9 +156,14 @@ const (
NFDBITS = 0x40 NFDBITS = 0x40
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x8008b705
NS_GET_NSTYPE = 0xb703 NS_GET_NSTYPE = 0xb703
NS_GET_OWNER_UID = 0xb704 NS_GET_OWNER_UID = 0xb704
NS_GET_PARENT = 0xb702 NS_GET_PARENT = 0xb702
NS_GET_PID_FROM_PIDNS = 0x8004b706
NS_GET_PID_IN_PIDNS = 0x8004b708
NS_GET_TGID_FROM_PIDNS = 0x8004b707
NS_GET_TGID_IN_PIDNS = 0x8004b709
NS_GET_USERNS = 0xb701 NS_GET_USERNS = 0xb701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -232,6 +240,20 @@ const (
PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCUNBRIDGECHAN = 0x7434
PPPIOCXFERUNIT = 0x744e PPPIOCXFERUNIT = 0x744e
PR_SET_PTRACER_ANY = 0xffffffffffffffff PR_SET_PTRACER_ANY = 0xffffffffffffffff
PTP_CLOCK_GETCAPS = 0x80503d01
PTP_CLOCK_GETCAPS2 = 0x80503d0a
PTP_ENABLE_PPS = 0x40043d04
PTP_ENABLE_PPS2 = 0x40043d0d
PTP_EXTTS_REQUEST = 0x40103d02
PTP_EXTTS_REQUEST2 = 0x40103d0b
PTP_MASK_CLEAR_ALL = 0x3d13
PTP_MASK_EN_SINGLE = 0x40043d14
PTP_PEROUT_REQUEST = 0x40383d03
PTP_PEROUT_REQUEST2 = 0x40383d0c
PTP_PIN_SETFUNC = 0x40603d07
PTP_PIN_SETFUNC2 = 0x40603d10
PTP_SYS_OFFSET = 0x43403d05
PTP_SYS_OFFSET2 = 0x43403d0e
PTRACE_ARCH_PRCTL = 0x1e PTRACE_ARCH_PRCTL = 0x1e
PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS = 0xe
PTRACE_GETFPXREGS = 0x12 PTRACE_GETFPXREGS = 0x12
@@ -279,10 +301,13 @@ const (
RTC_WIE_ON = 0x700f RTC_WIE_ON = 0x700f
RTC_WKALM_RD = 0x80287010 RTC_WKALM_RD = 0x80287010
RTC_WKALM_SET = 0x4028700f RTC_WKALM_SET = 0x4028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103
@@ -317,6 +342,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x27 SO_DOMAIN = 0x27
SO_DONTROUTE = 0x5 SO_DONTROUTE = 0x5
SO_ERROR = 0x4 SO_ERROR = 0x4

View File

@@ -108,12 +108,15 @@ const (
HIDIOCGRAWINFO = 0x80084803 HIDIOCGRAWINFO = 0x80084803
HIDIOCGRDESC = 0x90044802 HIDIOCGRDESC = 0x90044802
HIDIOCGRDESCSIZE = 0x80044801 HIDIOCGRDESCSIZE = 0x80044801
HIDIOCREVOKE = 0x4004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x8000 IEXTEN = 0x8000
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x800 IN_NONBLOCK = 0x800
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9
IPV6_FLOWINFO_MASK = 0xffffff0f
IPV6_FLOWLABEL_MASK = 0xffff0f00
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -150,9 +153,14 @@ const (
NFDBITS = 0x20 NFDBITS = 0x20
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x8008b705
NS_GET_NSTYPE = 0xb703 NS_GET_NSTYPE = 0xb703
NS_GET_OWNER_UID = 0xb704 NS_GET_OWNER_UID = 0xb704
NS_GET_PARENT = 0xb702 NS_GET_PARENT = 0xb702
NS_GET_PID_FROM_PIDNS = 0x8004b706
NS_GET_PID_IN_PIDNS = 0x8004b708
NS_GET_TGID_FROM_PIDNS = 0x8004b707
NS_GET_TGID_IN_PIDNS = 0x8004b709
NS_GET_USERNS = 0xb701 NS_GET_USERNS = 0xb701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -229,6 +237,20 @@ const (
PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCUNBRIDGECHAN = 0x7434
PPPIOCXFERUNIT = 0x744e PPPIOCXFERUNIT = 0x744e
PR_SET_PTRACER_ANY = 0xffffffff PR_SET_PTRACER_ANY = 0xffffffff
PTP_CLOCK_GETCAPS = 0x80503d01
PTP_CLOCK_GETCAPS2 = 0x80503d0a
PTP_ENABLE_PPS = 0x40043d04
PTP_ENABLE_PPS2 = 0x40043d0d
PTP_EXTTS_REQUEST = 0x40103d02
PTP_EXTTS_REQUEST2 = 0x40103d0b
PTP_MASK_CLEAR_ALL = 0x3d13
PTP_MASK_EN_SINGLE = 0x40043d14
PTP_PEROUT_REQUEST = 0x40383d03
PTP_PEROUT_REQUEST2 = 0x40383d0c
PTP_PIN_SETFUNC = 0x40603d07
PTP_PIN_SETFUNC2 = 0x40603d10
PTP_SYS_OFFSET = 0x43403d05
PTP_SYS_OFFSET2 = 0x43403d0e
PTRACE_GETCRUNCHREGS = 0x19 PTRACE_GETCRUNCHREGS = 0x19
PTRACE_GETFDPIC = 0x1f PTRACE_GETFDPIC = 0x1f
PTRACE_GETFDPIC_EXEC = 0x0 PTRACE_GETFDPIC_EXEC = 0x0
@@ -284,10 +306,13 @@ const (
RTC_WIE_ON = 0x700f RTC_WIE_ON = 0x700f
RTC_WKALM_RD = 0x80287010 RTC_WKALM_RD = 0x80287010
RTC_WKALM_SET = 0x4028700f RTC_WKALM_SET = 0x4028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103
@@ -322,6 +347,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x27 SO_DOMAIN = 0x27
SO_DONTROUTE = 0x5 SO_DONTROUTE = 0x5
SO_ERROR = 0x4 SO_ERROR = 0x4

View File

@@ -109,15 +109,19 @@ const (
F_SETOWN = 0x8 F_SETOWN = 0x8
F_UNLCK = 0x2 F_UNLCK = 0x2
F_WRLCK = 0x1 F_WRLCK = 0x1
GCS_MAGIC = 0x47435300
HIDIOCGRAWINFO = 0x80084803 HIDIOCGRAWINFO = 0x80084803
HIDIOCGRDESC = 0x90044802 HIDIOCGRDESC = 0x90044802
HIDIOCGRDESCSIZE = 0x80044801 HIDIOCGRDESCSIZE = 0x80044801
HIDIOCREVOKE = 0x4004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x8000 IEXTEN = 0x8000
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x800 IN_NONBLOCK = 0x800
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9
IPV6_FLOWINFO_MASK = 0xffffff0f
IPV6_FLOWLABEL_MASK = 0xffff0f00
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -154,9 +158,14 @@ const (
NFDBITS = 0x40 NFDBITS = 0x40
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x8008b705
NS_GET_NSTYPE = 0xb703 NS_GET_NSTYPE = 0xb703
NS_GET_OWNER_UID = 0xb704 NS_GET_OWNER_UID = 0xb704
NS_GET_PARENT = 0xb702 NS_GET_PARENT = 0xb702
NS_GET_PID_FROM_PIDNS = 0x8004b706
NS_GET_PID_IN_PIDNS = 0x8004b708
NS_GET_TGID_FROM_PIDNS = 0x8004b707
NS_GET_TGID_IN_PIDNS = 0x8004b709
NS_GET_USERNS = 0xb701 NS_GET_USERNS = 0xb701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -200,6 +209,7 @@ const (
PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_BPF = 0x40042408
PERF_EVENT_IOC_SET_FILTER = 0x40082406 PERF_EVENT_IOC_SET_FILTER = 0x40082406
PERF_EVENT_IOC_SET_OUTPUT = 0x2405 PERF_EVENT_IOC_SET_OUTPUT = 0x2405
POE_MAGIC = 0x504f4530
PPPIOCATTACH = 0x4004743d PPPIOCATTACH = 0x4004743d
PPPIOCATTCHAN = 0x40047438 PPPIOCATTCHAN = 0x40047438
PPPIOCBRIDGECHAN = 0x40047435 PPPIOCBRIDGECHAN = 0x40047435
@@ -235,6 +245,20 @@ const (
PROT_BTI = 0x10 PROT_BTI = 0x10
PROT_MTE = 0x20 PROT_MTE = 0x20
PR_SET_PTRACER_ANY = 0xffffffffffffffff PR_SET_PTRACER_ANY = 0xffffffffffffffff
PTP_CLOCK_GETCAPS = 0x80503d01
PTP_CLOCK_GETCAPS2 = 0x80503d0a
PTP_ENABLE_PPS = 0x40043d04
PTP_ENABLE_PPS2 = 0x40043d0d
PTP_EXTTS_REQUEST = 0x40103d02
PTP_EXTTS_REQUEST2 = 0x40103d0b
PTP_MASK_CLEAR_ALL = 0x3d13
PTP_MASK_EN_SINGLE = 0x40043d14
PTP_PEROUT_REQUEST = 0x40383d03
PTP_PEROUT_REQUEST2 = 0x40383d0c
PTP_PIN_SETFUNC = 0x40603d07
PTP_PIN_SETFUNC2 = 0x40603d10
PTP_SYS_OFFSET = 0x43403d05
PTP_SYS_OFFSET2 = 0x43403d0e
PTRACE_PEEKMTETAGS = 0x21 PTRACE_PEEKMTETAGS = 0x21
PTRACE_POKEMTETAGS = 0x22 PTRACE_POKEMTETAGS = 0x22
PTRACE_SYSEMU = 0x1f PTRACE_SYSEMU = 0x1f
@@ -275,10 +299,13 @@ const (
RTC_WIE_ON = 0x700f RTC_WIE_ON = 0x700f
RTC_WKALM_RD = 0x80287010 RTC_WKALM_RD = 0x80287010
RTC_WKALM_SET = 0x4028700f RTC_WKALM_SET = 0x4028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103
@@ -313,6 +340,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x27 SO_DOMAIN = 0x27
SO_DONTROUTE = 0x5 SO_DONTROUTE = 0x5
SO_ERROR = 0x4 SO_ERROR = 0x4

View File

@@ -109,12 +109,15 @@ const (
HIDIOCGRAWINFO = 0x80084803 HIDIOCGRAWINFO = 0x80084803
HIDIOCGRDESC = 0x90044802 HIDIOCGRDESC = 0x90044802
HIDIOCGRDESCSIZE = 0x80044801 HIDIOCGRDESCSIZE = 0x80044801
HIDIOCREVOKE = 0x4004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x8000 IEXTEN = 0x8000
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x800 IN_NONBLOCK = 0x800
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9
IPV6_FLOWINFO_MASK = 0xffffff0f
IPV6_FLOWLABEL_MASK = 0xffff0f00
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -154,9 +157,14 @@ const (
NFDBITS = 0x40 NFDBITS = 0x40
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x8008b705
NS_GET_NSTYPE = 0xb703 NS_GET_NSTYPE = 0xb703
NS_GET_OWNER_UID = 0xb704 NS_GET_OWNER_UID = 0xb704
NS_GET_PARENT = 0xb702 NS_GET_PARENT = 0xb702
NS_GET_PID_FROM_PIDNS = 0x8004b706
NS_GET_PID_IN_PIDNS = 0x8004b708
NS_GET_TGID_FROM_PIDNS = 0x8004b707
NS_GET_TGID_IN_PIDNS = 0x8004b709
NS_GET_USERNS = 0xb701 NS_GET_USERNS = 0xb701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -233,6 +241,20 @@ const (
PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCUNBRIDGECHAN = 0x7434
PPPIOCXFERUNIT = 0x744e PPPIOCXFERUNIT = 0x744e
PR_SET_PTRACER_ANY = 0xffffffffffffffff PR_SET_PTRACER_ANY = 0xffffffffffffffff
PTP_CLOCK_GETCAPS = 0x80503d01
PTP_CLOCK_GETCAPS2 = 0x80503d0a
PTP_ENABLE_PPS = 0x40043d04
PTP_ENABLE_PPS2 = 0x40043d0d
PTP_EXTTS_REQUEST = 0x40103d02
PTP_EXTTS_REQUEST2 = 0x40103d0b
PTP_MASK_CLEAR_ALL = 0x3d13
PTP_MASK_EN_SINGLE = 0x40043d14
PTP_PEROUT_REQUEST = 0x40383d03
PTP_PEROUT_REQUEST2 = 0x40383d0c
PTP_PIN_SETFUNC = 0x40603d07
PTP_PIN_SETFUNC2 = 0x40603d10
PTP_SYS_OFFSET = 0x43403d05
PTP_SYS_OFFSET2 = 0x43403d0e
PTRACE_SYSEMU = 0x1f PTRACE_SYSEMU = 0x1f
PTRACE_SYSEMU_SINGLESTEP = 0x20 PTRACE_SYSEMU_SINGLESTEP = 0x20
RLIMIT_AS = 0x9 RLIMIT_AS = 0x9
@@ -271,10 +293,13 @@ const (
RTC_WIE_ON = 0x700f RTC_WIE_ON = 0x700f
RTC_WKALM_RD = 0x80287010 RTC_WKALM_RD = 0x80287010
RTC_WKALM_SET = 0x4028700f RTC_WKALM_SET = 0x4028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103
@@ -309,6 +334,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x27 SO_DOMAIN = 0x27
SO_DONTROUTE = 0x5 SO_DONTROUTE = 0x5
SO_ERROR = 0x4 SO_ERROR = 0x4

View File

@@ -108,12 +108,15 @@ const (
HIDIOCGRAWINFO = 0x40084803 HIDIOCGRAWINFO = 0x40084803
HIDIOCGRDESC = 0x50044802 HIDIOCGRDESC = 0x50044802
HIDIOCGRDESCSIZE = 0x40044801 HIDIOCGRDESCSIZE = 0x40044801
HIDIOCREVOKE = 0x8004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x100 IEXTEN = 0x100
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x80 IN_NONBLOCK = 0x80
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9
IPV6_FLOWINFO_MASK = 0xfffffff
IPV6_FLOWLABEL_MASK = 0xfffff
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -150,9 +153,14 @@ const (
NFDBITS = 0x20 NFDBITS = 0x20
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x4008b705
NS_GET_NSTYPE = 0x2000b703 NS_GET_NSTYPE = 0x2000b703
NS_GET_OWNER_UID = 0x2000b704 NS_GET_OWNER_UID = 0x2000b704
NS_GET_PARENT = 0x2000b702 NS_GET_PARENT = 0x2000b702
NS_GET_PID_FROM_PIDNS = 0x4004b706
NS_GET_PID_IN_PIDNS = 0x4004b708
NS_GET_TGID_FROM_PIDNS = 0x4004b707
NS_GET_TGID_IN_PIDNS = 0x4004b709
NS_GET_USERNS = 0x2000b701 NS_GET_USERNS = 0x2000b701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -229,6 +237,20 @@ const (
PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCUNBRIDGECHAN = 0x20007434
PPPIOCXFERUNIT = 0x2000744e PPPIOCXFERUNIT = 0x2000744e
PR_SET_PTRACER_ANY = 0xffffffff PR_SET_PTRACER_ANY = 0xffffffff
PTP_CLOCK_GETCAPS = 0x40503d01
PTP_CLOCK_GETCAPS2 = 0x40503d0a
PTP_ENABLE_PPS = 0x80043d04
PTP_ENABLE_PPS2 = 0x80043d0d
PTP_EXTTS_REQUEST = 0x80103d02
PTP_EXTTS_REQUEST2 = 0x80103d0b
PTP_MASK_CLEAR_ALL = 0x20003d13
PTP_MASK_EN_SINGLE = 0x80043d14
PTP_PEROUT_REQUEST = 0x80383d03
PTP_PEROUT_REQUEST2 = 0x80383d0c
PTP_PIN_SETFUNC = 0x80603d07
PTP_PIN_SETFUNC2 = 0x80603d10
PTP_SYS_OFFSET = 0x83403d05
PTP_SYS_OFFSET2 = 0x83403d0e
PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS = 0xe
PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA = 0x19
PTRACE_GET_THREAD_AREA_3264 = 0xc4 PTRACE_GET_THREAD_AREA_3264 = 0xc4
@@ -277,10 +299,13 @@ const (
RTC_WIE_ON = 0x2000700f RTC_WIE_ON = 0x2000700f
RTC_WKALM_RD = 0x40287010 RTC_WKALM_RD = 0x40287010
RTC_WKALM_SET = 0x8028700f RTC_WKALM_SET = 0x8028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103
@@ -315,6 +340,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x1029 SO_DOMAIN = 0x1029
SO_DONTROUTE = 0x10 SO_DONTROUTE = 0x10
SO_ERROR = 0x1007 SO_ERROR = 0x1007

View File

@@ -108,12 +108,15 @@ const (
HIDIOCGRAWINFO = 0x40084803 HIDIOCGRAWINFO = 0x40084803
HIDIOCGRDESC = 0x50044802 HIDIOCGRDESC = 0x50044802
HIDIOCGRDESCSIZE = 0x40044801 HIDIOCGRDESCSIZE = 0x40044801
HIDIOCREVOKE = 0x8004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x100 IEXTEN = 0x100
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x80 IN_NONBLOCK = 0x80
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9
IPV6_FLOWINFO_MASK = 0xfffffff
IPV6_FLOWLABEL_MASK = 0xfffff
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -150,9 +153,14 @@ const (
NFDBITS = 0x40 NFDBITS = 0x40
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x4008b705
NS_GET_NSTYPE = 0x2000b703 NS_GET_NSTYPE = 0x2000b703
NS_GET_OWNER_UID = 0x2000b704 NS_GET_OWNER_UID = 0x2000b704
NS_GET_PARENT = 0x2000b702 NS_GET_PARENT = 0x2000b702
NS_GET_PID_FROM_PIDNS = 0x4004b706
NS_GET_PID_IN_PIDNS = 0x4004b708
NS_GET_TGID_FROM_PIDNS = 0x4004b707
NS_GET_TGID_IN_PIDNS = 0x4004b709
NS_GET_USERNS = 0x2000b701 NS_GET_USERNS = 0x2000b701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -229,6 +237,20 @@ const (
PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCUNBRIDGECHAN = 0x20007434
PPPIOCXFERUNIT = 0x2000744e PPPIOCXFERUNIT = 0x2000744e
PR_SET_PTRACER_ANY = 0xffffffffffffffff PR_SET_PTRACER_ANY = 0xffffffffffffffff
PTP_CLOCK_GETCAPS = 0x40503d01
PTP_CLOCK_GETCAPS2 = 0x40503d0a
PTP_ENABLE_PPS = 0x80043d04
PTP_ENABLE_PPS2 = 0x80043d0d
PTP_EXTTS_REQUEST = 0x80103d02
PTP_EXTTS_REQUEST2 = 0x80103d0b
PTP_MASK_CLEAR_ALL = 0x20003d13
PTP_MASK_EN_SINGLE = 0x80043d14
PTP_PEROUT_REQUEST = 0x80383d03
PTP_PEROUT_REQUEST2 = 0x80383d0c
PTP_PIN_SETFUNC = 0x80603d07
PTP_PIN_SETFUNC2 = 0x80603d10
PTP_SYS_OFFSET = 0x83403d05
PTP_SYS_OFFSET2 = 0x83403d0e
PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS = 0xe
PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA = 0x19
PTRACE_GET_THREAD_AREA_3264 = 0xc4 PTRACE_GET_THREAD_AREA_3264 = 0xc4
@@ -277,10 +299,13 @@ const (
RTC_WIE_ON = 0x2000700f RTC_WIE_ON = 0x2000700f
RTC_WKALM_RD = 0x40287010 RTC_WKALM_RD = 0x40287010
RTC_WKALM_SET = 0x8028700f RTC_WKALM_SET = 0x8028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103
@@ -315,6 +340,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x1029 SO_DOMAIN = 0x1029
SO_DONTROUTE = 0x10 SO_DONTROUTE = 0x10
SO_ERROR = 0x1007 SO_ERROR = 0x1007

View File

@@ -108,12 +108,15 @@ const (
HIDIOCGRAWINFO = 0x40084803 HIDIOCGRAWINFO = 0x40084803
HIDIOCGRDESC = 0x50044802 HIDIOCGRDESC = 0x50044802
HIDIOCGRDESCSIZE = 0x40044801 HIDIOCGRDESCSIZE = 0x40044801
HIDIOCREVOKE = 0x8004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x100 IEXTEN = 0x100
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x80 IN_NONBLOCK = 0x80
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9
IPV6_FLOWINFO_MASK = 0xffffff0f
IPV6_FLOWLABEL_MASK = 0xffff0f00
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -150,9 +153,14 @@ const (
NFDBITS = 0x40 NFDBITS = 0x40
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x4008b705
NS_GET_NSTYPE = 0x2000b703 NS_GET_NSTYPE = 0x2000b703
NS_GET_OWNER_UID = 0x2000b704 NS_GET_OWNER_UID = 0x2000b704
NS_GET_PARENT = 0x2000b702 NS_GET_PARENT = 0x2000b702
NS_GET_PID_FROM_PIDNS = 0x4004b706
NS_GET_PID_IN_PIDNS = 0x4004b708
NS_GET_TGID_FROM_PIDNS = 0x4004b707
NS_GET_TGID_IN_PIDNS = 0x4004b709
NS_GET_USERNS = 0x2000b701 NS_GET_USERNS = 0x2000b701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -229,6 +237,20 @@ const (
PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCUNBRIDGECHAN = 0x20007434
PPPIOCXFERUNIT = 0x2000744e PPPIOCXFERUNIT = 0x2000744e
PR_SET_PTRACER_ANY = 0xffffffffffffffff PR_SET_PTRACER_ANY = 0xffffffffffffffff
PTP_CLOCK_GETCAPS = 0x40503d01
PTP_CLOCK_GETCAPS2 = 0x40503d0a
PTP_ENABLE_PPS = 0x80043d04
PTP_ENABLE_PPS2 = 0x80043d0d
PTP_EXTTS_REQUEST = 0x80103d02
PTP_EXTTS_REQUEST2 = 0x80103d0b
PTP_MASK_CLEAR_ALL = 0x20003d13
PTP_MASK_EN_SINGLE = 0x80043d14
PTP_PEROUT_REQUEST = 0x80383d03
PTP_PEROUT_REQUEST2 = 0x80383d0c
PTP_PIN_SETFUNC = 0x80603d07
PTP_PIN_SETFUNC2 = 0x80603d10
PTP_SYS_OFFSET = 0x83403d05
PTP_SYS_OFFSET2 = 0x83403d0e
PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS = 0xe
PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA = 0x19
PTRACE_GET_THREAD_AREA_3264 = 0xc4 PTRACE_GET_THREAD_AREA_3264 = 0xc4
@@ -277,10 +299,13 @@ const (
RTC_WIE_ON = 0x2000700f RTC_WIE_ON = 0x2000700f
RTC_WKALM_RD = 0x40287010 RTC_WKALM_RD = 0x40287010
RTC_WKALM_SET = 0x8028700f RTC_WKALM_SET = 0x8028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103
@@ -315,6 +340,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x1029 SO_DOMAIN = 0x1029
SO_DONTROUTE = 0x10 SO_DONTROUTE = 0x10
SO_ERROR = 0x1007 SO_ERROR = 0x1007

View File

@@ -108,12 +108,15 @@ const (
HIDIOCGRAWINFO = 0x40084803 HIDIOCGRAWINFO = 0x40084803
HIDIOCGRDESC = 0x50044802 HIDIOCGRDESC = 0x50044802
HIDIOCGRDESCSIZE = 0x40044801 HIDIOCGRDESCSIZE = 0x40044801
HIDIOCREVOKE = 0x8004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x100 IEXTEN = 0x100
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x80 IN_NONBLOCK = 0x80
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9
IPV6_FLOWINFO_MASK = 0xffffff0f
IPV6_FLOWLABEL_MASK = 0xffff0f00
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -150,9 +153,14 @@ const (
NFDBITS = 0x20 NFDBITS = 0x20
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x4008b705
NS_GET_NSTYPE = 0x2000b703 NS_GET_NSTYPE = 0x2000b703
NS_GET_OWNER_UID = 0x2000b704 NS_GET_OWNER_UID = 0x2000b704
NS_GET_PARENT = 0x2000b702 NS_GET_PARENT = 0x2000b702
NS_GET_PID_FROM_PIDNS = 0x4004b706
NS_GET_PID_IN_PIDNS = 0x4004b708
NS_GET_TGID_FROM_PIDNS = 0x4004b707
NS_GET_TGID_IN_PIDNS = 0x4004b709
NS_GET_USERNS = 0x2000b701 NS_GET_USERNS = 0x2000b701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -229,6 +237,20 @@ const (
PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCUNBRIDGECHAN = 0x20007434
PPPIOCXFERUNIT = 0x2000744e PPPIOCXFERUNIT = 0x2000744e
PR_SET_PTRACER_ANY = 0xffffffff PR_SET_PTRACER_ANY = 0xffffffff
PTP_CLOCK_GETCAPS = 0x40503d01
PTP_CLOCK_GETCAPS2 = 0x40503d0a
PTP_ENABLE_PPS = 0x80043d04
PTP_ENABLE_PPS2 = 0x80043d0d
PTP_EXTTS_REQUEST = 0x80103d02
PTP_EXTTS_REQUEST2 = 0x80103d0b
PTP_MASK_CLEAR_ALL = 0x20003d13
PTP_MASK_EN_SINGLE = 0x80043d14
PTP_PEROUT_REQUEST = 0x80383d03
PTP_PEROUT_REQUEST2 = 0x80383d0c
PTP_PIN_SETFUNC = 0x80603d07
PTP_PIN_SETFUNC2 = 0x80603d10
PTP_SYS_OFFSET = 0x83403d05
PTP_SYS_OFFSET2 = 0x83403d0e
PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS = 0xe
PTRACE_GET_THREAD_AREA = 0x19 PTRACE_GET_THREAD_AREA = 0x19
PTRACE_GET_THREAD_AREA_3264 = 0xc4 PTRACE_GET_THREAD_AREA_3264 = 0xc4
@@ -277,10 +299,13 @@ const (
RTC_WIE_ON = 0x2000700f RTC_WIE_ON = 0x2000700f
RTC_WKALM_RD = 0x40287010 RTC_WKALM_RD = 0x40287010
RTC_WKALM_SET = 0x8028700f RTC_WKALM_SET = 0x8028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103
@@ -315,6 +340,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x1029 SO_DOMAIN = 0x1029
SO_DONTROUTE = 0x10 SO_DONTROUTE = 0x10
SO_ERROR = 0x1007 SO_ERROR = 0x1007

View File

@@ -108,12 +108,15 @@ const (
HIDIOCGRAWINFO = 0x40084803 HIDIOCGRAWINFO = 0x40084803
HIDIOCGRDESC = 0x50044802 HIDIOCGRDESC = 0x50044802
HIDIOCGRDESCSIZE = 0x40044801 HIDIOCGRDESCSIZE = 0x40044801
HIDIOCREVOKE = 0x8004480d
HUPCL = 0x4000 HUPCL = 0x4000
ICANON = 0x100 ICANON = 0x100
IEXTEN = 0x400 IEXTEN = 0x400
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x800 IN_NONBLOCK = 0x800
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9
IPV6_FLOWINFO_MASK = 0xfffffff
IPV6_FLOWLABEL_MASK = 0xfffff
ISIG = 0x80 ISIG = 0x80
IUCLC = 0x1000 IUCLC = 0x1000
IXOFF = 0x400 IXOFF = 0x400
@@ -152,9 +155,14 @@ const (
NL3 = 0x300 NL3 = 0x300
NLDLY = 0x300 NLDLY = 0x300
NOFLSH = 0x80000000 NOFLSH = 0x80000000
NS_GET_MNTNS_ID = 0x4008b705
NS_GET_NSTYPE = 0x2000b703 NS_GET_NSTYPE = 0x2000b703
NS_GET_OWNER_UID = 0x2000b704 NS_GET_OWNER_UID = 0x2000b704
NS_GET_PARENT = 0x2000b702 NS_GET_PARENT = 0x2000b702
NS_GET_PID_FROM_PIDNS = 0x4004b706
NS_GET_PID_IN_PIDNS = 0x4004b708
NS_GET_TGID_FROM_PIDNS = 0x4004b707
NS_GET_TGID_IN_PIDNS = 0x4004b709
NS_GET_USERNS = 0x2000b701 NS_GET_USERNS = 0x2000b701
OLCUC = 0x4 OLCUC = 0x4
ONLCR = 0x2 ONLCR = 0x2
@@ -232,6 +240,20 @@ const (
PPPIOCXFERUNIT = 0x2000744e PPPIOCXFERUNIT = 0x2000744e
PROT_SAO = 0x10 PROT_SAO = 0x10
PR_SET_PTRACER_ANY = 0xffffffff PR_SET_PTRACER_ANY = 0xffffffff
PTP_CLOCK_GETCAPS = 0x40503d01
PTP_CLOCK_GETCAPS2 = 0x40503d0a
PTP_ENABLE_PPS = 0x80043d04
PTP_ENABLE_PPS2 = 0x80043d0d
PTP_EXTTS_REQUEST = 0x80103d02
PTP_EXTTS_REQUEST2 = 0x80103d0b
PTP_MASK_CLEAR_ALL = 0x20003d13
PTP_MASK_EN_SINGLE = 0x80043d14
PTP_PEROUT_REQUEST = 0x80383d03
PTP_PEROUT_REQUEST2 = 0x80383d0c
PTP_PIN_SETFUNC = 0x80603d07
PTP_PIN_SETFUNC2 = 0x80603d10
PTP_SYS_OFFSET = 0x83403d05
PTP_SYS_OFFSET2 = 0x83403d0e
PTRACE_GETEVRREGS = 0x14 PTRACE_GETEVRREGS = 0x14
PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS = 0xe
PTRACE_GETREGS64 = 0x16 PTRACE_GETREGS64 = 0x16
@@ -332,10 +354,13 @@ const (
RTC_WIE_ON = 0x2000700f RTC_WIE_ON = 0x2000700f
RTC_WKALM_RD = 0x40287010 RTC_WKALM_RD = 0x40287010
RTC_WKALM_SET = 0x8028700f RTC_WKALM_SET = 0x8028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103
@@ -370,6 +395,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x27 SO_DOMAIN = 0x27
SO_DONTROUTE = 0x5 SO_DONTROUTE = 0x5
SO_ERROR = 0x4 SO_ERROR = 0x4

View File

@@ -108,12 +108,15 @@ const (
HIDIOCGRAWINFO = 0x40084803 HIDIOCGRAWINFO = 0x40084803
HIDIOCGRDESC = 0x50044802 HIDIOCGRDESC = 0x50044802
HIDIOCGRDESCSIZE = 0x40044801 HIDIOCGRDESCSIZE = 0x40044801
HIDIOCREVOKE = 0x8004480d
HUPCL = 0x4000 HUPCL = 0x4000
ICANON = 0x100 ICANON = 0x100
IEXTEN = 0x400 IEXTEN = 0x400
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x800 IN_NONBLOCK = 0x800
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9
IPV6_FLOWINFO_MASK = 0xfffffff
IPV6_FLOWLABEL_MASK = 0xfffff
ISIG = 0x80 ISIG = 0x80
IUCLC = 0x1000 IUCLC = 0x1000
IXOFF = 0x400 IXOFF = 0x400
@@ -152,9 +155,14 @@ const (
NL3 = 0x300 NL3 = 0x300
NLDLY = 0x300 NLDLY = 0x300
NOFLSH = 0x80000000 NOFLSH = 0x80000000
NS_GET_MNTNS_ID = 0x4008b705
NS_GET_NSTYPE = 0x2000b703 NS_GET_NSTYPE = 0x2000b703
NS_GET_OWNER_UID = 0x2000b704 NS_GET_OWNER_UID = 0x2000b704
NS_GET_PARENT = 0x2000b702 NS_GET_PARENT = 0x2000b702
NS_GET_PID_FROM_PIDNS = 0x4004b706
NS_GET_PID_IN_PIDNS = 0x4004b708
NS_GET_TGID_FROM_PIDNS = 0x4004b707
NS_GET_TGID_IN_PIDNS = 0x4004b709
NS_GET_USERNS = 0x2000b701 NS_GET_USERNS = 0x2000b701
OLCUC = 0x4 OLCUC = 0x4
ONLCR = 0x2 ONLCR = 0x2
@@ -232,6 +240,20 @@ const (
PPPIOCXFERUNIT = 0x2000744e PPPIOCXFERUNIT = 0x2000744e
PROT_SAO = 0x10 PROT_SAO = 0x10
PR_SET_PTRACER_ANY = 0xffffffffffffffff PR_SET_PTRACER_ANY = 0xffffffffffffffff
PTP_CLOCK_GETCAPS = 0x40503d01
PTP_CLOCK_GETCAPS2 = 0x40503d0a
PTP_ENABLE_PPS = 0x80043d04
PTP_ENABLE_PPS2 = 0x80043d0d
PTP_EXTTS_REQUEST = 0x80103d02
PTP_EXTTS_REQUEST2 = 0x80103d0b
PTP_MASK_CLEAR_ALL = 0x20003d13
PTP_MASK_EN_SINGLE = 0x80043d14
PTP_PEROUT_REQUEST = 0x80383d03
PTP_PEROUT_REQUEST2 = 0x80383d0c
PTP_PIN_SETFUNC = 0x80603d07
PTP_PIN_SETFUNC2 = 0x80603d10
PTP_SYS_OFFSET = 0x83403d05
PTP_SYS_OFFSET2 = 0x83403d0e
PTRACE_GETEVRREGS = 0x14 PTRACE_GETEVRREGS = 0x14
PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS = 0xe
PTRACE_GETREGS64 = 0x16 PTRACE_GETREGS64 = 0x16
@@ -336,10 +358,13 @@ const (
RTC_WIE_ON = 0x2000700f RTC_WIE_ON = 0x2000700f
RTC_WKALM_RD = 0x40287010 RTC_WKALM_RD = 0x40287010
RTC_WKALM_SET = 0x8028700f RTC_WKALM_SET = 0x8028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103
@@ -374,6 +399,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x27 SO_DOMAIN = 0x27
SO_DONTROUTE = 0x5 SO_DONTROUTE = 0x5
SO_ERROR = 0x4 SO_ERROR = 0x4

View File

@@ -108,12 +108,15 @@ const (
HIDIOCGRAWINFO = 0x40084803 HIDIOCGRAWINFO = 0x40084803
HIDIOCGRDESC = 0x50044802 HIDIOCGRDESC = 0x50044802
HIDIOCGRDESCSIZE = 0x40044801 HIDIOCGRDESCSIZE = 0x40044801
HIDIOCREVOKE = 0x8004480d
HUPCL = 0x4000 HUPCL = 0x4000
ICANON = 0x100 ICANON = 0x100
IEXTEN = 0x400 IEXTEN = 0x400
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x800 IN_NONBLOCK = 0x800
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9
IPV6_FLOWINFO_MASK = 0xffffff0f
IPV6_FLOWLABEL_MASK = 0xffff0f00
ISIG = 0x80 ISIG = 0x80
IUCLC = 0x1000 IUCLC = 0x1000
IXOFF = 0x400 IXOFF = 0x400
@@ -152,9 +155,14 @@ const (
NL3 = 0x300 NL3 = 0x300
NLDLY = 0x300 NLDLY = 0x300
NOFLSH = 0x80000000 NOFLSH = 0x80000000
NS_GET_MNTNS_ID = 0x4008b705
NS_GET_NSTYPE = 0x2000b703 NS_GET_NSTYPE = 0x2000b703
NS_GET_OWNER_UID = 0x2000b704 NS_GET_OWNER_UID = 0x2000b704
NS_GET_PARENT = 0x2000b702 NS_GET_PARENT = 0x2000b702
NS_GET_PID_FROM_PIDNS = 0x4004b706
NS_GET_PID_IN_PIDNS = 0x4004b708
NS_GET_TGID_FROM_PIDNS = 0x4004b707
NS_GET_TGID_IN_PIDNS = 0x4004b709
NS_GET_USERNS = 0x2000b701 NS_GET_USERNS = 0x2000b701
OLCUC = 0x4 OLCUC = 0x4
ONLCR = 0x2 ONLCR = 0x2
@@ -232,6 +240,20 @@ const (
PPPIOCXFERUNIT = 0x2000744e PPPIOCXFERUNIT = 0x2000744e
PROT_SAO = 0x10 PROT_SAO = 0x10
PR_SET_PTRACER_ANY = 0xffffffffffffffff PR_SET_PTRACER_ANY = 0xffffffffffffffff
PTP_CLOCK_GETCAPS = 0x40503d01
PTP_CLOCK_GETCAPS2 = 0x40503d0a
PTP_ENABLE_PPS = 0x80043d04
PTP_ENABLE_PPS2 = 0x80043d0d
PTP_EXTTS_REQUEST = 0x80103d02
PTP_EXTTS_REQUEST2 = 0x80103d0b
PTP_MASK_CLEAR_ALL = 0x20003d13
PTP_MASK_EN_SINGLE = 0x80043d14
PTP_PEROUT_REQUEST = 0x80383d03
PTP_PEROUT_REQUEST2 = 0x80383d0c
PTP_PIN_SETFUNC = 0x80603d07
PTP_PIN_SETFUNC2 = 0x80603d10
PTP_SYS_OFFSET = 0x83403d05
PTP_SYS_OFFSET2 = 0x83403d0e
PTRACE_GETEVRREGS = 0x14 PTRACE_GETEVRREGS = 0x14
PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS = 0xe
PTRACE_GETREGS64 = 0x16 PTRACE_GETREGS64 = 0x16
@@ -336,10 +358,13 @@ const (
RTC_WIE_ON = 0x2000700f RTC_WIE_ON = 0x2000700f
RTC_WKALM_RD = 0x40287010 RTC_WKALM_RD = 0x40287010
RTC_WKALM_SET = 0x8028700f RTC_WKALM_SET = 0x8028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103
@@ -374,6 +399,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x27 SO_DOMAIN = 0x27
SO_DONTROUTE = 0x5 SO_DONTROUTE = 0x5
SO_ERROR = 0x4 SO_ERROR = 0x4

View File

@@ -108,12 +108,15 @@ const (
HIDIOCGRAWINFO = 0x80084803 HIDIOCGRAWINFO = 0x80084803
HIDIOCGRDESC = 0x90044802 HIDIOCGRDESC = 0x90044802
HIDIOCGRDESCSIZE = 0x80044801 HIDIOCGRDESCSIZE = 0x80044801
HIDIOCREVOKE = 0x4004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x8000 IEXTEN = 0x8000
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x800 IN_NONBLOCK = 0x800
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9
IPV6_FLOWINFO_MASK = 0xffffff0f
IPV6_FLOWLABEL_MASK = 0xffff0f00
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -150,9 +153,14 @@ const (
NFDBITS = 0x40 NFDBITS = 0x40
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x8008b705
NS_GET_NSTYPE = 0xb703 NS_GET_NSTYPE = 0xb703
NS_GET_OWNER_UID = 0xb704 NS_GET_OWNER_UID = 0xb704
NS_GET_PARENT = 0xb702 NS_GET_PARENT = 0xb702
NS_GET_PID_FROM_PIDNS = 0x8004b706
NS_GET_PID_IN_PIDNS = 0x8004b708
NS_GET_TGID_FROM_PIDNS = 0x8004b707
NS_GET_TGID_IN_PIDNS = 0x8004b709
NS_GET_USERNS = 0xb701 NS_GET_USERNS = 0xb701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -229,6 +237,20 @@ const (
PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCUNBRIDGECHAN = 0x7434
PPPIOCXFERUNIT = 0x744e PPPIOCXFERUNIT = 0x744e
PR_SET_PTRACER_ANY = 0xffffffffffffffff PR_SET_PTRACER_ANY = 0xffffffffffffffff
PTP_CLOCK_GETCAPS = 0x80503d01
PTP_CLOCK_GETCAPS2 = 0x80503d0a
PTP_ENABLE_PPS = 0x40043d04
PTP_ENABLE_PPS2 = 0x40043d0d
PTP_EXTTS_REQUEST = 0x40103d02
PTP_EXTTS_REQUEST2 = 0x40103d0b
PTP_MASK_CLEAR_ALL = 0x3d13
PTP_MASK_EN_SINGLE = 0x40043d14
PTP_PEROUT_REQUEST = 0x40383d03
PTP_PEROUT_REQUEST2 = 0x40383d0c
PTP_PIN_SETFUNC = 0x40603d07
PTP_PIN_SETFUNC2 = 0x40603d10
PTP_SYS_OFFSET = 0x43403d05
PTP_SYS_OFFSET2 = 0x43403d0e
PTRACE_GETFDPIC = 0x21 PTRACE_GETFDPIC = 0x21
PTRACE_GETFDPIC_EXEC = 0x0 PTRACE_GETFDPIC_EXEC = 0x0
PTRACE_GETFDPIC_INTERP = 0x1 PTRACE_GETFDPIC_INTERP = 0x1
@@ -268,10 +290,13 @@ const (
RTC_WIE_ON = 0x700f RTC_WIE_ON = 0x700f
RTC_WKALM_RD = 0x80287010 RTC_WKALM_RD = 0x80287010
RTC_WKALM_SET = 0x4028700f RTC_WKALM_SET = 0x4028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103
@@ -306,6 +331,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x27 SO_DOMAIN = 0x27
SO_DONTROUTE = 0x5 SO_DONTROUTE = 0x5
SO_ERROR = 0x4 SO_ERROR = 0x4

View File

@@ -108,12 +108,15 @@ const (
HIDIOCGRAWINFO = 0x80084803 HIDIOCGRAWINFO = 0x80084803
HIDIOCGRDESC = 0x90044802 HIDIOCGRDESC = 0x90044802
HIDIOCGRDESCSIZE = 0x80044801 HIDIOCGRDESCSIZE = 0x80044801
HIDIOCREVOKE = 0x4004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x8000 IEXTEN = 0x8000
IN_CLOEXEC = 0x80000 IN_CLOEXEC = 0x80000
IN_NONBLOCK = 0x800 IN_NONBLOCK = 0x800
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x7b9
IPV6_FLOWINFO_MASK = 0xfffffff
IPV6_FLOWLABEL_MASK = 0xfffff
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -150,9 +153,14 @@ const (
NFDBITS = 0x40 NFDBITS = 0x40
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x8008b705
NS_GET_NSTYPE = 0xb703 NS_GET_NSTYPE = 0xb703
NS_GET_OWNER_UID = 0xb704 NS_GET_OWNER_UID = 0xb704
NS_GET_PARENT = 0xb702 NS_GET_PARENT = 0xb702
NS_GET_PID_FROM_PIDNS = 0x8004b706
NS_GET_PID_IN_PIDNS = 0x8004b708
NS_GET_TGID_FROM_PIDNS = 0x8004b707
NS_GET_TGID_IN_PIDNS = 0x8004b709
NS_GET_USERNS = 0xb701 NS_GET_USERNS = 0xb701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -229,6 +237,20 @@ const (
PPPIOCUNBRIDGECHAN = 0x7434 PPPIOCUNBRIDGECHAN = 0x7434
PPPIOCXFERUNIT = 0x744e PPPIOCXFERUNIT = 0x744e
PR_SET_PTRACER_ANY = 0xffffffffffffffff PR_SET_PTRACER_ANY = 0xffffffffffffffff
PTP_CLOCK_GETCAPS = 0x80503d01
PTP_CLOCK_GETCAPS2 = 0x80503d0a
PTP_ENABLE_PPS = 0x40043d04
PTP_ENABLE_PPS2 = 0x40043d0d
PTP_EXTTS_REQUEST = 0x40103d02
PTP_EXTTS_REQUEST2 = 0x40103d0b
PTP_MASK_CLEAR_ALL = 0x3d13
PTP_MASK_EN_SINGLE = 0x40043d14
PTP_PEROUT_REQUEST = 0x40383d03
PTP_PEROUT_REQUEST2 = 0x40383d0c
PTP_PIN_SETFUNC = 0x40603d07
PTP_PIN_SETFUNC2 = 0x40603d10
PTP_SYS_OFFSET = 0x43403d05
PTP_SYS_OFFSET2 = 0x43403d0e
PTRACE_DISABLE_TE = 0x5010 PTRACE_DISABLE_TE = 0x5010
PTRACE_ENABLE_TE = 0x5009 PTRACE_ENABLE_TE = 0x5009
PTRACE_GET_LAST_BREAK = 0x5006 PTRACE_GET_LAST_BREAK = 0x5006
@@ -340,10 +362,13 @@ const (
RTC_WIE_ON = 0x700f RTC_WIE_ON = 0x700f
RTC_WKALM_RD = 0x80287010 RTC_WKALM_RD = 0x80287010
RTC_WKALM_SET = 0x4028700f RTC_WKALM_SET = 0x4028700f
SCM_DEVMEM_DMABUF = 0x4f
SCM_DEVMEM_LINEAR = 0x4e
SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPING = 0x25
SCM_TIMESTAMPING_OPT_STATS = 0x36 SCM_TIMESTAMPING_OPT_STATS = 0x36
SCM_TIMESTAMPING_PKTINFO = 0x3a SCM_TIMESTAMPING_PKTINFO = 0x3a
SCM_TIMESTAMPNS = 0x23 SCM_TIMESTAMPNS = 0x23
SCM_TS_OPT_ID = 0x51
SCM_TXTIME = 0x3d SCM_TXTIME = 0x3d
SCM_WIFI_STATUS = 0x29 SCM_WIFI_STATUS = 0x29
SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x40182103
@@ -378,6 +403,9 @@ const (
SO_CNX_ADVICE = 0x35 SO_CNX_ADVICE = 0x35
SO_COOKIE = 0x39 SO_COOKIE = 0x39
SO_DETACH_REUSEPORT_BPF = 0x44 SO_DETACH_REUSEPORT_BPF = 0x44
SO_DEVMEM_DMABUF = 0x4f
SO_DEVMEM_DONTNEED = 0x50
SO_DEVMEM_LINEAR = 0x4e
SO_DOMAIN = 0x27 SO_DOMAIN = 0x27
SO_DONTROUTE = 0x5 SO_DONTROUTE = 0x5
SO_ERROR = 0x4 SO_ERROR = 0x4

View File

@@ -112,12 +112,15 @@ const (
HIDIOCGRAWINFO = 0x40084803 HIDIOCGRAWINFO = 0x40084803
HIDIOCGRDESC = 0x50044802 HIDIOCGRDESC = 0x50044802
HIDIOCGRDESCSIZE = 0x40044801 HIDIOCGRDESCSIZE = 0x40044801
HIDIOCREVOKE = 0x8004480d
HUPCL = 0x400 HUPCL = 0x400
ICANON = 0x2 ICANON = 0x2
IEXTEN = 0x8000 IEXTEN = 0x8000
IN_CLOEXEC = 0x400000 IN_CLOEXEC = 0x400000
IN_NONBLOCK = 0x4000 IN_NONBLOCK = 0x4000
IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9 IOCTL_VM_SOCKETS_GET_LOCAL_CID = 0x200007b9
IPV6_FLOWINFO_MASK = 0xfffffff
IPV6_FLOWLABEL_MASK = 0xfffff
ISIG = 0x1 ISIG = 0x1
IUCLC = 0x200 IUCLC = 0x200
IXOFF = 0x1000 IXOFF = 0x1000
@@ -155,9 +158,14 @@ const (
NFDBITS = 0x40 NFDBITS = 0x40
NLDLY = 0x100 NLDLY = 0x100
NOFLSH = 0x80 NOFLSH = 0x80
NS_GET_MNTNS_ID = 0x4008b705
NS_GET_NSTYPE = 0x2000b703 NS_GET_NSTYPE = 0x2000b703
NS_GET_OWNER_UID = 0x2000b704 NS_GET_OWNER_UID = 0x2000b704
NS_GET_PARENT = 0x2000b702 NS_GET_PARENT = 0x2000b702
NS_GET_PID_FROM_PIDNS = 0x4004b706
NS_GET_PID_IN_PIDNS = 0x4004b708
NS_GET_TGID_FROM_PIDNS = 0x4004b707
NS_GET_TGID_IN_PIDNS = 0x4004b709
NS_GET_USERNS = 0x2000b701 NS_GET_USERNS = 0x2000b701
OLCUC = 0x2 OLCUC = 0x2
ONLCR = 0x4 ONLCR = 0x4
@@ -234,6 +242,20 @@ const (
PPPIOCUNBRIDGECHAN = 0x20007434 PPPIOCUNBRIDGECHAN = 0x20007434
PPPIOCXFERUNIT = 0x2000744e PPPIOCXFERUNIT = 0x2000744e
PR_SET_PTRACER_ANY = 0xffffffffffffffff PR_SET_PTRACER_ANY = 0xffffffffffffffff
PTP_CLOCK_GETCAPS = 0x40503d01
PTP_CLOCK_GETCAPS2 = 0x40503d0a
PTP_ENABLE_PPS = 0x80043d04
PTP_ENABLE_PPS2 = 0x80043d0d
PTP_EXTTS_REQUEST = 0x80103d02
PTP_EXTTS_REQUEST2 = 0x80103d0b
PTP_MASK_CLEAR_ALL = 0x20003d13
PTP_MASK_EN_SINGLE = 0x80043d14
PTP_PEROUT_REQUEST = 0x80383d03
PTP_PEROUT_REQUEST2 = 0x80383d0c
PTP_PIN_SETFUNC = 0x80603d07
PTP_PIN_SETFUNC2 = 0x80603d10
PTP_SYS_OFFSET = 0x83403d05
PTP_SYS_OFFSET2 = 0x83403d0e
PTRACE_GETFPAREGS = 0x14 PTRACE_GETFPAREGS = 0x14
PTRACE_GETFPREGS = 0xe PTRACE_GETFPREGS = 0xe
PTRACE_GETFPREGS64 = 0x19 PTRACE_GETFPREGS64 = 0x19
@@ -331,10 +353,13 @@ const (
RTC_WIE_ON = 0x2000700f RTC_WIE_ON = 0x2000700f
RTC_WKALM_RD = 0x40287010 RTC_WKALM_RD = 0x40287010
RTC_WKALM_SET = 0x8028700f RTC_WKALM_SET = 0x8028700f
SCM_DEVMEM_DMABUF = 0x58
SCM_DEVMEM_LINEAR = 0x57
SCM_TIMESTAMPING = 0x23 SCM_TIMESTAMPING = 0x23
SCM_TIMESTAMPING_OPT_STATS = 0x38 SCM_TIMESTAMPING_OPT_STATS = 0x38
SCM_TIMESTAMPING_PKTINFO = 0x3c SCM_TIMESTAMPING_PKTINFO = 0x3c
SCM_TIMESTAMPNS = 0x21 SCM_TIMESTAMPNS = 0x21
SCM_TS_OPT_ID = 0x5a
SCM_TXTIME = 0x3f SCM_TXTIME = 0x3f
SCM_WIFI_STATUS = 0x25 SCM_WIFI_STATUS = 0x25
SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103 SECCOMP_IOCTL_NOTIF_ADDFD = 0x80182103
@@ -417,6 +442,9 @@ const (
SO_CNX_ADVICE = 0x37 SO_CNX_ADVICE = 0x37
SO_COOKIE = 0x3b SO_COOKIE = 0x3b
SO_DETACH_REUSEPORT_BPF = 0x47 SO_DETACH_REUSEPORT_BPF = 0x47
SO_DEVMEM_DMABUF = 0x58
SO_DEVMEM_DONTNEED = 0x59
SO_DEVMEM_LINEAR = 0x57
SO_DOMAIN = 0x1029 SO_DOMAIN = 0x1029
SO_DONTROUTE = 0x10 SO_DONTROUTE = 0x10
SO_ERROR = 0x1007 SO_ERROR = 0x1007

View File

@@ -2512,6 +2512,90 @@ var libc_munmap_trampoline_addr uintptr
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func readv(fd int, iovecs []Iovec) (n int, err error) {
var _p0 unsafe.Pointer
if len(iovecs) > 0 {
_p0 = unsafe.Pointer(&iovecs[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := syscall_syscall(libc_readv_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
var libc_readv_trampoline_addr uintptr
//go:cgo_import_dynamic libc_readv readv "/usr/lib/libSystem.B.dylib"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func preadv(fd int, iovecs []Iovec, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(iovecs) > 0 {
_p0 = unsafe.Pointer(&iovecs[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := syscall_syscall6(libc_preadv_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
var libc_preadv_trampoline_addr uintptr
//go:cgo_import_dynamic libc_preadv preadv "/usr/lib/libSystem.B.dylib"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func writev(fd int, iovecs []Iovec) (n int, err error) {
var _p0 unsafe.Pointer
if len(iovecs) > 0 {
_p0 = unsafe.Pointer(&iovecs[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := syscall_syscall(libc_writev_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
var libc_writev_trampoline_addr uintptr
//go:cgo_import_dynamic libc_writev writev "/usr/lib/libSystem.B.dylib"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func pwritev(fd int, iovecs []Iovec, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(iovecs) > 0 {
_p0 = unsafe.Pointer(&iovecs[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := syscall_syscall6(libc_pwritev_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
var libc_pwritev_trampoline_addr uintptr
//go:cgo_import_dynamic libc_pwritev pwritev "/usr/lib/libSystem.B.dylib"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstat(fd int, stat *Stat_t) (err error) { func Fstat(fd int, stat *Stat_t) (err error) {
_, _, e1 := syscall_syscall(libc_fstat64_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) _, _, e1 := syscall_syscall(libc_fstat64_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 { if e1 != 0 {

View File

@@ -738,6 +738,26 @@ TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0
GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8
DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB) DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB)
TEXT libc_readv_trampoline<>(SB),NOSPLIT,$0-0
JMP libc_readv(SB)
GLOBL ·libc_readv_trampoline_addr(SB), RODATA, $8
DATA ·libc_readv_trampoline_addr(SB)/8, $libc_readv_trampoline<>(SB)
TEXT libc_preadv_trampoline<>(SB),NOSPLIT,$0-0
JMP libc_preadv(SB)
GLOBL ·libc_preadv_trampoline_addr(SB), RODATA, $8
DATA ·libc_preadv_trampoline_addr(SB)/8, $libc_preadv_trampoline<>(SB)
TEXT libc_writev_trampoline<>(SB),NOSPLIT,$0-0
JMP libc_writev(SB)
GLOBL ·libc_writev_trampoline_addr(SB), RODATA, $8
DATA ·libc_writev_trampoline_addr(SB)/8, $libc_writev_trampoline<>(SB)
TEXT libc_pwritev_trampoline<>(SB),NOSPLIT,$0-0
JMP libc_pwritev(SB)
GLOBL ·libc_pwritev_trampoline_addr(SB), RODATA, $8
DATA ·libc_pwritev_trampoline_addr(SB)/8, $libc_pwritev_trampoline<>(SB)
TEXT libc_fstat64_trampoline<>(SB),NOSPLIT,$0-0 TEXT libc_fstat64_trampoline<>(SB),NOSPLIT,$0-0
JMP libc_fstat64(SB) JMP libc_fstat64(SB)
GLOBL ·libc_fstat64_trampoline_addr(SB), RODATA, $8 GLOBL ·libc_fstat64_trampoline_addr(SB), RODATA, $8

View File

@@ -2512,6 +2512,90 @@ var libc_munmap_trampoline_addr uintptr
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func readv(fd int, iovecs []Iovec) (n int, err error) {
var _p0 unsafe.Pointer
if len(iovecs) > 0 {
_p0 = unsafe.Pointer(&iovecs[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := syscall_syscall(libc_readv_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
var libc_readv_trampoline_addr uintptr
//go:cgo_import_dynamic libc_readv readv "/usr/lib/libSystem.B.dylib"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func preadv(fd int, iovecs []Iovec, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(iovecs) > 0 {
_p0 = unsafe.Pointer(&iovecs[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := syscall_syscall6(libc_preadv_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
var libc_preadv_trampoline_addr uintptr
//go:cgo_import_dynamic libc_preadv preadv "/usr/lib/libSystem.B.dylib"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func writev(fd int, iovecs []Iovec) (n int, err error) {
var _p0 unsafe.Pointer
if len(iovecs) > 0 {
_p0 = unsafe.Pointer(&iovecs[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := syscall_syscall(libc_writev_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
var libc_writev_trampoline_addr uintptr
//go:cgo_import_dynamic libc_writev writev "/usr/lib/libSystem.B.dylib"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func pwritev(fd int, iovecs []Iovec, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(iovecs) > 0 {
_p0 = unsafe.Pointer(&iovecs[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := syscall_syscall6(libc_pwritev_trampoline_addr, uintptr(fd), uintptr(_p0), uintptr(len(iovecs)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
var libc_pwritev_trampoline_addr uintptr
//go:cgo_import_dynamic libc_pwritev pwritev "/usr/lib/libSystem.B.dylib"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstat(fd int, stat *Stat_t) (err error) { func Fstat(fd int, stat *Stat_t) (err error) {
_, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 { if e1 != 0 {

View File

@@ -738,6 +738,26 @@ TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0
GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8
DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB) DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB)
TEXT libc_readv_trampoline<>(SB),NOSPLIT,$0-0
JMP libc_readv(SB)
GLOBL ·libc_readv_trampoline_addr(SB), RODATA, $8
DATA ·libc_readv_trampoline_addr(SB)/8, $libc_readv_trampoline<>(SB)
TEXT libc_preadv_trampoline<>(SB),NOSPLIT,$0-0
JMP libc_preadv(SB)
GLOBL ·libc_preadv_trampoline_addr(SB), RODATA, $8
DATA ·libc_preadv_trampoline_addr(SB)/8, $libc_preadv_trampoline<>(SB)
TEXT libc_writev_trampoline<>(SB),NOSPLIT,$0-0
JMP libc_writev(SB)
GLOBL ·libc_writev_trampoline_addr(SB), RODATA, $8
DATA ·libc_writev_trampoline_addr(SB)/8, $libc_writev_trampoline<>(SB)
TEXT libc_pwritev_trampoline<>(SB),NOSPLIT,$0-0
JMP libc_pwritev(SB)
GLOBL ·libc_pwritev_trampoline_addr(SB), RODATA, $8
DATA ·libc_pwritev_trampoline_addr(SB)/8, $libc_pwritev_trampoline<>(SB)
TEXT libc_fstat_trampoline<>(SB),NOSPLIT,$0-0 TEXT libc_fstat_trampoline<>(SB),NOSPLIT,$0-0
JMP libc_fstat(SB) JMP libc_fstat(SB)
GLOBL ·libc_fstat_trampoline_addr(SB), RODATA, $8 GLOBL ·libc_fstat_trampoline_addr(SB), RODATA, $8

View File

@@ -592,6 +592,16 @@ func ClockGettime(clockid int32, time *Timespec) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ClockSettime(clockid int32, time *Timespec) (err error) {
_, _, e1 := Syscall(SYS_CLOCK_SETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error) { func ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error) {
_, _, e1 := Syscall6(SYS_CLOCK_NANOSLEEP, uintptr(clockid), uintptr(flags), uintptr(unsafe.Pointer(request)), uintptr(unsafe.Pointer(remain)), 0, 0) _, _, e1 := Syscall6(SYS_CLOCK_NANOSLEEP, uintptr(clockid), uintptr(flags), uintptr(unsafe.Pointer(request)), uintptr(unsafe.Pointer(remain)), 0, 0)
if e1 != 0 { if e1 != 0 {
@@ -971,23 +981,6 @@ func Getpriority(which int, who int) (prio int, err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrandom(buf []byte, flags int) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_GETRANDOM, uintptr(_p0), uintptr(len(buf)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrusage(who int, rusage *Rusage) (err error) { func Getrusage(who int, rusage *Rusage) (err error) {
_, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0)
if e1 != 0 { if e1 != 0 {

View File

@@ -141,6 +141,16 @@ import (
//go:cgo_import_dynamic libc_getpeername getpeername "libsocket.so" //go:cgo_import_dynamic libc_getpeername getpeername "libsocket.so"
//go:cgo_import_dynamic libc_setsockopt setsockopt "libsocket.so" //go:cgo_import_dynamic libc_setsockopt setsockopt "libsocket.so"
//go:cgo_import_dynamic libc_recvfrom recvfrom "libsocket.so" //go:cgo_import_dynamic libc_recvfrom recvfrom "libsocket.so"
//go:cgo_import_dynamic libc_getpeerucred getpeerucred "libc.so"
//go:cgo_import_dynamic libc_ucred_get ucred_get "libc.so"
//go:cgo_import_dynamic libc_ucred_geteuid ucred_geteuid "libc.so"
//go:cgo_import_dynamic libc_ucred_getegid ucred_getegid "libc.so"
//go:cgo_import_dynamic libc_ucred_getruid ucred_getruid "libc.so"
//go:cgo_import_dynamic libc_ucred_getrgid ucred_getrgid "libc.so"
//go:cgo_import_dynamic libc_ucred_getsuid ucred_getsuid "libc.so"
//go:cgo_import_dynamic libc_ucred_getsgid ucred_getsgid "libc.so"
//go:cgo_import_dynamic libc_ucred_getpid ucred_getpid "libc.so"
//go:cgo_import_dynamic libc_ucred_free ucred_free "libc.so"
//go:cgo_import_dynamic libc_port_create port_create "libc.so" //go:cgo_import_dynamic libc_port_create port_create "libc.so"
//go:cgo_import_dynamic libc_port_associate port_associate "libc.so" //go:cgo_import_dynamic libc_port_associate port_associate "libc.so"
//go:cgo_import_dynamic libc_port_dissociate port_dissociate "libc.so" //go:cgo_import_dynamic libc_port_dissociate port_dissociate "libc.so"
@@ -280,6 +290,16 @@ import (
//go:linkname procgetpeername libc_getpeername //go:linkname procgetpeername libc_getpeername
//go:linkname procsetsockopt libc_setsockopt //go:linkname procsetsockopt libc_setsockopt
//go:linkname procrecvfrom libc_recvfrom //go:linkname procrecvfrom libc_recvfrom
//go:linkname procgetpeerucred libc_getpeerucred
//go:linkname procucred_get libc_ucred_get
//go:linkname procucred_geteuid libc_ucred_geteuid
//go:linkname procucred_getegid libc_ucred_getegid
//go:linkname procucred_getruid libc_ucred_getruid
//go:linkname procucred_getrgid libc_ucred_getrgid
//go:linkname procucred_getsuid libc_ucred_getsuid
//go:linkname procucred_getsgid libc_ucred_getsgid
//go:linkname procucred_getpid libc_ucred_getpid
//go:linkname procucred_free libc_ucred_free
//go:linkname procport_create libc_port_create //go:linkname procport_create libc_port_create
//go:linkname procport_associate libc_port_associate //go:linkname procport_associate libc_port_associate
//go:linkname procport_dissociate libc_port_dissociate //go:linkname procport_dissociate libc_port_dissociate
@@ -420,6 +440,16 @@ var (
procgetpeername, procgetpeername,
procsetsockopt, procsetsockopt,
procrecvfrom, procrecvfrom,
procgetpeerucred,
procucred_get,
procucred_geteuid,
procucred_getegid,
procucred_getruid,
procucred_getrgid,
procucred_getsuid,
procucred_getsgid,
procucred_getpid,
procucred_free,
procport_create, procport_create,
procport_associate, procport_associate,
procport_dissociate, procport_dissociate,
@@ -2029,6 +2059,90 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getpeerucred(fd uintptr, ucred *uintptr) (err error) {
_, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgetpeerucred)), 2, uintptr(fd), uintptr(unsafe.Pointer(ucred)), 0, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ucredGet(pid int) (ucred uintptr, err error) {
r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procucred_get)), 1, uintptr(pid), 0, 0, 0, 0, 0)
ucred = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ucredGeteuid(ucred uintptr) (uid int) {
r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procucred_geteuid)), 1, uintptr(ucred), 0, 0, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ucredGetegid(ucred uintptr) (gid int) {
r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procucred_getegid)), 1, uintptr(ucred), 0, 0, 0, 0, 0)
gid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ucredGetruid(ucred uintptr) (uid int) {
r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procucred_getruid)), 1, uintptr(ucred), 0, 0, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ucredGetrgid(ucred uintptr) (gid int) {
r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procucred_getrgid)), 1, uintptr(ucred), 0, 0, 0, 0, 0)
gid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ucredGetsuid(ucred uintptr) (uid int) {
r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procucred_getsuid)), 1, uintptr(ucred), 0, 0, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ucredGetsgid(ucred uintptr) (gid int) {
r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procucred_getsgid)), 1, uintptr(ucred), 0, 0, 0, 0, 0)
gid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ucredGetpid(ucred uintptr) (pid int) {
r0, _, _ := sysvicall6(uintptr(unsafe.Pointer(&procucred_getpid)), 1, uintptr(ucred), 0, 0, 0, 0, 0)
pid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ucredFree(ucred uintptr) {
sysvicall6(uintptr(unsafe.Pointer(&procucred_free)), 1, uintptr(ucred), 0, 0, 0, 0, 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func port_create() (n int, err error) { func port_create() (n int, err error) {
r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_create)), 0, 0, 0, 0, 0, 0, 0) r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_create)), 0, 0, 0, 0, 0, 0, 0)
n = int(r0) n = int(r0)

View File

@@ -458,4 +458,8 @@ const (
SYS_LSM_SET_SELF_ATTR = 460 SYS_LSM_SET_SELF_ATTR = 460
SYS_LSM_LIST_MODULES = 461 SYS_LSM_LIST_MODULES = 461
SYS_MSEAL = 462 SYS_MSEAL = 462
SYS_SETXATTRAT = 463
SYS_GETXATTRAT = 464
SYS_LISTXATTRAT = 465
SYS_REMOVEXATTRAT = 466
) )

View File

@@ -341,6 +341,7 @@ const (
SYS_STATX = 332 SYS_STATX = 332
SYS_IO_PGETEVENTS = 333 SYS_IO_PGETEVENTS = 333
SYS_RSEQ = 334 SYS_RSEQ = 334
SYS_URETPROBE = 335
SYS_PIDFD_SEND_SIGNAL = 424 SYS_PIDFD_SEND_SIGNAL = 424
SYS_IO_URING_SETUP = 425 SYS_IO_URING_SETUP = 425
SYS_IO_URING_ENTER = 426 SYS_IO_URING_ENTER = 426
@@ -380,4 +381,8 @@ const (
SYS_LSM_SET_SELF_ATTR = 460 SYS_LSM_SET_SELF_ATTR = 460
SYS_LSM_LIST_MODULES = 461 SYS_LSM_LIST_MODULES = 461
SYS_MSEAL = 462 SYS_MSEAL = 462
SYS_SETXATTRAT = 463
SYS_GETXATTRAT = 464
SYS_LISTXATTRAT = 465
SYS_REMOVEXATTRAT = 466
) )

View File

@@ -422,4 +422,8 @@ const (
SYS_LSM_SET_SELF_ATTR = 460 SYS_LSM_SET_SELF_ATTR = 460
SYS_LSM_LIST_MODULES = 461 SYS_LSM_LIST_MODULES = 461
SYS_MSEAL = 462 SYS_MSEAL = 462
SYS_SETXATTRAT = 463
SYS_GETXATTRAT = 464
SYS_LISTXATTRAT = 465
SYS_REMOVEXATTRAT = 466
) )

Some files were not shown because too many files have changed in this diff Show More