syscall_linux.go 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Linux system calls.
  5. // This file is compiled as ordinary Go code,
  6. // but it is also input to mksyscall,
  7. // which parses the //sys lines and generates system call stubs.
  8. // Note that sometimes we use a lowercase //sys name and
  9. // wrap it in our own nicer implementation.
  10. package unix
  11. import (
  12. "encoding/binary"
  13. "slices"
  14. "strconv"
  15. "syscall"
  16. "time"
  17. "unsafe"
  18. )
  19. /*
  20. * Wrapped
  21. */
  22. func Access(path string, mode uint32) (err error) {
  23. return Faccessat(AT_FDCWD, path, mode, 0)
  24. }
  25. func Chmod(path string, mode uint32) (err error) {
  26. return Fchmodat(AT_FDCWD, path, mode, 0)
  27. }
  28. func Chown(path string, uid int, gid int) (err error) {
  29. return Fchownat(AT_FDCWD, path, uid, gid, 0)
  30. }
  31. func Creat(path string, mode uint32) (fd int, err error) {
  32. return Open(path, O_CREAT|O_WRONLY|O_TRUNC, mode)
  33. }
  34. func EpollCreate(size int) (fd int, err error) {
  35. if size <= 0 {
  36. return -1, EINVAL
  37. }
  38. return EpollCreate1(0)
  39. }
  40. //sys FanotifyInit(flags uint, event_f_flags uint) (fd int, err error)
  41. //sys fanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname *byte) (err error)
  42. func FanotifyMark(fd int, flags uint, mask uint64, dirFd int, pathname string) (err error) {
  43. if pathname == "" {
  44. return fanotifyMark(fd, flags, mask, dirFd, nil)
  45. }
  46. p, err := BytePtrFromString(pathname)
  47. if err != nil {
  48. return err
  49. }
  50. return fanotifyMark(fd, flags, mask, dirFd, p)
  51. }
  52. //sys fchmodat(dirfd int, path string, mode uint32) (err error)
  53. //sys fchmodat2(dirfd int, path string, mode uint32, flags int) (err error)
  54. func Fchmodat(dirfd int, path string, mode uint32, flags int) error {
  55. // Linux fchmodat doesn't support the flags parameter, but fchmodat2 does.
  56. // Try fchmodat2 if flags are specified.
  57. if flags != 0 {
  58. err := fchmodat2(dirfd, path, mode, flags)
  59. if err == ENOSYS {
  60. // fchmodat2 isn't available. If the flags are known to be valid,
  61. // return EOPNOTSUPP to indicate that fchmodat doesn't support them.
  62. if flags&^(AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH) != 0 {
  63. return EINVAL
  64. } else if flags&(AT_SYMLINK_NOFOLLOW|AT_EMPTY_PATH) != 0 {
  65. return EOPNOTSUPP
  66. }
  67. }
  68. return err
  69. }
  70. return fchmodat(dirfd, path, mode)
  71. }
  72. func InotifyInit() (fd int, err error) {
  73. return InotifyInit1(0)
  74. }
  75. //sys ioctl(fd int, req uint, arg uintptr) (err error) = SYS_IOCTL
  76. //sys ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) = SYS_IOCTL
  77. // ioctl itself should not be exposed directly, but additional get/set functions
  78. // for specific types are permissible. These are defined in ioctl.go and
  79. // ioctl_linux.go.
  80. //
  81. // The third argument to ioctl is often a pointer but sometimes an integer.
  82. // Callers should use ioctlPtr when the third argument is a pointer and ioctl
  83. // when the third argument is an integer.
  84. //
  85. // TODO: some existing code incorrectly uses ioctl when it should use ioctlPtr.
  86. //sys Linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error)
  87. func Link(oldpath string, newpath string) (err error) {
  88. return Linkat(AT_FDCWD, oldpath, AT_FDCWD, newpath, 0)
  89. }
  90. func Mkdir(path string, mode uint32) (err error) {
  91. return Mkdirat(AT_FDCWD, path, mode)
  92. }
  93. func Mknod(path string, mode uint32, dev int) (err error) {
  94. return Mknodat(AT_FDCWD, path, mode, dev)
  95. }
  96. func Open(path string, mode int, perm uint32) (fd int, err error) {
  97. return openat(AT_FDCWD, path, mode|O_LARGEFILE, perm)
  98. }
  99. //sys openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
  100. func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) {
  101. return openat(dirfd, path, flags|O_LARGEFILE, mode)
  102. }
  103. //sys openat2(dirfd int, path string, open_how *OpenHow, size int) (fd int, err error)
  104. func Openat2(dirfd int, path string, how *OpenHow) (fd int, err error) {
  105. return openat2(dirfd, path, how, SizeofOpenHow)
  106. }
  107. func Pipe(p []int) error {
  108. return Pipe2(p, 0)
  109. }
  110. //sysnb pipe2(p *[2]_C_int, flags int) (err error)
  111. func Pipe2(p []int, flags int) error {
  112. if len(p) != 2 {
  113. return EINVAL
  114. }
  115. var pp [2]_C_int
  116. err := pipe2(&pp, flags)
  117. if err == nil {
  118. p[0] = int(pp[0])
  119. p[1] = int(pp[1])
  120. }
  121. return err
  122. }
  123. //sys ppoll(fds *PollFd, nfds int, timeout *Timespec, sigmask *Sigset_t) (n int, err error)
  124. func Ppoll(fds []PollFd, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
  125. if len(fds) == 0 {
  126. return ppoll(nil, 0, timeout, sigmask)
  127. }
  128. return ppoll(&fds[0], len(fds), timeout, sigmask)
  129. }
  130. func Poll(fds []PollFd, timeout int) (n int, err error) {
  131. var ts *Timespec
  132. if timeout >= 0 {
  133. ts = new(Timespec)
  134. *ts = NsecToTimespec(int64(timeout) * 1e6)
  135. }
  136. return Ppoll(fds, ts, nil)
  137. }
  138. //sys Readlinkat(dirfd int, path string, buf []byte) (n int, err error)
  139. func Readlink(path string, buf []byte) (n int, err error) {
  140. return Readlinkat(AT_FDCWD, path, buf)
  141. }
  142. func Rename(oldpath string, newpath string) (err error) {
  143. return Renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath)
  144. }
  145. func Rmdir(path string) error {
  146. return Unlinkat(AT_FDCWD, path, AT_REMOVEDIR)
  147. }
  148. //sys Symlinkat(oldpath string, newdirfd int, newpath string) (err error)
  149. func Symlink(oldpath string, newpath string) (err error) {
  150. return Symlinkat(oldpath, AT_FDCWD, newpath)
  151. }
  152. func Unlink(path string) error {
  153. return Unlinkat(AT_FDCWD, path, 0)
  154. }
  155. //sys Unlinkat(dirfd int, path string, flags int) (err error)
  156. func Utimes(path string, tv []Timeval) error {
  157. if tv == nil {
  158. err := utimensat(AT_FDCWD, path, nil, 0)
  159. if err != ENOSYS {
  160. return err
  161. }
  162. return utimes(path, nil)
  163. }
  164. if len(tv) != 2 {
  165. return EINVAL
  166. }
  167. var ts [2]Timespec
  168. ts[0] = NsecToTimespec(TimevalToNsec(tv[0]))
  169. ts[1] = NsecToTimespec(TimevalToNsec(tv[1]))
  170. err := utimensat(AT_FDCWD, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), 0)
  171. if err != ENOSYS {
  172. return err
  173. }
  174. return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  175. }
  176. //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error)
  177. func UtimesNano(path string, ts []Timespec) error {
  178. return UtimesNanoAt(AT_FDCWD, path, ts, 0)
  179. }
  180. func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error {
  181. if ts == nil {
  182. return utimensat(dirfd, path, nil, flags)
  183. }
  184. if len(ts) != 2 {
  185. return EINVAL
  186. }
  187. return utimensat(dirfd, path, (*[2]Timespec)(unsafe.Pointer(&ts[0])), flags)
  188. }
  189. func Futimesat(dirfd int, path string, tv []Timeval) error {
  190. if tv == nil {
  191. return futimesat(dirfd, path, nil)
  192. }
  193. if len(tv) != 2 {
  194. return EINVAL
  195. }
  196. return futimesat(dirfd, path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
  197. }
  198. func Futimes(fd int, tv []Timeval) (err error) {
  199. // Believe it or not, this is the best we can do on Linux
  200. // (and is what glibc does).
  201. return Utimes("/proc/self/fd/"+strconv.Itoa(fd), tv)
  202. }
  203. const ImplementsGetwd = true
  204. //sys Getcwd(buf []byte) (n int, err error)
  205. func Getwd() (wd string, err error) {
  206. var buf [PathMax]byte
  207. n, err := Getcwd(buf[0:])
  208. if err != nil {
  209. return "", err
  210. }
  211. // Getcwd returns the number of bytes written to buf, including the NUL.
  212. if n < 1 || n > len(buf) || buf[n-1] != 0 {
  213. return "", EINVAL
  214. }
  215. // In some cases, Linux can return a path that starts with the
  216. // "(unreachable)" prefix, which can potentially be a valid relative
  217. // path. To work around that, return ENOENT if path is not absolute.
  218. if buf[0] != '/' {
  219. return "", ENOENT
  220. }
  221. return string(buf[0 : n-1]), nil
  222. }
  223. func Getgroups() (gids []int, err error) {
  224. n, err := getgroups(0, nil)
  225. if err != nil {
  226. return nil, err
  227. }
  228. if n == 0 {
  229. return nil, nil
  230. }
  231. // Sanity check group count. Max is 1<<16 on Linux.
  232. if n < 0 || n > 1<<20 {
  233. return nil, EINVAL
  234. }
  235. a := make([]_Gid_t, n)
  236. n, err = getgroups(n, &a[0])
  237. if err != nil {
  238. return nil, err
  239. }
  240. gids = make([]int, n)
  241. for i, v := range a[0:n] {
  242. gids[i] = int(v)
  243. }
  244. return
  245. }
  246. func Setgroups(gids []int) (err error) {
  247. if len(gids) == 0 {
  248. return setgroups(0, nil)
  249. }
  250. a := make([]_Gid_t, len(gids))
  251. for i, v := range gids {
  252. a[i] = _Gid_t(v)
  253. }
  254. return setgroups(len(a), &a[0])
  255. }
  256. type WaitStatus uint32
  257. // Wait status is 7 bits at bottom, either 0 (exited),
  258. // 0x7F (stopped), or a signal number that caused an exit.
  259. // The 0x80 bit is whether there was a core dump.
  260. // An extra number (exit code, signal causing a stop)
  261. // is in the high bits. At least that's the idea.
  262. // There are various irregularities. For example, the
  263. // "continued" status is 0xFFFF, distinguishing itself
  264. // from stopped via the core dump bit.
  265. const (
  266. mask = 0x7F
  267. core = 0x80
  268. exited = 0x00
  269. stopped = 0x7F
  270. shift = 8
  271. )
  272. func (w WaitStatus) Exited() bool { return w&mask == exited }
  273. func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != exited }
  274. func (w WaitStatus) Stopped() bool { return w&0xFF == stopped }
  275. func (w WaitStatus) Continued() bool { return w == 0xFFFF }
  276. func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
  277. func (w WaitStatus) ExitStatus() int {
  278. if !w.Exited() {
  279. return -1
  280. }
  281. return int(w>>shift) & 0xFF
  282. }
  283. func (w WaitStatus) Signal() syscall.Signal {
  284. if !w.Signaled() {
  285. return -1
  286. }
  287. return syscall.Signal(w & mask)
  288. }
  289. func (w WaitStatus) StopSignal() syscall.Signal {
  290. if !w.Stopped() {
  291. return -1
  292. }
  293. return syscall.Signal(w>>shift) & 0xFF
  294. }
  295. func (w WaitStatus) TrapCause() int {
  296. if w.StopSignal() != SIGTRAP {
  297. return -1
  298. }
  299. return int(w>>shift) >> 8
  300. }
  301. //sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
  302. func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
  303. var status _C_int
  304. wpid, err = wait4(pid, &status, options, rusage)
  305. if wstatus != nil {
  306. *wstatus = WaitStatus(status)
  307. }
  308. return
  309. }
  310. //sys Waitid(idType int, id int, info *Siginfo, options int, rusage *Rusage) (err error)
  311. func Mkfifo(path string, mode uint32) error {
  312. return Mknod(path, mode|S_IFIFO, 0)
  313. }
  314. func Mkfifoat(dirfd int, path string, mode uint32) error {
  315. return Mknodat(dirfd, path, mode|S_IFIFO, 0)
  316. }
  317. func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
  318. if sa.Port < 0 || sa.Port > 0xFFFF {
  319. return nil, 0, EINVAL
  320. }
  321. sa.raw.Family = AF_INET
  322. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  323. p[0] = byte(sa.Port >> 8)
  324. p[1] = byte(sa.Port)
  325. sa.raw.Addr = sa.Addr
  326. return unsafe.Pointer(&sa.raw), SizeofSockaddrInet4, nil
  327. }
  328. func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
  329. if sa.Port < 0 || sa.Port > 0xFFFF {
  330. return nil, 0, EINVAL
  331. }
  332. sa.raw.Family = AF_INET6
  333. p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
  334. p[0] = byte(sa.Port >> 8)
  335. p[1] = byte(sa.Port)
  336. sa.raw.Scope_id = sa.ZoneId
  337. sa.raw.Addr = sa.Addr
  338. return unsafe.Pointer(&sa.raw), SizeofSockaddrInet6, nil
  339. }
  340. func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
  341. name := sa.Name
  342. n := len(name)
  343. if n >= len(sa.raw.Path) {
  344. return nil, 0, EINVAL
  345. }
  346. sa.raw.Family = AF_UNIX
  347. for i := range n {
  348. sa.raw.Path[i] = int8(name[i])
  349. }
  350. // length is family (uint16), name, NUL.
  351. sl := _Socklen(2)
  352. if n > 0 {
  353. sl += _Socklen(n) + 1
  354. }
  355. if sa.raw.Path[0] == '@' || (sa.raw.Path[0] == 0 && sl > 3) {
  356. // Check sl > 3 so we don't change unnamed socket behavior.
  357. sa.raw.Path[0] = 0
  358. // Don't count trailing NUL for abstract address.
  359. sl--
  360. }
  361. return unsafe.Pointer(&sa.raw), sl, nil
  362. }
  363. // SockaddrLinklayer implements the Sockaddr interface for AF_PACKET type sockets.
  364. type SockaddrLinklayer struct {
  365. Protocol uint16
  366. Ifindex int
  367. Hatype uint16
  368. Pkttype uint8
  369. Halen uint8
  370. Addr [8]byte
  371. raw RawSockaddrLinklayer
  372. }
  373. func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) {
  374. if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
  375. return nil, 0, EINVAL
  376. }
  377. sa.raw.Family = AF_PACKET
  378. sa.raw.Protocol = sa.Protocol
  379. sa.raw.Ifindex = int32(sa.Ifindex)
  380. sa.raw.Hatype = sa.Hatype
  381. sa.raw.Pkttype = sa.Pkttype
  382. sa.raw.Halen = sa.Halen
  383. sa.raw.Addr = sa.Addr
  384. return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil
  385. }
  386. // SockaddrNetlink implements the Sockaddr interface for AF_NETLINK type sockets.
  387. type SockaddrNetlink struct {
  388. Family uint16
  389. Pad uint16
  390. Pid uint32
  391. Groups uint32
  392. raw RawSockaddrNetlink
  393. }
  394. func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) {
  395. sa.raw.Family = AF_NETLINK
  396. sa.raw.Pad = sa.Pad
  397. sa.raw.Pid = sa.Pid
  398. sa.raw.Groups = sa.Groups
  399. return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil
  400. }
  401. // SockaddrHCI implements the Sockaddr interface for AF_BLUETOOTH type sockets
  402. // using the HCI protocol.
  403. type SockaddrHCI struct {
  404. Dev uint16
  405. Channel uint16
  406. raw RawSockaddrHCI
  407. }
  408. func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
  409. sa.raw.Family = AF_BLUETOOTH
  410. sa.raw.Dev = sa.Dev
  411. sa.raw.Channel = sa.Channel
  412. return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil
  413. }
  414. // SockaddrL2 implements the Sockaddr interface for AF_BLUETOOTH type sockets
  415. // using the L2CAP protocol.
  416. type SockaddrL2 struct {
  417. PSM uint16
  418. CID uint16
  419. Addr [6]uint8
  420. AddrType uint8
  421. raw RawSockaddrL2
  422. }
  423. func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) {
  424. sa.raw.Family = AF_BLUETOOTH
  425. psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm))
  426. psm[0] = byte(sa.PSM)
  427. psm[1] = byte(sa.PSM >> 8)
  428. for i := range len(sa.Addr) {
  429. sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i]
  430. }
  431. cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid))
  432. cid[0] = byte(sa.CID)
  433. cid[1] = byte(sa.CID >> 8)
  434. sa.raw.Bdaddr_type = sa.AddrType
  435. return unsafe.Pointer(&sa.raw), SizeofSockaddrL2, nil
  436. }
  437. // SockaddrRFCOMM implements the Sockaddr interface for AF_BLUETOOTH type sockets
  438. // using the RFCOMM protocol.
  439. //
  440. // Server example:
  441. //
  442. // fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)
  443. // _ = unix.Bind(fd, &unix.SockaddrRFCOMM{
  444. // Channel: 1,
  445. // Addr: [6]uint8{0, 0, 0, 0, 0, 0}, // BDADDR_ANY or 00:00:00:00:00:00
  446. // })
  447. // _ = Listen(fd, 1)
  448. // nfd, sa, _ := Accept(fd)
  449. // fmt.Printf("conn addr=%v fd=%d", sa.(*unix.SockaddrRFCOMM).Addr, nfd)
  450. // Read(nfd, buf)
  451. //
  452. // Client example:
  453. //
  454. // fd, _ := Socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)
  455. // _ = Connect(fd, &SockaddrRFCOMM{
  456. // Channel: 1,
  457. // Addr: [6]byte{0x11, 0x22, 0x33, 0xaa, 0xbb, 0xcc}, // CC:BB:AA:33:22:11
  458. // })
  459. // Write(fd, []byte(`hello`))
  460. type SockaddrRFCOMM struct {
  461. // Addr represents a bluetooth address, byte ordering is little-endian.
  462. Addr [6]uint8
  463. // Channel is a designated bluetooth channel, only 1-30 are available for use.
  464. // Since Linux 2.6.7 and further zero value is the first available channel.
  465. Channel uint8
  466. raw RawSockaddrRFCOMM
  467. }
  468. func (sa *SockaddrRFCOMM) sockaddr() (unsafe.Pointer, _Socklen, error) {
  469. sa.raw.Family = AF_BLUETOOTH
  470. sa.raw.Channel = sa.Channel
  471. sa.raw.Bdaddr = sa.Addr
  472. return unsafe.Pointer(&sa.raw), SizeofSockaddrRFCOMM, nil
  473. }
  474. // SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets.
  475. // The RxID and TxID fields are used for transport protocol addressing in
  476. // (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with
  477. // zero values for CAN_RAW and CAN_BCM sockets as they have no meaning.
  478. //
  479. // The SockaddrCAN struct must be bound to the socket file descriptor
  480. // using Bind before the CAN socket can be used.
  481. //
  482. // // Read one raw CAN frame
  483. // fd, _ := Socket(AF_CAN, SOCK_RAW, CAN_RAW)
  484. // addr := &SockaddrCAN{Ifindex: index}
  485. // Bind(fd, addr)
  486. // frame := make([]byte, 16)
  487. // Read(fd, frame)
  488. //
  489. // The full SocketCAN documentation can be found in the linux kernel
  490. // archives at: https://www.kernel.org/doc/Documentation/networking/can.txt
  491. type SockaddrCAN struct {
  492. Ifindex int
  493. RxID uint32
  494. TxID uint32
  495. raw RawSockaddrCAN
  496. }
  497. func (sa *SockaddrCAN) sockaddr() (unsafe.Pointer, _Socklen, error) {
  498. if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
  499. return nil, 0, EINVAL
  500. }
  501. sa.raw.Family = AF_CAN
  502. sa.raw.Ifindex = int32(sa.Ifindex)
  503. rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
  504. for i := range 4 {
  505. sa.raw.Addr[i] = rx[i]
  506. }
  507. tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
  508. for i := range 4 {
  509. sa.raw.Addr[i+4] = tx[i]
  510. }
  511. return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
  512. }
  513. // SockaddrCANJ1939 implements the Sockaddr interface for AF_CAN using J1939
  514. // protocol (https://en.wikipedia.org/wiki/SAE_J1939). For more information
  515. // on the purposes of the fields, check the official linux kernel documentation
  516. // available here: https://www.kernel.org/doc/Documentation/networking/j1939.rst
  517. type SockaddrCANJ1939 struct {
  518. Ifindex int
  519. Name uint64
  520. PGN uint32
  521. Addr uint8
  522. raw RawSockaddrCAN
  523. }
  524. func (sa *SockaddrCANJ1939) sockaddr() (unsafe.Pointer, _Socklen, error) {
  525. if sa.Ifindex < 0 || sa.Ifindex > 0x7fffffff {
  526. return nil, 0, EINVAL
  527. }
  528. sa.raw.Family = AF_CAN
  529. sa.raw.Ifindex = int32(sa.Ifindex)
  530. n := (*[8]byte)(unsafe.Pointer(&sa.Name))
  531. for i := range 8 {
  532. sa.raw.Addr[i] = n[i]
  533. }
  534. p := (*[4]byte)(unsafe.Pointer(&sa.PGN))
  535. for i := range 4 {
  536. sa.raw.Addr[i+8] = p[i]
  537. }
  538. sa.raw.Addr[12] = sa.Addr
  539. return unsafe.Pointer(&sa.raw), SizeofSockaddrCAN, nil
  540. }
  541. // SockaddrALG implements the Sockaddr interface for AF_ALG type sockets.
  542. // SockaddrALG enables userspace access to the Linux kernel's cryptography
  543. // subsystem. The Type and Name fields specify which type of hash or cipher
  544. // should be used with a given socket.
  545. //
  546. // To create a file descriptor that provides access to a hash or cipher, both
  547. // Bind and Accept must be used. Once the setup process is complete, input
  548. // data can be written to the socket, processed by the kernel, and then read
  549. // back as hash output or ciphertext.
  550. //
  551. // Here is an example of using an AF_ALG socket with SHA1 hashing.
  552. // The initial socket setup process is as follows:
  553. //
  554. // // Open a socket to perform SHA1 hashing.
  555. // fd, _ := unix.Socket(unix.AF_ALG, unix.SOCK_SEQPACKET, 0)
  556. // addr := &unix.SockaddrALG{Type: "hash", Name: "sha1"}
  557. // unix.Bind(fd, addr)
  558. // // Note: unix.Accept does not work at this time; must invoke accept()
  559. // // manually using unix.Syscall.
  560. // hashfd, _, _ := unix.Syscall(unix.SYS_ACCEPT, uintptr(fd), 0, 0)
  561. //
  562. // Once a file descriptor has been returned from Accept, it may be used to
  563. // perform SHA1 hashing. The descriptor is not safe for concurrent use, but
  564. // may be re-used repeatedly with subsequent Write and Read operations.
  565. //
  566. // When hashing a small byte slice or string, a single Write and Read may
  567. // be used:
  568. //
  569. // // Assume hashfd is already configured using the setup process.
  570. // hash := os.NewFile(hashfd, "sha1")
  571. // // Hash an input string and read the results. Each Write discards
  572. // // previous hash state. Read always reads the current state.
  573. // b := make([]byte, 20)
  574. // for i := 0; i < 2; i++ {
  575. // io.WriteString(hash, "Hello, world.")
  576. // hash.Read(b)
  577. // fmt.Println(hex.EncodeToString(b))
  578. // }
  579. // // Output:
  580. // // 2ae01472317d1935a84797ec1983ae243fc6aa28
  581. // // 2ae01472317d1935a84797ec1983ae243fc6aa28
  582. //
  583. // For hashing larger byte slices, or byte streams such as those read from
  584. // a file or socket, use Sendto with MSG_MORE to instruct the kernel to update
  585. // the hash digest instead of creating a new one for a given chunk and finalizing it.
  586. //
  587. // // Assume hashfd and addr are already configured using the setup process.
  588. // hash := os.NewFile(hashfd, "sha1")
  589. // // Hash the contents of a file.
  590. // f, _ := os.Open("/tmp/linux-4.10-rc7.tar.xz")
  591. // b := make([]byte, 4096)
  592. // for {
  593. // n, err := f.Read(b)
  594. // if err == io.EOF {
  595. // break
  596. // }
  597. // unix.Sendto(hashfd, b[:n], unix.MSG_MORE, addr)
  598. // }
  599. // hash.Read(b)
  600. // fmt.Println(hex.EncodeToString(b))
  601. // // Output: 85cdcad0c06eef66f805ecce353bec9accbeecc5
  602. //
  603. // For more information, see: http://www.chronox.de/crypto-API/crypto/userspace-if.html.
  604. type SockaddrALG struct {
  605. Type string
  606. Name string
  607. Feature uint32
  608. Mask uint32
  609. raw RawSockaddrALG
  610. }
  611. func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) {
  612. // Leave room for NUL byte terminator.
  613. if len(sa.Type) > len(sa.raw.Type)-1 {
  614. return nil, 0, EINVAL
  615. }
  616. if len(sa.Name) > len(sa.raw.Name)-1 {
  617. return nil, 0, EINVAL
  618. }
  619. sa.raw.Family = AF_ALG
  620. sa.raw.Feat = sa.Feature
  621. sa.raw.Mask = sa.Mask
  622. copy(sa.raw.Type[:], sa.Type)
  623. copy(sa.raw.Name[:], sa.Name)
  624. return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil
  625. }
  626. // SockaddrVM implements the Sockaddr interface for AF_VSOCK type sockets.
  627. // SockaddrVM provides access to Linux VM sockets: a mechanism that enables
  628. // bidirectional communication between a hypervisor and its guest virtual
  629. // machines.
  630. type SockaddrVM struct {
  631. // CID and Port specify a context ID and port address for a VM socket.
  632. // Guests have a unique CID, and hosts may have a well-known CID of:
  633. // - VMADDR_CID_HYPERVISOR: refers to the hypervisor process.
  634. // - VMADDR_CID_LOCAL: refers to local communication (loopback).
  635. // - VMADDR_CID_HOST: refers to other processes on the host.
  636. CID uint32
  637. Port uint32
  638. Flags uint8
  639. raw RawSockaddrVM
  640. }
  641. func (sa *SockaddrVM) sockaddr() (unsafe.Pointer, _Socklen, error) {
  642. sa.raw.Family = AF_VSOCK
  643. sa.raw.Port = sa.Port
  644. sa.raw.Cid = sa.CID
  645. sa.raw.Flags = sa.Flags
  646. return unsafe.Pointer(&sa.raw), SizeofSockaddrVM, nil
  647. }
  648. type SockaddrXDP struct {
  649. Flags uint16
  650. Ifindex uint32
  651. QueueID uint32
  652. SharedUmemFD uint32
  653. raw RawSockaddrXDP
  654. }
  655. func (sa *SockaddrXDP) sockaddr() (unsafe.Pointer, _Socklen, error) {
  656. sa.raw.Family = AF_XDP
  657. sa.raw.Flags = sa.Flags
  658. sa.raw.Ifindex = sa.Ifindex
  659. sa.raw.Queue_id = sa.QueueID
  660. sa.raw.Shared_umem_fd = sa.SharedUmemFD
  661. return unsafe.Pointer(&sa.raw), SizeofSockaddrXDP, nil
  662. }
  663. // This constant mirrors the #define of PX_PROTO_OE in
  664. // linux/if_pppox.h. We're defining this by hand here instead of
  665. // autogenerating through mkerrors.sh because including
  666. // linux/if_pppox.h causes some declaration conflicts with other
  667. // includes (linux/if_pppox.h includes linux/in.h, which conflicts
  668. // with netinet/in.h). Given that we only need a single zero constant
  669. // out of that file, it's cleaner to just define it by hand here.
  670. const px_proto_oe = 0
  671. type SockaddrPPPoE struct {
  672. SID uint16
  673. Remote []byte
  674. Dev string
  675. raw RawSockaddrPPPoX
  676. }
  677. func (sa *SockaddrPPPoE) sockaddr() (unsafe.Pointer, _Socklen, error) {
  678. if len(sa.Remote) != 6 {
  679. return nil, 0, EINVAL
  680. }
  681. if len(sa.Dev) > IFNAMSIZ-1 {
  682. return nil, 0, EINVAL
  683. }
  684. *(*uint16)(unsafe.Pointer(&sa.raw[0])) = AF_PPPOX
  685. // This next field is in host-endian byte order. We can't use the
  686. // same unsafe pointer cast as above, because this value is not
  687. // 32-bit aligned and some architectures don't allow unaligned
  688. // access.
  689. //
  690. // However, the value of px_proto_oe is 0, so we can use
  691. // encoding/binary helpers to write the bytes without worrying
  692. // about the ordering.
  693. binary.BigEndian.PutUint32(sa.raw[2:6], px_proto_oe)
  694. // This field is deliberately big-endian, unlike the previous
  695. // one. The kernel expects SID to be in network byte order.
  696. binary.BigEndian.PutUint16(sa.raw[6:8], sa.SID)
  697. copy(sa.raw[8:14], sa.Remote)
  698. clear(sa.raw[14 : 14+IFNAMSIZ])
  699. copy(sa.raw[14:], sa.Dev)
  700. return unsafe.Pointer(&sa.raw), SizeofSockaddrPPPoX, nil
  701. }
  702. // SockaddrTIPC implements the Sockaddr interface for AF_TIPC type sockets.
  703. // For more information on TIPC, see: http://tipc.sourceforge.net/.
  704. type SockaddrTIPC struct {
  705. // Scope is the publication scopes when binding service/service range.
  706. // Should be set to TIPC_CLUSTER_SCOPE or TIPC_NODE_SCOPE.
  707. Scope int
  708. // Addr is the type of address used to manipulate a socket. Addr must be
  709. // one of:
  710. // - *TIPCSocketAddr: "id" variant in the C addr union
  711. // - *TIPCServiceRange: "nameseq" variant in the C addr union
  712. // - *TIPCServiceName: "name" variant in the C addr union
  713. //
  714. // If nil, EINVAL will be returned when the structure is used.
  715. Addr TIPCAddr
  716. raw RawSockaddrTIPC
  717. }
  718. // TIPCAddr is implemented by types that can be used as an address for
  719. // SockaddrTIPC. It is only implemented by *TIPCSocketAddr, *TIPCServiceRange,
  720. // and *TIPCServiceName.
  721. type TIPCAddr interface {
  722. tipcAddrtype() uint8
  723. tipcAddr() [12]byte
  724. }
  725. func (sa *TIPCSocketAddr) tipcAddr() [12]byte {
  726. var out [12]byte
  727. copy(out[:], (*(*[unsafe.Sizeof(TIPCSocketAddr{})]byte)(unsafe.Pointer(sa)))[:])
  728. return out
  729. }
  730. func (sa *TIPCSocketAddr) tipcAddrtype() uint8 { return TIPC_SOCKET_ADDR }
  731. func (sa *TIPCServiceRange) tipcAddr() [12]byte {
  732. var out [12]byte
  733. copy(out[:], (*(*[unsafe.Sizeof(TIPCServiceRange{})]byte)(unsafe.Pointer(sa)))[:])
  734. return out
  735. }
  736. func (sa *TIPCServiceRange) tipcAddrtype() uint8 { return TIPC_SERVICE_RANGE }
  737. func (sa *TIPCServiceName) tipcAddr() [12]byte {
  738. var out [12]byte
  739. copy(out[:], (*(*[unsafe.Sizeof(TIPCServiceName{})]byte)(unsafe.Pointer(sa)))[:])
  740. return out
  741. }
  742. func (sa *TIPCServiceName) tipcAddrtype() uint8 { return TIPC_SERVICE_ADDR }
  743. func (sa *SockaddrTIPC) sockaddr() (unsafe.Pointer, _Socklen, error) {
  744. if sa.Addr == nil {
  745. return nil, 0, EINVAL
  746. }
  747. sa.raw.Family = AF_TIPC
  748. sa.raw.Scope = int8(sa.Scope)
  749. sa.raw.Addrtype = sa.Addr.tipcAddrtype()
  750. sa.raw.Addr = sa.Addr.tipcAddr()
  751. return unsafe.Pointer(&sa.raw), SizeofSockaddrTIPC, nil
  752. }
  753. // SockaddrL2TPIP implements the Sockaddr interface for IPPROTO_L2TP/AF_INET sockets.
  754. type SockaddrL2TPIP struct {
  755. Addr [4]byte
  756. ConnId uint32
  757. raw RawSockaddrL2TPIP
  758. }
  759. func (sa *SockaddrL2TPIP) sockaddr() (unsafe.Pointer, _Socklen, error) {
  760. sa.raw.Family = AF_INET
  761. sa.raw.Conn_id = sa.ConnId
  762. sa.raw.Addr = sa.Addr
  763. return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP, nil
  764. }
  765. // SockaddrL2TPIP6 implements the Sockaddr interface for IPPROTO_L2TP/AF_INET6 sockets.
  766. type SockaddrL2TPIP6 struct {
  767. Addr [16]byte
  768. ZoneId uint32
  769. ConnId uint32
  770. raw RawSockaddrL2TPIP6
  771. }
  772. func (sa *SockaddrL2TPIP6) sockaddr() (unsafe.Pointer, _Socklen, error) {
  773. sa.raw.Family = AF_INET6
  774. sa.raw.Conn_id = sa.ConnId
  775. sa.raw.Scope_id = sa.ZoneId
  776. sa.raw.Addr = sa.Addr
  777. return unsafe.Pointer(&sa.raw), SizeofSockaddrL2TPIP6, nil
  778. }
  779. // SockaddrIUCV implements the Sockaddr interface for AF_IUCV sockets.
  780. type SockaddrIUCV struct {
  781. UserID string
  782. Name string
  783. raw RawSockaddrIUCV
  784. }
  785. func (sa *SockaddrIUCV) sockaddr() (unsafe.Pointer, _Socklen, error) {
  786. sa.raw.Family = AF_IUCV
  787. // These are EBCDIC encoded by the kernel, but we still need to pad them
  788. // with blanks. Initializing with blanks allows the caller to feed in either
  789. // a padded or an unpadded string.
  790. for i := range 8 {
  791. sa.raw.Nodeid[i] = ' '
  792. sa.raw.User_id[i] = ' '
  793. sa.raw.Name[i] = ' '
  794. }
  795. if len(sa.UserID) > 8 || len(sa.Name) > 8 {
  796. return nil, 0, EINVAL
  797. }
  798. for i, b := range []byte(sa.UserID[:]) {
  799. sa.raw.User_id[i] = int8(b)
  800. }
  801. for i, b := range []byte(sa.Name[:]) {
  802. sa.raw.Name[i] = int8(b)
  803. }
  804. return unsafe.Pointer(&sa.raw), SizeofSockaddrIUCV, nil
  805. }
  806. type SockaddrNFC struct {
  807. DeviceIdx uint32
  808. TargetIdx uint32
  809. NFCProtocol uint32
  810. raw RawSockaddrNFC
  811. }
  812. func (sa *SockaddrNFC) sockaddr() (unsafe.Pointer, _Socklen, error) {
  813. sa.raw.Sa_family = AF_NFC
  814. sa.raw.Dev_idx = sa.DeviceIdx
  815. sa.raw.Target_idx = sa.TargetIdx
  816. sa.raw.Nfc_protocol = sa.NFCProtocol
  817. return unsafe.Pointer(&sa.raw), SizeofSockaddrNFC, nil
  818. }
  819. type SockaddrNFCLLCP struct {
  820. DeviceIdx uint32
  821. TargetIdx uint32
  822. NFCProtocol uint32
  823. DestinationSAP uint8
  824. SourceSAP uint8
  825. ServiceName string
  826. raw RawSockaddrNFCLLCP
  827. }
  828. func (sa *SockaddrNFCLLCP) sockaddr() (unsafe.Pointer, _Socklen, error) {
  829. sa.raw.Sa_family = AF_NFC
  830. sa.raw.Dev_idx = sa.DeviceIdx
  831. sa.raw.Target_idx = sa.TargetIdx
  832. sa.raw.Nfc_protocol = sa.NFCProtocol
  833. sa.raw.Dsap = sa.DestinationSAP
  834. sa.raw.Ssap = sa.SourceSAP
  835. if len(sa.ServiceName) > len(sa.raw.Service_name) {
  836. return nil, 0, EINVAL
  837. }
  838. copy(sa.raw.Service_name[:], sa.ServiceName)
  839. sa.raw.SetServiceNameLen(len(sa.ServiceName))
  840. return unsafe.Pointer(&sa.raw), SizeofSockaddrNFCLLCP, nil
  841. }
  842. var socketProtocol = func(fd int) (int, error) {
  843. return GetsockoptInt(fd, SOL_SOCKET, SO_PROTOCOL)
  844. }
  845. func anyToSockaddr(fd int, rsa *RawSockaddrAny) (Sockaddr, error) {
  846. switch rsa.Addr.Family {
  847. case AF_NETLINK:
  848. pp := (*RawSockaddrNetlink)(unsafe.Pointer(rsa))
  849. sa := new(SockaddrNetlink)
  850. sa.Family = pp.Family
  851. sa.Pad = pp.Pad
  852. sa.Pid = pp.Pid
  853. sa.Groups = pp.Groups
  854. return sa, nil
  855. case AF_PACKET:
  856. pp := (*RawSockaddrLinklayer)(unsafe.Pointer(rsa))
  857. sa := new(SockaddrLinklayer)
  858. sa.Protocol = pp.Protocol
  859. sa.Ifindex = int(pp.Ifindex)
  860. sa.Hatype = pp.Hatype
  861. sa.Pkttype = pp.Pkttype
  862. sa.Halen = pp.Halen
  863. sa.Addr = pp.Addr
  864. return sa, nil
  865. case AF_UNIX:
  866. pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
  867. sa := new(SockaddrUnix)
  868. if pp.Path[0] == 0 {
  869. // "Abstract" Unix domain socket.
  870. // Rewrite leading NUL as @ for textual display.
  871. // (This is the standard convention.)
  872. // Not friendly to overwrite in place,
  873. // but the callers below don't care.
  874. pp.Path[0] = '@'
  875. }
  876. // Assume path ends at NUL.
  877. // This is not technically the Linux semantics for
  878. // abstract Unix domain sockets--they are supposed
  879. // to be uninterpreted fixed-size binary blobs--but
  880. // everyone uses this convention.
  881. n := 0
  882. for n < len(pp.Path) && pp.Path[n] != 0 {
  883. n++
  884. }
  885. sa.Name = string(unsafe.Slice((*byte)(unsafe.Pointer(&pp.Path[0])), n))
  886. return sa, nil
  887. case AF_INET:
  888. proto, err := socketProtocol(fd)
  889. if err != nil {
  890. return nil, err
  891. }
  892. switch proto {
  893. case IPPROTO_L2TP:
  894. pp := (*RawSockaddrL2TPIP)(unsafe.Pointer(rsa))
  895. sa := new(SockaddrL2TPIP)
  896. sa.ConnId = pp.Conn_id
  897. sa.Addr = pp.Addr
  898. return sa, nil
  899. default:
  900. pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
  901. sa := new(SockaddrInet4)
  902. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  903. sa.Port = int(p[0])<<8 + int(p[1])
  904. sa.Addr = pp.Addr
  905. return sa, nil
  906. }
  907. case AF_INET6:
  908. proto, err := socketProtocol(fd)
  909. if err != nil {
  910. return nil, err
  911. }
  912. switch proto {
  913. case IPPROTO_L2TP:
  914. pp := (*RawSockaddrL2TPIP6)(unsafe.Pointer(rsa))
  915. sa := new(SockaddrL2TPIP6)
  916. sa.ConnId = pp.Conn_id
  917. sa.ZoneId = pp.Scope_id
  918. sa.Addr = pp.Addr
  919. return sa, nil
  920. default:
  921. pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
  922. sa := new(SockaddrInet6)
  923. p := (*[2]byte)(unsafe.Pointer(&pp.Port))
  924. sa.Port = int(p[0])<<8 + int(p[1])
  925. sa.ZoneId = pp.Scope_id
  926. sa.Addr = pp.Addr
  927. return sa, nil
  928. }
  929. case AF_VSOCK:
  930. pp := (*RawSockaddrVM)(unsafe.Pointer(rsa))
  931. sa := &SockaddrVM{
  932. CID: pp.Cid,
  933. Port: pp.Port,
  934. Flags: pp.Flags,
  935. }
  936. return sa, nil
  937. case AF_BLUETOOTH:
  938. proto, err := socketProtocol(fd)
  939. if err != nil {
  940. return nil, err
  941. }
  942. // only BTPROTO_L2CAP and BTPROTO_RFCOMM can accept connections
  943. switch proto {
  944. case BTPROTO_L2CAP:
  945. pp := (*RawSockaddrL2)(unsafe.Pointer(rsa))
  946. sa := &SockaddrL2{
  947. PSM: pp.Psm,
  948. CID: pp.Cid,
  949. Addr: pp.Bdaddr,
  950. AddrType: pp.Bdaddr_type,
  951. }
  952. return sa, nil
  953. case BTPROTO_RFCOMM:
  954. pp := (*RawSockaddrRFCOMM)(unsafe.Pointer(rsa))
  955. sa := &SockaddrRFCOMM{
  956. Channel: pp.Channel,
  957. Addr: pp.Bdaddr,
  958. }
  959. return sa, nil
  960. }
  961. case AF_XDP:
  962. pp := (*RawSockaddrXDP)(unsafe.Pointer(rsa))
  963. sa := &SockaddrXDP{
  964. Flags: pp.Flags,
  965. Ifindex: pp.Ifindex,
  966. QueueID: pp.Queue_id,
  967. SharedUmemFD: pp.Shared_umem_fd,
  968. }
  969. return sa, nil
  970. case AF_PPPOX:
  971. pp := (*RawSockaddrPPPoX)(unsafe.Pointer(rsa))
  972. if binary.BigEndian.Uint32(pp[2:6]) != px_proto_oe {
  973. return nil, EINVAL
  974. }
  975. sa := &SockaddrPPPoE{
  976. SID: binary.BigEndian.Uint16(pp[6:8]),
  977. Remote: pp[8:14],
  978. }
  979. for i := 14; i < 14+IFNAMSIZ; i++ {
  980. if pp[i] == 0 {
  981. sa.Dev = string(pp[14:i])
  982. break
  983. }
  984. }
  985. return sa, nil
  986. case AF_TIPC:
  987. pp := (*RawSockaddrTIPC)(unsafe.Pointer(rsa))
  988. sa := &SockaddrTIPC{
  989. Scope: int(pp.Scope),
  990. }
  991. // Determine which union variant is present in pp.Addr by checking
  992. // pp.Addrtype.
  993. switch pp.Addrtype {
  994. case TIPC_SERVICE_RANGE:
  995. sa.Addr = (*TIPCServiceRange)(unsafe.Pointer(&pp.Addr))
  996. case TIPC_SERVICE_ADDR:
  997. sa.Addr = (*TIPCServiceName)(unsafe.Pointer(&pp.Addr))
  998. case TIPC_SOCKET_ADDR:
  999. sa.Addr = (*TIPCSocketAddr)(unsafe.Pointer(&pp.Addr))
  1000. default:
  1001. return nil, EINVAL
  1002. }
  1003. return sa, nil
  1004. case AF_IUCV:
  1005. pp := (*RawSockaddrIUCV)(unsafe.Pointer(rsa))
  1006. var user [8]byte
  1007. var name [8]byte
  1008. for i := range 8 {
  1009. user[i] = byte(pp.User_id[i])
  1010. name[i] = byte(pp.Name[i])
  1011. }
  1012. sa := &SockaddrIUCV{
  1013. UserID: string(user[:]),
  1014. Name: string(name[:]),
  1015. }
  1016. return sa, nil
  1017. case AF_CAN:
  1018. proto, err := socketProtocol(fd)
  1019. if err != nil {
  1020. return nil, err
  1021. }
  1022. pp := (*RawSockaddrCAN)(unsafe.Pointer(rsa))
  1023. switch proto {
  1024. case CAN_J1939:
  1025. sa := &SockaddrCANJ1939{
  1026. Ifindex: int(pp.Ifindex),
  1027. }
  1028. name := (*[8]byte)(unsafe.Pointer(&sa.Name))
  1029. for i := range 8 {
  1030. name[i] = pp.Addr[i]
  1031. }
  1032. pgn := (*[4]byte)(unsafe.Pointer(&sa.PGN))
  1033. for i := range 4 {
  1034. pgn[i] = pp.Addr[i+8]
  1035. }
  1036. addr := (*[1]byte)(unsafe.Pointer(&sa.Addr))
  1037. addr[0] = pp.Addr[12]
  1038. return sa, nil
  1039. default:
  1040. sa := &SockaddrCAN{
  1041. Ifindex: int(pp.Ifindex),
  1042. }
  1043. rx := (*[4]byte)(unsafe.Pointer(&sa.RxID))
  1044. for i := range 4 {
  1045. rx[i] = pp.Addr[i]
  1046. }
  1047. tx := (*[4]byte)(unsafe.Pointer(&sa.TxID))
  1048. for i := range 4 {
  1049. tx[i] = pp.Addr[i+4]
  1050. }
  1051. return sa, nil
  1052. }
  1053. case AF_NFC:
  1054. proto, err := socketProtocol(fd)
  1055. if err != nil {
  1056. return nil, err
  1057. }
  1058. switch proto {
  1059. case NFC_SOCKPROTO_RAW:
  1060. pp := (*RawSockaddrNFC)(unsafe.Pointer(rsa))
  1061. sa := &SockaddrNFC{
  1062. DeviceIdx: pp.Dev_idx,
  1063. TargetIdx: pp.Target_idx,
  1064. NFCProtocol: pp.Nfc_protocol,
  1065. }
  1066. return sa, nil
  1067. case NFC_SOCKPROTO_LLCP:
  1068. pp := (*RawSockaddrNFCLLCP)(unsafe.Pointer(rsa))
  1069. if uint64(pp.Service_name_len) > uint64(len(pp.Service_name)) {
  1070. return nil, EINVAL
  1071. }
  1072. sa := &SockaddrNFCLLCP{
  1073. DeviceIdx: pp.Dev_idx,
  1074. TargetIdx: pp.Target_idx,
  1075. NFCProtocol: pp.Nfc_protocol,
  1076. DestinationSAP: pp.Dsap,
  1077. SourceSAP: pp.Ssap,
  1078. ServiceName: string(pp.Service_name[:pp.Service_name_len]),
  1079. }
  1080. return sa, nil
  1081. default:
  1082. return nil, EINVAL
  1083. }
  1084. }
  1085. return nil, EAFNOSUPPORT
  1086. }
  1087. func Accept(fd int) (nfd int, sa Sockaddr, err error) {
  1088. var rsa RawSockaddrAny
  1089. var len _Socklen = SizeofSockaddrAny
  1090. nfd, err = accept4(fd, &rsa, &len, 0)
  1091. if err != nil {
  1092. return
  1093. }
  1094. sa, err = anyToSockaddr(fd, &rsa)
  1095. if err != nil {
  1096. Close(nfd)
  1097. nfd = 0
  1098. }
  1099. return
  1100. }
  1101. func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error) {
  1102. var rsa RawSockaddrAny
  1103. var len _Socklen = SizeofSockaddrAny
  1104. nfd, err = accept4(fd, &rsa, &len, flags)
  1105. if err != nil {
  1106. return
  1107. }
  1108. if len > SizeofSockaddrAny {
  1109. panic("RawSockaddrAny too small")
  1110. }
  1111. sa, err = anyToSockaddr(fd, &rsa)
  1112. if err != nil {
  1113. Close(nfd)
  1114. nfd = 0
  1115. }
  1116. return
  1117. }
  1118. func Getsockname(fd int) (sa Sockaddr, err error) {
  1119. var rsa RawSockaddrAny
  1120. var len _Socklen = SizeofSockaddrAny
  1121. if err = getsockname(fd, &rsa, &len); err != nil {
  1122. return
  1123. }
  1124. return anyToSockaddr(fd, &rsa)
  1125. }
  1126. func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) {
  1127. var value IPMreqn
  1128. vallen := _Socklen(SizeofIPMreqn)
  1129. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1130. return &value, err
  1131. }
  1132. func GetsockoptUcred(fd, level, opt int) (*Ucred, error) {
  1133. var value Ucred
  1134. vallen := _Socklen(SizeofUcred)
  1135. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1136. return &value, err
  1137. }
  1138. func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) {
  1139. var value TCPInfo
  1140. vallen := _Socklen(SizeofTCPInfo)
  1141. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1142. return &value, err
  1143. }
  1144. // GetsockoptTCPCCVegasInfo returns algorithm specific congestion control information for a socket using the "vegas"
  1145. // algorithm.
  1146. //
  1147. // The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option:
  1148. //
  1149. // algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION)
  1150. func GetsockoptTCPCCVegasInfo(fd, level, opt int) (*TCPVegasInfo, error) {
  1151. var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment
  1152. vallen := _Socklen(SizeofTCPCCInfo)
  1153. err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
  1154. out := (*TCPVegasInfo)(unsafe.Pointer(&value[0]))
  1155. return out, err
  1156. }
  1157. // GetsockoptTCPCCDCTCPInfo returns algorithm specific congestion control information for a socket using the "dctp"
  1158. // algorithm.
  1159. //
  1160. // The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option:
  1161. //
  1162. // algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION)
  1163. func GetsockoptTCPCCDCTCPInfo(fd, level, opt int) (*TCPDCTCPInfo, error) {
  1164. var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment
  1165. vallen := _Socklen(SizeofTCPCCInfo)
  1166. err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
  1167. out := (*TCPDCTCPInfo)(unsafe.Pointer(&value[0]))
  1168. return out, err
  1169. }
  1170. // GetsockoptTCPCCBBRInfo returns algorithm specific congestion control information for a socket using the "bbr"
  1171. // algorithm.
  1172. //
  1173. // The socket's congestion control algorighm can be retrieved via [GetsockoptString] with the [TCP_CONGESTION] option:
  1174. //
  1175. // algo, err := unix.GetsockoptString(fd, unix.IPPROTO_TCP, unix.TCP_CONGESTION)
  1176. func GetsockoptTCPCCBBRInfo(fd, level, opt int) (*TCPBBRInfo, error) {
  1177. var value [SizeofTCPCCInfo / 4]uint32 // ensure proper alignment
  1178. vallen := _Socklen(SizeofTCPCCInfo)
  1179. err := getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
  1180. out := (*TCPBBRInfo)(unsafe.Pointer(&value[0]))
  1181. return out, err
  1182. }
  1183. // GetsockoptString returns the string value of the socket option opt for the
  1184. // socket associated with fd at the given socket level.
  1185. func GetsockoptString(fd, level, opt int) (string, error) {
  1186. buf := make([]byte, 256)
  1187. vallen := _Socklen(len(buf))
  1188. err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
  1189. if err != nil {
  1190. if err == ERANGE {
  1191. buf = make([]byte, vallen)
  1192. err = getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen)
  1193. }
  1194. if err != nil {
  1195. return "", err
  1196. }
  1197. }
  1198. return ByteSliceToString(buf[:vallen]), nil
  1199. }
  1200. func GetsockoptTpacketStats(fd, level, opt int) (*TpacketStats, error) {
  1201. var value TpacketStats
  1202. vallen := _Socklen(SizeofTpacketStats)
  1203. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1204. return &value, err
  1205. }
  1206. func GetsockoptTpacketStatsV3(fd, level, opt int) (*TpacketStatsV3, error) {
  1207. var value TpacketStatsV3
  1208. vallen := _Socklen(SizeofTpacketStatsV3)
  1209. err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
  1210. return &value, err
  1211. }
  1212. func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) {
  1213. return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
  1214. }
  1215. func SetsockoptPacketMreq(fd, level, opt int, mreq *PacketMreq) error {
  1216. return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq))
  1217. }
  1218. // SetsockoptSockFprog attaches a classic BPF or an extended BPF program to a
  1219. // socket to filter incoming packets. See 'man 7 socket' for usage information.
  1220. func SetsockoptSockFprog(fd, level, opt int, fprog *SockFprog) error {
  1221. return setsockopt(fd, level, opt, unsafe.Pointer(fprog), unsafe.Sizeof(*fprog))
  1222. }
  1223. func SetsockoptCanRawFilter(fd, level, opt int, filter []CanFilter) error {
  1224. var p unsafe.Pointer
  1225. if len(filter) > 0 {
  1226. p = unsafe.Pointer(&filter[0])
  1227. }
  1228. return setsockopt(fd, level, opt, p, uintptr(len(filter)*SizeofCanFilter))
  1229. }
  1230. func SetsockoptTpacketReq(fd, level, opt int, tp *TpacketReq) error {
  1231. return setsockopt(fd, level, opt, unsafe.Pointer(tp), unsafe.Sizeof(*tp))
  1232. }
  1233. func SetsockoptTpacketReq3(fd, level, opt int, tp *TpacketReq3) error {
  1234. return setsockopt(fd, level, opt, unsafe.Pointer(tp), unsafe.Sizeof(*tp))
  1235. }
  1236. func SetsockoptTCPRepairOpt(fd, level, opt int, o []TCPRepairOpt) (err error) {
  1237. if len(o) == 0 {
  1238. return EINVAL
  1239. }
  1240. return setsockopt(fd, level, opt, unsafe.Pointer(&o[0]), uintptr(SizeofTCPRepairOpt*len(o)))
  1241. }
  1242. func SetsockoptTCPMD5Sig(fd, level, opt int, s *TCPMD5Sig) error {
  1243. return setsockopt(fd, level, opt, unsafe.Pointer(s), unsafe.Sizeof(*s))
  1244. }
  1245. // Keyctl Commands (http://man7.org/linux/man-pages/man2/keyctl.2.html)
  1246. // KeyctlInt calls keyctl commands in which each argument is an int.
  1247. // These commands are KEYCTL_REVOKE, KEYCTL_CHOWN, KEYCTL_CLEAR, KEYCTL_LINK,
  1248. // KEYCTL_UNLINK, KEYCTL_NEGATE, KEYCTL_SET_REQKEY_KEYRING, KEYCTL_SET_TIMEOUT,
  1249. // KEYCTL_ASSUME_AUTHORITY, KEYCTL_SESSION_TO_PARENT, KEYCTL_REJECT,
  1250. // KEYCTL_INVALIDATE, and KEYCTL_GET_PERSISTENT.
  1251. //sys KeyctlInt(cmd int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err error) = SYS_KEYCTL
  1252. // KeyctlBuffer calls keyctl commands in which the third and fourth
  1253. // arguments are a buffer and its length, respectively.
  1254. // These commands are KEYCTL_UPDATE, KEYCTL_READ, and KEYCTL_INSTANTIATE.
  1255. //sys KeyctlBuffer(cmd int, arg2 int, buf []byte, arg5 int) (ret int, err error) = SYS_KEYCTL
  1256. // KeyctlString calls keyctl commands which return a string.
  1257. // These commands are KEYCTL_DESCRIBE and KEYCTL_GET_SECURITY.
  1258. func KeyctlString(cmd int, id int) (string, error) {
  1259. // We must loop as the string data may change in between the syscalls.
  1260. // We could allocate a large buffer here to reduce the chance that the
  1261. // syscall needs to be called twice; however, this is unnecessary as
  1262. // the performance loss is negligible.
  1263. var buffer []byte
  1264. for {
  1265. // Try to fill the buffer with data
  1266. length, err := KeyctlBuffer(cmd, id, buffer, 0)
  1267. if err != nil {
  1268. return "", err
  1269. }
  1270. // Check if the data was written
  1271. if length <= len(buffer) {
  1272. // Exclude the null terminator
  1273. return string(buffer[:length-1]), nil
  1274. }
  1275. // Make a bigger buffer if needed
  1276. buffer = make([]byte, length)
  1277. }
  1278. }
  1279. // Keyctl commands with special signatures.
  1280. // KeyctlGetKeyringID implements the KEYCTL_GET_KEYRING_ID command.
  1281. // See the full documentation at:
  1282. // http://man7.org/linux/man-pages/man3/keyctl_get_keyring_ID.3.html
  1283. func KeyctlGetKeyringID(id int, create bool) (ringid int, err error) {
  1284. createInt := 0
  1285. if create {
  1286. createInt = 1
  1287. }
  1288. return KeyctlInt(KEYCTL_GET_KEYRING_ID, id, createInt, 0, 0)
  1289. }
  1290. // KeyctlSetperm implements the KEYCTL_SETPERM command. The perm value is the
  1291. // key handle permission mask as described in the "keyctl setperm" section of
  1292. // http://man7.org/linux/man-pages/man1/keyctl.1.html.
  1293. // See the full documentation at:
  1294. // http://man7.org/linux/man-pages/man3/keyctl_setperm.3.html
  1295. func KeyctlSetperm(id int, perm uint32) error {
  1296. _, err := KeyctlInt(KEYCTL_SETPERM, id, int(perm), 0, 0)
  1297. return err
  1298. }
  1299. //sys keyctlJoin(cmd int, arg2 string) (ret int, err error) = SYS_KEYCTL
  1300. // KeyctlJoinSessionKeyring implements the KEYCTL_JOIN_SESSION_KEYRING command.
  1301. // See the full documentation at:
  1302. // http://man7.org/linux/man-pages/man3/keyctl_join_session_keyring.3.html
  1303. func KeyctlJoinSessionKeyring(name string) (ringid int, err error) {
  1304. return keyctlJoin(KEYCTL_JOIN_SESSION_KEYRING, name)
  1305. }
  1306. //sys keyctlSearch(cmd int, arg2 int, arg3 string, arg4 string, arg5 int) (ret int, err error) = SYS_KEYCTL
  1307. // KeyctlSearch implements the KEYCTL_SEARCH command.
  1308. // See the full documentation at:
  1309. // http://man7.org/linux/man-pages/man3/keyctl_search.3.html
  1310. func KeyctlSearch(ringid int, keyType, description string, destRingid int) (id int, err error) {
  1311. return keyctlSearch(KEYCTL_SEARCH, ringid, keyType, description, destRingid)
  1312. }
  1313. //sys keyctlIOV(cmd int, arg2 int, payload []Iovec, arg5 int) (err error) = SYS_KEYCTL
  1314. // KeyctlInstantiateIOV implements the KEYCTL_INSTANTIATE_IOV command. This
  1315. // command is similar to KEYCTL_INSTANTIATE, except that the payload is a slice
  1316. // of Iovec (each of which represents a buffer) instead of a single buffer.
  1317. // See the full documentation at:
  1318. // http://man7.org/linux/man-pages/man3/keyctl_instantiate_iov.3.html
  1319. func KeyctlInstantiateIOV(id int, payload []Iovec, ringid int) error {
  1320. return keyctlIOV(KEYCTL_INSTANTIATE_IOV, id, payload, ringid)
  1321. }
  1322. //sys keyctlDH(cmd int, arg2 *KeyctlDHParams, buf []byte) (ret int, err error) = SYS_KEYCTL
  1323. // KeyctlDHCompute implements the KEYCTL_DH_COMPUTE command. This command
  1324. // computes a Diffie-Hellman shared secret based on the provide params. The
  1325. // secret is written to the provided buffer and the returned size is the number
  1326. // of bytes written (returning an error if there is insufficient space in the
  1327. // buffer). If a nil buffer is passed in, this function returns the minimum
  1328. // buffer length needed to store the appropriate data. Note that this differs
  1329. // from KEYCTL_READ's behavior which always returns the requested payload size.
  1330. // See the full documentation at:
  1331. // http://man7.org/linux/man-pages/man3/keyctl_dh_compute.3.html
  1332. func KeyctlDHCompute(params *KeyctlDHParams, buffer []byte) (size int, err error) {
  1333. return keyctlDH(KEYCTL_DH_COMPUTE, params, buffer)
  1334. }
  1335. // KeyctlRestrictKeyring implements the KEYCTL_RESTRICT_KEYRING command. This
  1336. // command limits the set of keys that can be linked to the keyring, regardless
  1337. // of keyring permissions. The command requires the "setattr" permission.
  1338. //
  1339. // When called with an empty keyType the command locks the keyring, preventing
  1340. // any further keys from being linked to the keyring.
  1341. //
  1342. // The "asymmetric" keyType defines restrictions requiring key payloads to be
  1343. // DER encoded X.509 certificates signed by keys in another keyring. Restrictions
  1344. // for "asymmetric" include "builtin_trusted", "builtin_and_secondary_trusted",
  1345. // "key_or_keyring:<key>", and "key_or_keyring:<key>:chain".
  1346. //
  1347. // As of Linux 4.12, only the "asymmetric" keyType defines type-specific
  1348. // restrictions.
  1349. //
  1350. // See the full documentation at:
  1351. // http://man7.org/linux/man-pages/man3/keyctl_restrict_keyring.3.html
  1352. // http://man7.org/linux/man-pages/man2/keyctl.2.html
  1353. func KeyctlRestrictKeyring(ringid int, keyType string, restriction string) error {
  1354. if keyType == "" {
  1355. return keyctlRestrictKeyring(KEYCTL_RESTRICT_KEYRING, ringid)
  1356. }
  1357. return keyctlRestrictKeyringByType(KEYCTL_RESTRICT_KEYRING, ringid, keyType, restriction)
  1358. }
  1359. //sys keyctlRestrictKeyringByType(cmd int, arg2 int, keyType string, restriction string) (err error) = SYS_KEYCTL
  1360. //sys keyctlRestrictKeyring(cmd int, arg2 int) (err error) = SYS_KEYCTL
  1361. func recvmsgRaw(fd int, iov []Iovec, oob []byte, flags int, rsa *RawSockaddrAny) (n, oobn int, recvflags int, err error) {
  1362. var msg Msghdr
  1363. msg.Name = (*byte)(unsafe.Pointer(rsa))
  1364. msg.Namelen = uint32(SizeofSockaddrAny)
  1365. var dummy byte
  1366. if len(oob) > 0 {
  1367. if emptyIovecs(iov) {
  1368. var sockType int
  1369. sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
  1370. if err != nil {
  1371. return
  1372. }
  1373. // receive at least one normal byte
  1374. if sockType != SOCK_DGRAM {
  1375. var iova [1]Iovec
  1376. iova[0].Base = &dummy
  1377. iova[0].SetLen(1)
  1378. iov = iova[:]
  1379. }
  1380. }
  1381. msg.Control = &oob[0]
  1382. msg.SetControllen(len(oob))
  1383. }
  1384. if len(iov) > 0 {
  1385. msg.Iov = &iov[0]
  1386. msg.SetIovlen(len(iov))
  1387. }
  1388. if n, err = recvmsg(fd, &msg, flags); err != nil {
  1389. return
  1390. }
  1391. oobn = int(msg.Controllen)
  1392. recvflags = int(msg.Flags)
  1393. return
  1394. }
  1395. func sendmsgN(fd int, iov []Iovec, oob []byte, ptr unsafe.Pointer, salen _Socklen, flags int) (n int, err error) {
  1396. var msg Msghdr
  1397. msg.Name = (*byte)(ptr)
  1398. msg.Namelen = uint32(salen)
  1399. var dummy byte
  1400. var empty bool
  1401. if len(oob) > 0 {
  1402. empty = emptyIovecs(iov)
  1403. if empty {
  1404. var sockType int
  1405. sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE)
  1406. if err != nil {
  1407. return 0, err
  1408. }
  1409. // send at least one normal byte
  1410. if sockType != SOCK_DGRAM {
  1411. var iova [1]Iovec
  1412. iova[0].Base = &dummy
  1413. iova[0].SetLen(1)
  1414. iov = iova[:]
  1415. }
  1416. }
  1417. msg.Control = &oob[0]
  1418. msg.SetControllen(len(oob))
  1419. }
  1420. if len(iov) > 0 {
  1421. msg.Iov = &iov[0]
  1422. msg.SetIovlen(len(iov))
  1423. }
  1424. if n, err = sendmsg(fd, &msg, flags); err != nil {
  1425. return 0, err
  1426. }
  1427. if len(oob) > 0 && empty {
  1428. n = 0
  1429. }
  1430. return n, nil
  1431. }
  1432. // BindToDevice binds the socket associated with fd to device.
  1433. func BindToDevice(fd int, device string) (err error) {
  1434. return SetsockoptString(fd, SOL_SOCKET, SO_BINDTODEVICE, device)
  1435. }
  1436. //sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error)
  1437. //sys ptracePtr(request int, pid int, addr uintptr, data unsafe.Pointer) (err error) = SYS_PTRACE
  1438. func ptracePeek(req int, pid int, addr uintptr, out []byte) (count int, err error) {
  1439. // The peek requests are machine-size oriented, so we wrap it
  1440. // to retrieve arbitrary-length data.
  1441. // The ptrace syscall differs from glibc's ptrace.
  1442. // Peeks returns the word in *data, not as the return value.
  1443. var buf [SizeofPtr]byte
  1444. // Leading edge. PEEKTEXT/PEEKDATA don't require aligned
  1445. // access (PEEKUSER warns that it might), but if we don't
  1446. // align our reads, we might straddle an unmapped page
  1447. // boundary and not get the bytes leading up to the page
  1448. // boundary.
  1449. n := 0
  1450. if addr%SizeofPtr != 0 {
  1451. err = ptracePtr(req, pid, addr-addr%SizeofPtr, unsafe.Pointer(&buf[0]))
  1452. if err != nil {
  1453. return 0, err
  1454. }
  1455. n += copy(out, buf[addr%SizeofPtr:])
  1456. out = out[n:]
  1457. }
  1458. // Remainder.
  1459. for len(out) > 0 {
  1460. // We use an internal buffer to guarantee alignment.
  1461. // It's not documented if this is necessary, but we're paranoid.
  1462. err = ptracePtr(req, pid, addr+uintptr(n), unsafe.Pointer(&buf[0]))
  1463. if err != nil {
  1464. return n, err
  1465. }
  1466. copied := copy(out, buf[0:])
  1467. n += copied
  1468. out = out[copied:]
  1469. }
  1470. return n, nil
  1471. }
  1472. func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error) {
  1473. return ptracePeek(PTRACE_PEEKTEXT, pid, addr, out)
  1474. }
  1475. func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error) {
  1476. return ptracePeek(PTRACE_PEEKDATA, pid, addr, out)
  1477. }
  1478. func PtracePeekUser(pid int, addr uintptr, out []byte) (count int, err error) {
  1479. return ptracePeek(PTRACE_PEEKUSR, pid, addr, out)
  1480. }
  1481. func ptracePoke(pokeReq int, peekReq int, pid int, addr uintptr, data []byte) (count int, err error) {
  1482. // As for ptracePeek, we need to align our accesses to deal
  1483. // with the possibility of straddling an invalid page.
  1484. // Leading edge.
  1485. n := 0
  1486. if addr%SizeofPtr != 0 {
  1487. var buf [SizeofPtr]byte
  1488. err = ptracePtr(peekReq, pid, addr-addr%SizeofPtr, unsafe.Pointer(&buf[0]))
  1489. if err != nil {
  1490. return 0, err
  1491. }
  1492. n += copy(buf[addr%SizeofPtr:], data)
  1493. word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  1494. err = ptrace(pokeReq, pid, addr-addr%SizeofPtr, word)
  1495. if err != nil {
  1496. return 0, err
  1497. }
  1498. data = data[n:]
  1499. }
  1500. // Interior.
  1501. for len(data) > SizeofPtr {
  1502. word := *((*uintptr)(unsafe.Pointer(&data[0])))
  1503. err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  1504. if err != nil {
  1505. return n, err
  1506. }
  1507. n += SizeofPtr
  1508. data = data[SizeofPtr:]
  1509. }
  1510. // Trailing edge.
  1511. if len(data) > 0 {
  1512. var buf [SizeofPtr]byte
  1513. err = ptracePtr(peekReq, pid, addr+uintptr(n), unsafe.Pointer(&buf[0]))
  1514. if err != nil {
  1515. return n, err
  1516. }
  1517. copy(buf[0:], data)
  1518. word := *((*uintptr)(unsafe.Pointer(&buf[0])))
  1519. err = ptrace(pokeReq, pid, addr+uintptr(n), word)
  1520. if err != nil {
  1521. return n, err
  1522. }
  1523. n += len(data)
  1524. }
  1525. return n, nil
  1526. }
  1527. func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error) {
  1528. return ptracePoke(PTRACE_POKETEXT, PTRACE_PEEKTEXT, pid, addr, data)
  1529. }
  1530. func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error) {
  1531. return ptracePoke(PTRACE_POKEDATA, PTRACE_PEEKDATA, pid, addr, data)
  1532. }
  1533. func PtracePokeUser(pid int, addr uintptr, data []byte) (count int, err error) {
  1534. return ptracePoke(PTRACE_POKEUSR, PTRACE_PEEKUSR, pid, addr, data)
  1535. }
  1536. // elfNT_PRSTATUS is a copy of the debug/elf.NT_PRSTATUS constant so
  1537. // x/sys/unix doesn't need to depend on debug/elf and thus
  1538. // compress/zlib, debug/dwarf, and other packages.
  1539. const elfNT_PRSTATUS = 1
  1540. func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error) {
  1541. var iov Iovec
  1542. iov.Base = (*byte)(unsafe.Pointer(regsout))
  1543. iov.SetLen(int(unsafe.Sizeof(*regsout)))
  1544. return ptracePtr(PTRACE_GETREGSET, pid, uintptr(elfNT_PRSTATUS), unsafe.Pointer(&iov))
  1545. }
  1546. func PtraceSetRegs(pid int, regs *PtraceRegs) (err error) {
  1547. var iov Iovec
  1548. iov.Base = (*byte)(unsafe.Pointer(regs))
  1549. iov.SetLen(int(unsafe.Sizeof(*regs)))
  1550. return ptracePtr(PTRACE_SETREGSET, pid, uintptr(elfNT_PRSTATUS), unsafe.Pointer(&iov))
  1551. }
  1552. func PtraceSetOptions(pid int, options int) (err error) {
  1553. return ptrace(PTRACE_SETOPTIONS, pid, 0, uintptr(options))
  1554. }
  1555. func PtraceGetEventMsg(pid int) (msg uint, err error) {
  1556. var data _C_long
  1557. err = ptracePtr(PTRACE_GETEVENTMSG, pid, 0, unsafe.Pointer(&data))
  1558. msg = uint(data)
  1559. return
  1560. }
  1561. func PtraceCont(pid int, signal int) (err error) {
  1562. return ptrace(PTRACE_CONT, pid, 0, uintptr(signal))
  1563. }
  1564. func PtraceSyscall(pid int, signal int) (err error) {
  1565. return ptrace(PTRACE_SYSCALL, pid, 0, uintptr(signal))
  1566. }
  1567. func PtraceSingleStep(pid int) (err error) { return ptrace(PTRACE_SINGLESTEP, pid, 0, 0) }
  1568. func PtraceInterrupt(pid int) (err error) { return ptrace(PTRACE_INTERRUPT, pid, 0, 0) }
  1569. func PtraceAttach(pid int) (err error) { return ptrace(PTRACE_ATTACH, pid, 0, 0) }
  1570. func PtraceSeize(pid int) (err error) { return ptrace(PTRACE_SEIZE, pid, 0, 0) }
  1571. func PtraceDetach(pid int) (err error) { return ptrace(PTRACE_DETACH, pid, 0, 0) }
  1572. //sys reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error)
  1573. func Reboot(cmd int) (err error) {
  1574. return reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, "")
  1575. }
  1576. func direntIno(buf []byte) (uint64, bool) {
  1577. return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino))
  1578. }
  1579. func direntReclen(buf []byte) (uint64, bool) {
  1580. return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen))
  1581. }
  1582. func direntNamlen(buf []byte) (uint64, bool) {
  1583. reclen, ok := direntReclen(buf)
  1584. if !ok {
  1585. return 0, false
  1586. }
  1587. return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true
  1588. }
  1589. //sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error)
  1590. func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) {
  1591. // Certain file systems get rather angry and EINVAL if you give
  1592. // them an empty string of data, rather than NULL.
  1593. if data == "" {
  1594. return mount(source, target, fstype, flags, nil)
  1595. }
  1596. datap, err := BytePtrFromString(data)
  1597. if err != nil {
  1598. return err
  1599. }
  1600. return mount(source, target, fstype, flags, datap)
  1601. }
  1602. //sys mountSetattr(dirfd int, pathname string, flags uint, attr *MountAttr, size uintptr) (err error) = SYS_MOUNT_SETATTR
  1603. // MountSetattr is a wrapper for mount_setattr(2).
  1604. // https://man7.org/linux/man-pages/man2/mount_setattr.2.html
  1605. //
  1606. // Requires kernel >= 5.12.
  1607. func MountSetattr(dirfd int, pathname string, flags uint, attr *MountAttr) error {
  1608. return mountSetattr(dirfd, pathname, flags, attr, unsafe.Sizeof(*attr))
  1609. }
  1610. func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
  1611. if raceenabled {
  1612. raceReleaseMerge(unsafe.Pointer(&ioSync))
  1613. }
  1614. return sendfile(outfd, infd, offset, count)
  1615. }
  1616. // Sendto
  1617. // Recvfrom
  1618. // Socketpair
  1619. /*
  1620. * Direct access
  1621. */
  1622. //sys Acct(path string) (err error)
  1623. //sys AddKey(keyType string, description string, payload []byte, ringid int) (id int, err error)
  1624. //sys Adjtimex(buf *Timex) (state int, err error)
  1625. //sysnb Capget(hdr *CapUserHeader, data *CapUserData) (err error)
  1626. //sysnb Capset(hdr *CapUserHeader, data *CapUserData) (err error)
  1627. //sys Chdir(path string) (err error)
  1628. //sys Chroot(path string) (err error)
  1629. //sys ClockAdjtime(clockid int32, buf *Timex) (state int, err error)
  1630. //sys ClockGetres(clockid int32, res *Timespec) (err error)
  1631. //sys ClockGettime(clockid int32, time *Timespec) (err error)
  1632. //sys ClockSettime(clockid int32, time *Timespec) (err error)
  1633. //sys ClockNanosleep(clockid int32, flags int, request *Timespec, remain *Timespec) (err error)
  1634. //sys Close(fd int) (err error)
  1635. //sys CloseRange(first uint, last uint, flags uint) (err error)
  1636. //sys CopyFileRange(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error)
  1637. //sys DeleteModule(name string, flags int) (err error)
  1638. //sys Dup(oldfd int) (fd int, err error)
  1639. func Dup2(oldfd, newfd int) error {
  1640. return Dup3(oldfd, newfd, 0)
  1641. }
  1642. //sys Dup3(oldfd int, newfd int, flags int) (err error)
  1643. //sysnb EpollCreate1(flag int) (fd int, err error)
  1644. //sysnb EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
  1645. //sys Eventfd(initval uint, flags int) (fd int, err error) = SYS_EVENTFD2
  1646. //sys Exit(code int) = SYS_EXIT_GROUP
  1647. //sys Fallocate(fd int, mode uint32, off int64, len int64) (err error)
  1648. //sys Fchdir(fd int) (err error)
  1649. //sys Fchmod(fd int, mode uint32) (err error)
  1650. //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
  1651. //sys Fdatasync(fd int) (err error)
  1652. //sys Fgetxattr(fd int, attr string, dest []byte) (sz int, err error)
  1653. //sys FinitModule(fd int, params string, flags int) (err error)
  1654. //sys Flistxattr(fd int, dest []byte) (sz int, err error)
  1655. //sys Flock(fd int, how int) (err error)
  1656. //sys Fremovexattr(fd int, attr string) (err error)
  1657. //sys Fsetxattr(fd int, attr string, dest []byte, flags int) (err error)
  1658. //sys Fsync(fd int) (err error)
  1659. //sys Fsmount(fd int, flags int, mountAttrs int) (fsfd int, err error)
  1660. //sys Fsopen(fsName string, flags int) (fd int, err error)
  1661. //sys Fspick(dirfd int, pathName string, flags int) (fd int, err error)
  1662. //sys fsconfig(fd int, cmd uint, key *byte, value *byte, aux int) (err error)
  1663. func fsconfigCommon(fd int, cmd uint, key string, value *byte, aux int) (err error) {
  1664. var keyp *byte
  1665. if keyp, err = BytePtrFromString(key); err != nil {
  1666. return
  1667. }
  1668. return fsconfig(fd, cmd, keyp, value, aux)
  1669. }
  1670. // FsconfigSetFlag is equivalent to fsconfig(2) called
  1671. // with cmd == FSCONFIG_SET_FLAG.
  1672. //
  1673. // fd is the filesystem context to act upon.
  1674. // key the parameter key to set.
  1675. func FsconfigSetFlag(fd int, key string) (err error) {
  1676. return fsconfigCommon(fd, FSCONFIG_SET_FLAG, key, nil, 0)
  1677. }
  1678. // FsconfigSetString is equivalent to fsconfig(2) called
  1679. // with cmd == FSCONFIG_SET_STRING.
  1680. //
  1681. // fd is the filesystem context to act upon.
  1682. // key the parameter key to set.
  1683. // value is the parameter value to set.
  1684. func FsconfigSetString(fd int, key string, value string) (err error) {
  1685. var valuep *byte
  1686. if valuep, err = BytePtrFromString(value); err != nil {
  1687. return
  1688. }
  1689. return fsconfigCommon(fd, FSCONFIG_SET_STRING, key, valuep, 0)
  1690. }
  1691. // FsconfigSetBinary is equivalent to fsconfig(2) called
  1692. // with cmd == FSCONFIG_SET_BINARY.
  1693. //
  1694. // fd is the filesystem context to act upon.
  1695. // key the parameter key to set.
  1696. // value is the parameter value to set.
  1697. func FsconfigSetBinary(fd int, key string, value []byte) (err error) {
  1698. if len(value) == 0 {
  1699. return EINVAL
  1700. }
  1701. return fsconfigCommon(fd, FSCONFIG_SET_BINARY, key, &value[0], len(value))
  1702. }
  1703. // FsconfigSetPath is equivalent to fsconfig(2) called
  1704. // with cmd == FSCONFIG_SET_PATH.
  1705. //
  1706. // fd is the filesystem context to act upon.
  1707. // key the parameter key to set.
  1708. // path is a non-empty path for specified key.
  1709. // atfd is a file descriptor at which to start lookup from or AT_FDCWD.
  1710. func FsconfigSetPath(fd int, key string, path string, atfd int) (err error) {
  1711. var valuep *byte
  1712. if valuep, err = BytePtrFromString(path); err != nil {
  1713. return
  1714. }
  1715. return fsconfigCommon(fd, FSCONFIG_SET_PATH, key, valuep, atfd)
  1716. }
  1717. // FsconfigSetPathEmpty is equivalent to fsconfig(2) called
  1718. // with cmd == FSCONFIG_SET_PATH_EMPTY. The same as
  1719. // FconfigSetPath but with AT_PATH_EMPTY implied.
  1720. func FsconfigSetPathEmpty(fd int, key string, path string, atfd int) (err error) {
  1721. var valuep *byte
  1722. if valuep, err = BytePtrFromString(path); err != nil {
  1723. return
  1724. }
  1725. return fsconfigCommon(fd, FSCONFIG_SET_PATH_EMPTY, key, valuep, atfd)
  1726. }
  1727. // FsconfigSetFd is equivalent to fsconfig(2) called
  1728. // with cmd == FSCONFIG_SET_FD.
  1729. //
  1730. // fd is the filesystem context to act upon.
  1731. // key the parameter key to set.
  1732. // value is a file descriptor to be assigned to specified key.
  1733. func FsconfigSetFd(fd int, key string, value int) (err error) {
  1734. return fsconfigCommon(fd, FSCONFIG_SET_FD, key, nil, value)
  1735. }
  1736. // FsconfigCreate is equivalent to fsconfig(2) called
  1737. // with cmd == FSCONFIG_CMD_CREATE.
  1738. //
  1739. // fd is the filesystem context to act upon.
  1740. func FsconfigCreate(fd int) (err error) {
  1741. return fsconfig(fd, FSCONFIG_CMD_CREATE, nil, nil, 0)
  1742. }
  1743. // FsconfigReconfigure is equivalent to fsconfig(2) called
  1744. // with cmd == FSCONFIG_CMD_RECONFIGURE.
  1745. //
  1746. // fd is the filesystem context to act upon.
  1747. func FsconfigReconfigure(fd int) (err error) {
  1748. return fsconfig(fd, FSCONFIG_CMD_RECONFIGURE, nil, nil, 0)
  1749. }
  1750. //sys Getdents(fd int, buf []byte) (n int, err error) = SYS_GETDENTS64
  1751. //sysnb Getpgid(pid int) (pgid int, err error)
  1752. func Getpgrp() (pid int) {
  1753. pid, _ = Getpgid(0)
  1754. return
  1755. }
  1756. //sysnb Getpid() (pid int)
  1757. //sysnb Getppid() (ppid int)
  1758. //sys Getpriority(which int, who int) (prio int, err error)
  1759. func Getrandom(buf []byte, flags int) (n int, err error) {
  1760. vdsoRet, supported := vgetrandom(buf, uint32(flags))
  1761. if supported {
  1762. if vdsoRet < 0 {
  1763. return 0, errnoErr(syscall.Errno(-vdsoRet))
  1764. }
  1765. return vdsoRet, nil
  1766. }
  1767. var p *byte
  1768. if len(buf) > 0 {
  1769. p = &buf[0]
  1770. }
  1771. r, _, e := Syscall(SYS_GETRANDOM, uintptr(unsafe.Pointer(p)), uintptr(len(buf)), uintptr(flags))
  1772. if e != 0 {
  1773. return 0, errnoErr(e)
  1774. }
  1775. return int(r), nil
  1776. }
  1777. //sysnb Getrusage(who int, rusage *Rusage) (err error)
  1778. //sysnb Getsid(pid int) (sid int, err error)
  1779. //sysnb Gettid() (tid int)
  1780. //sys Getxattr(path string, attr string, dest []byte) (sz int, err error)
  1781. //sys InitModule(moduleImage []byte, params string) (err error)
  1782. //sys InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
  1783. //sysnb InotifyInit1(flags int) (fd int, err error)
  1784. //sysnb InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
  1785. //sysnb Kill(pid int, sig syscall.Signal) (err error)
  1786. //sys Klogctl(typ int, buf []byte) (n int, err error) = SYS_SYSLOG
  1787. //sys Lgetxattr(path string, attr string, dest []byte) (sz int, err error)
  1788. //sys Listxattr(path string, dest []byte) (sz int, err error)
  1789. //sys Llistxattr(path string, dest []byte) (sz int, err error)
  1790. //sys Lremovexattr(path string, attr string) (err error)
  1791. //sys Lsetxattr(path string, attr string, data []byte, flags int) (err error)
  1792. //sys MemfdCreate(name string, flags int) (fd int, err error)
  1793. //sys Mkdirat(dirfd int, path string, mode uint32) (err error)
  1794. //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
  1795. //sys MoveMount(fromDirfd int, fromPathName string, toDirfd int, toPathName string, flags int) (err error)
  1796. //sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
  1797. //sys OpenTree(dfd int, fileName string, flags uint) (r int, err error)
  1798. //sys PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error)
  1799. //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT
  1800. //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error)
  1801. //sys pselect6(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *sigset_argpack) (n int, err error)
  1802. //sys read(fd int, p []byte) (n int, err error)
  1803. //sys Removexattr(path string, attr string) (err error)
  1804. //sys Renameat2(olddirfd int, oldpath string, newdirfd int, newpath string, flags uint) (err error)
  1805. //sys RequestKey(keyType string, description string, callback string, destRingid int) (id int, err error)
  1806. //sys Setdomainname(p []byte) (err error)
  1807. //sys Sethostname(p []byte) (err error)
  1808. //sysnb Setpgid(pid int, pgid int) (err error)
  1809. //sysnb Setsid() (pid int, err error)
  1810. //sysnb Settimeofday(tv *Timeval) (err error)
  1811. //sys Setns(fd int, nstype int) (err error)
  1812. //go:linkname syscall_prlimit syscall.prlimit
  1813. func syscall_prlimit(pid, resource int, newlimit, old *syscall.Rlimit) error
  1814. func Prlimit(pid, resource int, newlimit, old *Rlimit) error {
  1815. // Just call the syscall version, because as of Go 1.21
  1816. // it will affect starting a new process.
  1817. return syscall_prlimit(pid, resource, (*syscall.Rlimit)(newlimit), (*syscall.Rlimit)(old))
  1818. }
  1819. // PrctlRetInt performs a prctl operation specified by option and further
  1820. // optional arguments arg2 through arg5 depending on option. It returns a
  1821. // non-negative integer that is returned by the prctl syscall.
  1822. func PrctlRetInt(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (int, error) {
  1823. ret, _, err := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0)
  1824. if err != 0 {
  1825. return 0, err
  1826. }
  1827. return int(ret), nil
  1828. }
  1829. func Setuid(uid int) (err error) {
  1830. return syscall.Setuid(uid)
  1831. }
  1832. func Setgid(gid int) (err error) {
  1833. return syscall.Setgid(gid)
  1834. }
  1835. func Setreuid(ruid, euid int) (err error) {
  1836. return syscall.Setreuid(ruid, euid)
  1837. }
  1838. func Setregid(rgid, egid int) (err error) {
  1839. return syscall.Setregid(rgid, egid)
  1840. }
  1841. func Setresuid(ruid, euid, suid int) (err error) {
  1842. return syscall.Setresuid(ruid, euid, suid)
  1843. }
  1844. func Setresgid(rgid, egid, sgid int) (err error) {
  1845. return syscall.Setresgid(rgid, egid, sgid)
  1846. }
  1847. // SetfsgidRetGid sets fsgid for current thread and returns previous fsgid set.
  1848. // setfsgid(2) will return a non-nil error only if its caller lacks CAP_SETUID capability.
  1849. // If the call fails due to other reasons, current fsgid will be returned.
  1850. func SetfsgidRetGid(gid int) (int, error) {
  1851. return setfsgid(gid)
  1852. }
  1853. // SetfsuidRetUid sets fsuid for current thread and returns previous fsuid set.
  1854. // setfsgid(2) will return a non-nil error only if its caller lacks CAP_SETUID capability
  1855. // If the call fails due to other reasons, current fsuid will be returned.
  1856. func SetfsuidRetUid(uid int) (int, error) {
  1857. return setfsuid(uid)
  1858. }
  1859. func Setfsgid(gid int) error {
  1860. _, err := setfsgid(gid)
  1861. return err
  1862. }
  1863. func Setfsuid(uid int) error {
  1864. _, err := setfsuid(uid)
  1865. return err
  1866. }
  1867. func Signalfd(fd int, sigmask *Sigset_t, flags int) (newfd int, err error) {
  1868. return signalfd(fd, sigmask, _C__NSIG/8, flags)
  1869. }
  1870. //sys Setpriority(which int, who int, prio int) (err error)
  1871. //sys Setxattr(path string, attr string, data []byte, flags int) (err error)
  1872. //sys signalfd(fd int, sigmask *Sigset_t, maskSize uintptr, flags int) (newfd int, err error) = SYS_SIGNALFD4
  1873. //sys Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error)
  1874. //sys Sync()
  1875. //sys Syncfs(fd int) (err error)
  1876. //sysnb Sysinfo(info *Sysinfo_t) (err error)
  1877. //sys Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
  1878. //sysnb TimerfdCreate(clockid int, flags int) (fd int, err error)
  1879. //sysnb TimerfdGettime(fd int, currValue *ItimerSpec) (err error)
  1880. //sysnb TimerfdSettime(fd int, flags int, newValue *ItimerSpec, oldValue *ItimerSpec) (err error)
  1881. //sysnb Tgkill(tgid int, tid int, sig syscall.Signal) (err error)
  1882. //sysnb Times(tms *Tms) (ticks uintptr, err error)
  1883. //sysnb Umask(mask int) (oldmask int)
  1884. //sysnb Uname(buf *Utsname) (err error)
  1885. //sys Unmount(target string, flags int) (err error) = SYS_UMOUNT2
  1886. //sys Unshare(flags int) (err error)
  1887. //sys write(fd int, p []byte) (n int, err error)
  1888. //sys exitThread(code int) (err error) = SYS_EXIT
  1889. //sys readv(fd int, iovs []Iovec) (n int, err error) = SYS_READV
  1890. //sys writev(fd int, iovs []Iovec) (n int, err error) = SYS_WRITEV
  1891. //sys preadv(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) = SYS_PREADV
  1892. //sys pwritev(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) = SYS_PWRITEV
  1893. //sys preadv2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) = SYS_PREADV2
  1894. //sys pwritev2(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr, flags int) (n int, err error) = SYS_PWRITEV2
  1895. // minIovec is the size of the small initial allocation used by
  1896. // Readv, Writev, etc.
  1897. //
  1898. // This small allocation gets stack allocated, which lets the
  1899. // common use case of len(iovs) <= minIovs avoid more expensive
  1900. // heap allocations.
  1901. const minIovec = 8
  1902. // appendBytes converts bs to Iovecs and appends them to vecs.
  1903. func appendBytes(vecs []Iovec, bs [][]byte) []Iovec {
  1904. for _, b := range bs {
  1905. var v Iovec
  1906. v.SetLen(len(b))
  1907. if len(b) > 0 {
  1908. v.Base = &b[0]
  1909. } else {
  1910. v.Base = (*byte)(unsafe.Pointer(&_zero))
  1911. }
  1912. vecs = append(vecs, v)
  1913. }
  1914. return vecs
  1915. }
  1916. // offs2lohi splits offs into its low and high order bits.
  1917. func offs2lohi(offs int64) (lo, hi uintptr) {
  1918. const longBits = SizeofLong * 8
  1919. return uintptr(offs), uintptr(uint64(offs) >> (longBits - 1) >> 1) // two shifts to avoid false positive in vet
  1920. }
  1921. func Readv(fd int, iovs [][]byte) (n int, err error) {
  1922. iovecs := make([]Iovec, 0, minIovec)
  1923. iovecs = appendBytes(iovecs, iovs)
  1924. n, err = readv(fd, iovecs)
  1925. readvRacedetect(iovecs, n, err)
  1926. return n, err
  1927. }
  1928. func Preadv(fd int, iovs [][]byte, offset int64) (n int, err error) {
  1929. iovecs := make([]Iovec, 0, minIovec)
  1930. iovecs = appendBytes(iovecs, iovs)
  1931. lo, hi := offs2lohi(offset)
  1932. n, err = preadv(fd, iovecs, lo, hi)
  1933. readvRacedetect(iovecs, n, err)
  1934. return n, err
  1935. }
  1936. func Preadv2(fd int, iovs [][]byte, offset int64, flags int) (n int, err error) {
  1937. iovecs := make([]Iovec, 0, minIovec)
  1938. iovecs = appendBytes(iovecs, iovs)
  1939. lo, hi := offs2lohi(offset)
  1940. n, err = preadv2(fd, iovecs, lo, hi, flags)
  1941. readvRacedetect(iovecs, n, err)
  1942. return n, err
  1943. }
  1944. func readvRacedetect(iovecs []Iovec, n int, err error) {
  1945. if !raceenabled {
  1946. return
  1947. }
  1948. for i := 0; n > 0 && i < len(iovecs); i++ {
  1949. m := min(int(iovecs[i].Len), n)
  1950. n -= m
  1951. if m > 0 {
  1952. raceWriteRange(unsafe.Pointer(iovecs[i].Base), m)
  1953. }
  1954. }
  1955. if err == nil {
  1956. raceAcquire(unsafe.Pointer(&ioSync))
  1957. }
  1958. }
  1959. func Writev(fd int, iovs [][]byte) (n int, err error) {
  1960. iovecs := make([]Iovec, 0, minIovec)
  1961. iovecs = appendBytes(iovecs, iovs)
  1962. if raceenabled {
  1963. raceReleaseMerge(unsafe.Pointer(&ioSync))
  1964. }
  1965. n, err = writev(fd, iovecs)
  1966. writevRacedetect(iovecs, n)
  1967. return n, err
  1968. }
  1969. func Pwritev(fd int, iovs [][]byte, offset int64) (n int, err error) {
  1970. iovecs := make([]Iovec, 0, minIovec)
  1971. iovecs = appendBytes(iovecs, iovs)
  1972. if raceenabled {
  1973. raceReleaseMerge(unsafe.Pointer(&ioSync))
  1974. }
  1975. lo, hi := offs2lohi(offset)
  1976. n, err = pwritev(fd, iovecs, lo, hi)
  1977. writevRacedetect(iovecs, n)
  1978. return n, err
  1979. }
  1980. func Pwritev2(fd int, iovs [][]byte, offset int64, flags int) (n int, err error) {
  1981. iovecs := make([]Iovec, 0, minIovec)
  1982. iovecs = appendBytes(iovecs, iovs)
  1983. if raceenabled {
  1984. raceReleaseMerge(unsafe.Pointer(&ioSync))
  1985. }
  1986. lo, hi := offs2lohi(offset)
  1987. n, err = pwritev2(fd, iovecs, lo, hi, flags)
  1988. writevRacedetect(iovecs, n)
  1989. return n, err
  1990. }
  1991. func writevRacedetect(iovecs []Iovec, n int) {
  1992. if !raceenabled {
  1993. return
  1994. }
  1995. for i := 0; n > 0 && i < len(iovecs); i++ {
  1996. m := min(int(iovecs[i].Len), n)
  1997. n -= m
  1998. if m > 0 {
  1999. raceReadRange(unsafe.Pointer(iovecs[i].Base), m)
  2000. }
  2001. }
  2002. }
  2003. // mmap varies by architecture; see syscall_linux_*.go.
  2004. //sys munmap(addr uintptr, length uintptr) (err error)
  2005. //sys mremap(oldaddr uintptr, oldlength uintptr, newlength uintptr, flags int, newaddr uintptr) (xaddr uintptr, err error)
  2006. //sys Madvise(b []byte, advice int) (err error)
  2007. //sys Mprotect(b []byte, prot int) (err error)
  2008. //sys Mlock(b []byte) (err error)
  2009. //sys Mlockall(flags int) (err error)
  2010. //sys Msync(b []byte, flags int) (err error)
  2011. //sys Munlock(b []byte) (err error)
  2012. //sys Munlockall() (err error)
  2013. const (
  2014. mremapFixed = MREMAP_FIXED
  2015. mremapDontunmap = MREMAP_DONTUNMAP
  2016. mremapMaymove = MREMAP_MAYMOVE
  2017. )
  2018. // Vmsplice splices user pages from a slice of Iovecs into a pipe specified by fd,
  2019. // using the specified flags.
  2020. func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) {
  2021. var p unsafe.Pointer
  2022. if len(iovs) > 0 {
  2023. p = unsafe.Pointer(&iovs[0])
  2024. }
  2025. n, _, errno := Syscall6(SYS_VMSPLICE, uintptr(fd), uintptr(p), uintptr(len(iovs)), uintptr(flags), 0, 0)
  2026. if errno != 0 {
  2027. return 0, syscall.Errno(errno)
  2028. }
  2029. return int(n), nil
  2030. }
  2031. func isGroupMember(gid int) bool {
  2032. groups, err := Getgroups()
  2033. if err != nil {
  2034. return false
  2035. }
  2036. return slices.Contains(groups, gid)
  2037. }
  2038. func isCapDacOverrideSet() bool {
  2039. hdr := CapUserHeader{Version: LINUX_CAPABILITY_VERSION_3}
  2040. data := [2]CapUserData{}
  2041. err := Capget(&hdr, &data[0])
  2042. return err == nil && data[0].Effective&(1<<CAP_DAC_OVERRIDE) != 0
  2043. }
  2044. //sys faccessat(dirfd int, path string, mode uint32) (err error)
  2045. //sys Faccessat2(dirfd int, path string, mode uint32, flags int) (err error)
  2046. func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) {
  2047. if flags == 0 {
  2048. return faccessat(dirfd, path, mode)
  2049. }
  2050. if err := Faccessat2(dirfd, path, mode, flags); err != ENOSYS && err != EPERM {
  2051. return err
  2052. }
  2053. // The Linux kernel faccessat system call does not take any flags.
  2054. // The glibc faccessat implements the flags itself; see
  2055. // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/unix/sysv/linux/faccessat.c;hb=HEAD
  2056. // Because people naturally expect syscall.Faccessat to act
  2057. // like C faccessat, we do the same.
  2058. if flags & ^(AT_SYMLINK_NOFOLLOW|AT_EACCESS) != 0 {
  2059. return EINVAL
  2060. }
  2061. var st Stat_t
  2062. if err := Fstatat(dirfd, path, &st, flags&AT_SYMLINK_NOFOLLOW); err != nil {
  2063. return err
  2064. }
  2065. mode &= 7
  2066. if mode == 0 {
  2067. return nil
  2068. }
  2069. var uid int
  2070. if flags&AT_EACCESS != 0 {
  2071. uid = Geteuid()
  2072. if uid != 0 && isCapDacOverrideSet() {
  2073. // If CAP_DAC_OVERRIDE is set, file access check is
  2074. // done by the kernel in the same way as for root
  2075. // (see generic_permission() in the Linux sources).
  2076. uid = 0
  2077. }
  2078. } else {
  2079. uid = Getuid()
  2080. }
  2081. if uid == 0 {
  2082. if mode&1 == 0 {
  2083. // Root can read and write any file.
  2084. return nil
  2085. }
  2086. if st.Mode&0111 != 0 {
  2087. // Root can execute any file that anybody can execute.
  2088. return nil
  2089. }
  2090. return EACCES
  2091. }
  2092. var fmode uint32
  2093. if uint32(uid) == st.Uid {
  2094. fmode = (st.Mode >> 6) & 7
  2095. } else {
  2096. var gid int
  2097. if flags&AT_EACCESS != 0 {
  2098. gid = Getegid()
  2099. } else {
  2100. gid = Getgid()
  2101. }
  2102. if uint32(gid) == st.Gid || isGroupMember(int(st.Gid)) {
  2103. fmode = (st.Mode >> 3) & 7
  2104. } else {
  2105. fmode = st.Mode & 7
  2106. }
  2107. }
  2108. if fmode&mode == mode {
  2109. return nil
  2110. }
  2111. return EACCES
  2112. }
  2113. //sys nameToHandleAt(dirFD int, pathname string, fh *fileHandle, mountID *_C_int, flags int) (err error) = SYS_NAME_TO_HANDLE_AT
  2114. //sys openByHandleAt(mountFD int, fh *fileHandle, flags int) (fd int, err error) = SYS_OPEN_BY_HANDLE_AT
  2115. // fileHandle is the argument to nameToHandleAt and openByHandleAt. We
  2116. // originally tried to generate it via unix/linux/types.go with "type
  2117. // fileHandle C.struct_file_handle" but that generated empty structs
  2118. // for mips64 and mips64le. Instead, hard code it for now (it's the
  2119. // same everywhere else) until the mips64 generator issue is fixed.
  2120. type fileHandle struct {
  2121. Bytes uint32
  2122. Type int32
  2123. }
  2124. // FileHandle represents the C struct file_handle used by
  2125. // name_to_handle_at (see NameToHandleAt) and open_by_handle_at (see
  2126. // OpenByHandleAt).
  2127. type FileHandle struct {
  2128. *fileHandle
  2129. }
  2130. // NewFileHandle constructs a FileHandle.
  2131. func NewFileHandle(handleType int32, handle []byte) FileHandle {
  2132. const hdrSize = unsafe.Sizeof(fileHandle{})
  2133. buf := make([]byte, hdrSize+uintptr(len(handle)))
  2134. copy(buf[hdrSize:], handle)
  2135. fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
  2136. fh.Type = handleType
  2137. fh.Bytes = uint32(len(handle))
  2138. return FileHandle{fh}
  2139. }
  2140. func (fh *FileHandle) Size() int { return int(fh.fileHandle.Bytes) }
  2141. func (fh *FileHandle) Type() int32 { return fh.fileHandle.Type }
  2142. func (fh *FileHandle) Bytes() []byte {
  2143. n := fh.Size()
  2144. if n == 0 {
  2145. return nil
  2146. }
  2147. return unsafe.Slice((*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(&fh.fileHandle.Type))+4)), n)
  2148. }
  2149. // NameToHandleAt wraps the name_to_handle_at system call; it obtains
  2150. // a handle for a path name.
  2151. func NameToHandleAt(dirfd int, path string, flags int) (handle FileHandle, mountID int, err error) {
  2152. var mid _C_int
  2153. // Try first with a small buffer, assuming the handle will
  2154. // only be 32 bytes.
  2155. size := uint32(32 + unsafe.Sizeof(fileHandle{}))
  2156. didResize := false
  2157. for {
  2158. buf := make([]byte, size)
  2159. fh := (*fileHandle)(unsafe.Pointer(&buf[0]))
  2160. fh.Bytes = size - uint32(unsafe.Sizeof(fileHandle{}))
  2161. err = nameToHandleAt(dirfd, path, fh, &mid, flags)
  2162. if err == EOVERFLOW {
  2163. if didResize {
  2164. // We shouldn't need to resize more than once
  2165. return
  2166. }
  2167. didResize = true
  2168. size = fh.Bytes + uint32(unsafe.Sizeof(fileHandle{}))
  2169. continue
  2170. }
  2171. if err != nil {
  2172. return
  2173. }
  2174. return FileHandle{fh}, int(mid), nil
  2175. }
  2176. }
  2177. // OpenByHandleAt wraps the open_by_handle_at system call; it opens a
  2178. // file via a handle as previously returned by NameToHandleAt.
  2179. func OpenByHandleAt(mountFD int, handle FileHandle, flags int) (fd int, err error) {
  2180. return openByHandleAt(mountFD, handle.fileHandle, flags)
  2181. }
  2182. // Klogset wraps the sys_syslog system call; it sets console_loglevel to
  2183. // the value specified by arg and passes a dummy pointer to bufp.
  2184. func Klogset(typ int, arg int) (err error) {
  2185. var p unsafe.Pointer
  2186. _, _, errno := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(p), uintptr(arg))
  2187. if errno != 0 {
  2188. return errnoErr(errno)
  2189. }
  2190. return nil
  2191. }
  2192. // RemoteIovec is Iovec with the pointer replaced with an integer.
  2193. // It is used for ProcessVMReadv and ProcessVMWritev, where the pointer
  2194. // refers to a location in a different process' address space, which
  2195. // would confuse the Go garbage collector.
  2196. type RemoteIovec struct {
  2197. Base uintptr
  2198. Len int
  2199. }
  2200. //sys ProcessVMReadv(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) = SYS_PROCESS_VM_READV
  2201. //sys ProcessVMWritev(pid int, localIov []Iovec, remoteIov []RemoteIovec, flags uint) (n int, err error) = SYS_PROCESS_VM_WRITEV
  2202. //sys PidfdOpen(pid int, flags int) (fd int, err error) = SYS_PIDFD_OPEN
  2203. //sys PidfdGetfd(pidfd int, targetfd int, flags int) (fd int, err error) = SYS_PIDFD_GETFD
  2204. //sys PidfdSendSignal(pidfd int, sig Signal, info *Siginfo, flags int) (err error) = SYS_PIDFD_SEND_SIGNAL
  2205. //sys shmat(id int, addr uintptr, flag int) (ret uintptr, err error)
  2206. //sys shmctl(id int, cmd int, buf *SysvShmDesc) (result int, err error)
  2207. //sys shmdt(addr uintptr) (err error)
  2208. //sys shmget(key int, size int, flag int) (id int, err error)
  2209. //sys getitimer(which int, currValue *Itimerval) (err error)
  2210. //sys setitimer(which int, newValue *Itimerval, oldValue *Itimerval) (err error)
  2211. // MakeItimerval creates an Itimerval from interval and value durations.
  2212. func MakeItimerval(interval, value time.Duration) Itimerval {
  2213. return Itimerval{
  2214. Interval: NsecToTimeval(interval.Nanoseconds()),
  2215. Value: NsecToTimeval(value.Nanoseconds()),
  2216. }
  2217. }
  2218. // A value which may be passed to the which parameter for Getitimer and
  2219. // Setitimer.
  2220. type ItimerWhich int
  2221. // Possible which values for Getitimer and Setitimer.
  2222. const (
  2223. ItimerReal ItimerWhich = ITIMER_REAL
  2224. ItimerVirtual ItimerWhich = ITIMER_VIRTUAL
  2225. ItimerProf ItimerWhich = ITIMER_PROF
  2226. )
  2227. // Getitimer wraps getitimer(2) to return the current value of the timer
  2228. // specified by which.
  2229. func Getitimer(which ItimerWhich) (Itimerval, error) {
  2230. var it Itimerval
  2231. if err := getitimer(int(which), &it); err != nil {
  2232. return Itimerval{}, err
  2233. }
  2234. return it, nil
  2235. }
  2236. // Setitimer wraps setitimer(2) to arm or disarm the timer specified by which.
  2237. // It returns the previous value of the timer.
  2238. //
  2239. // If the Itimerval argument is the zero value, the timer will be disarmed.
  2240. func Setitimer(which ItimerWhich, it Itimerval) (Itimerval, error) {
  2241. var prev Itimerval
  2242. if err := setitimer(int(which), &it, &prev); err != nil {
  2243. return Itimerval{}, err
  2244. }
  2245. return prev, nil
  2246. }
  2247. //sysnb rtSigprocmask(how int, set *Sigset_t, oldset *Sigset_t, sigsetsize uintptr) (err error) = SYS_RT_SIGPROCMASK
  2248. func PthreadSigmask(how int, set, oldset *Sigset_t) error {
  2249. if oldset != nil {
  2250. // Explicitly clear in case Sigset_t is larger than _C__NSIG.
  2251. *oldset = Sigset_t{}
  2252. }
  2253. return rtSigprocmask(how, set, oldset, _C__NSIG/8)
  2254. }
  2255. //sysnb getresuid(ruid *_C_int, euid *_C_int, suid *_C_int)
  2256. //sysnb getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int)
  2257. func Getresuid() (ruid, euid, suid int) {
  2258. var r, e, s _C_int
  2259. getresuid(&r, &e, &s)
  2260. return int(r), int(e), int(s)
  2261. }
  2262. func Getresgid() (rgid, egid, sgid int) {
  2263. var r, e, s _C_int
  2264. getresgid(&r, &e, &s)
  2265. return int(r), int(e), int(s)
  2266. }
  2267. // Pselect is a wrapper around the Linux pselect6 system call.
  2268. // This version does not modify the timeout argument.
  2269. func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {
  2270. // Per https://man7.org/linux/man-pages/man2/select.2.html#NOTES,
  2271. // The Linux pselect6() system call modifies its timeout argument.
  2272. // [Not modifying the argument] is the behavior required by POSIX.1-2001.
  2273. var mutableTimeout *Timespec
  2274. if timeout != nil {
  2275. mutableTimeout = new(Timespec)
  2276. *mutableTimeout = *timeout
  2277. }
  2278. // The final argument of the pselect6() system call is not a
  2279. // sigset_t * pointer, but is instead a structure
  2280. var kernelMask *sigset_argpack
  2281. if sigmask != nil {
  2282. wordBits := 32 << (^uintptr(0) >> 63) // see math.intSize
  2283. // A sigset stores one bit per signal,
  2284. // offset by 1 (because signal 0 does not exist).
  2285. // So the number of words needed is ⌈__C_NSIG - 1 / wordBits⌉.
  2286. sigsetWords := (_C__NSIG - 1 + wordBits - 1) / (wordBits)
  2287. sigsetBytes := uintptr(sigsetWords * (wordBits / 8))
  2288. kernelMask = &sigset_argpack{
  2289. ss: sigmask,
  2290. ssLen: sigsetBytes,
  2291. }
  2292. }
  2293. return pselect6(nfd, r, w, e, mutableTimeout, kernelMask)
  2294. }
  2295. //sys schedSetattr(pid int, attr *SchedAttr, flags uint) (err error)
  2296. //sys schedGetattr(pid int, attr *SchedAttr, size uint, flags uint) (err error)
  2297. // SchedSetAttr is a wrapper for sched_setattr(2) syscall.
  2298. // https://man7.org/linux/man-pages/man2/sched_setattr.2.html
  2299. func SchedSetAttr(pid int, attr *SchedAttr, flags uint) error {
  2300. if attr == nil {
  2301. return EINVAL
  2302. }
  2303. attr.Size = SizeofSchedAttr
  2304. return schedSetattr(pid, attr, flags)
  2305. }
  2306. // SchedGetAttr is a wrapper for sched_getattr(2) syscall.
  2307. // https://man7.org/linux/man-pages/man2/sched_getattr.2.html
  2308. func SchedGetAttr(pid int, flags uint) (*SchedAttr, error) {
  2309. attr := &SchedAttr{}
  2310. if err := schedGetattr(pid, attr, SizeofSchedAttr, flags); err != nil {
  2311. return nil, err
  2312. }
  2313. return attr, nil
  2314. }
  2315. //sys Cachestat(fd uint, crange *CachestatRange, cstat *Cachestat_t, flags uint) (err error)
  2316. //sys Mseal(b []byte, flags uint) (err error)
  2317. //sys setMemPolicy(mode int, mask unsafe.Pointer, size uintptr) (err error) = SYS_SET_MEMPOLICY
  2318. func SetMemPolicy(mode int, mask *CPUSet) error {
  2319. return setMemPolicy(mode, unsafe.Pointer(mask), _CPU_SETSIZE)
  2320. }
  2321. func SetMemPolicyDynamic(mode int, mask CPUSetDynamic) error {
  2322. return setMemPolicy(mode, mask.pointer(), mask.size())
  2323. }