syscall_linux.go 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651
  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 *CPUSet, size int) (err error) = SYS_SET_MEMPOLICY
  2318. func SetMemPolicy(mode int, mask *CPUSet) error {
  2319. return setMemPolicy(mode, mask, _CPU_SETSIZE)
  2320. }