]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Syscall.pm
e9175ceb9cfac0c3ce504be36962d7c7b9e51941
[public-inbox.git] / lib / PublicInbox / Syscall.pm
1 # This is a fork of the (for now) unmaintained Sys::Syscall 0.25,
2 # specifically the Debian libsys-syscall-perl 0.25-6 version to
3 # fix upstream regressions in 0.25.
4 #
5 # See devel/syscall-list in the public-inbox source tree for maintenance
6 # <https://80x24.org/public-inbox.git>
7 #
8 # This license differs from the rest of public-inbox
9 #
10 # This module is Copyright (c) 2005 Six Apart, Ltd.
11 # Copyright (C) all contributors <meta@public-inbox.org>
12 #
13 # All rights reserved.
14 #
15 # You may distribute under the terms of either the GNU General Public
16 # License or the Artistic License, as specified in the Perl README file.
17 package PublicInbox::Syscall;
18 use strict;
19 use v5.10.1;
20 use parent qw(Exporter);
21 use POSIX qw(ENOENT ENOSYS EINVAL O_NONBLOCK);
22 use Socket qw(SOL_SOCKET SCM_RIGHTS);
23 use Config;
24
25 # $VERSION = '0.25'; # Sys::Syscall version
26 our @EXPORT_OK = qw(epoll_ctl epoll_create epoll_wait
27                   EPOLLIN EPOLLOUT EPOLLET
28                   EPOLL_CTL_ADD EPOLL_CTL_DEL EPOLL_CTL_MOD
29                   EPOLLONESHOT EPOLLEXCLUSIVE
30                   signalfd rename_noreplace);
31 our %EXPORT_TAGS = (epoll => [qw(epoll_ctl epoll_create epoll_wait
32                              EPOLLIN EPOLLOUT
33                              EPOLL_CTL_ADD EPOLL_CTL_DEL EPOLL_CTL_MOD
34                              EPOLLONESHOT EPOLLEXCLUSIVE)],
35                 );
36
37 use constant {
38         EPOLLIN => 1,
39         EPOLLOUT => 4,
40         # EPOLLERR => 8,
41         # EPOLLHUP => 16,
42         # EPOLLRDBAND => 128,
43         EPOLLEXCLUSIVE => (1 << 28),
44         EPOLLONESHOT => (1 << 30),
45         EPOLLET => (1 << 31),
46         EPOLL_CTL_ADD => 1,
47         EPOLL_CTL_DEL => 2,
48         EPOLL_CTL_MOD => 3,
49         SIZEOF_int => $Config{intsize},
50         SIZEOF_size_t => $Config{sizesize},
51         NUL => "\0",
52 };
53
54 use constant {
55         TMPL_size_t => SIZEOF_size_t == 8 ? 'Q' : 'L',
56         BYTES_4_hole => SIZEOF_size_t == 8 ? 'L' : '',
57         # cmsg_len, cmsg_level, cmsg_type
58         SIZEOF_cmsghdr => SIZEOF_int * 2 + SIZEOF_size_t,
59 };
60
61 my @BYTES_4_hole = BYTES_4_hole ? (0) : ();
62 our $loaded_syscall = 0;
63
64 sub _load_syscall {
65     # props to Gaal for this!
66     return if $loaded_syscall++;
67     my $clean = sub {
68         delete @INC{qw<syscall.ph asm/unistd.ph bits/syscall.ph
69                         _h2ph_pre.ph sys/syscall.ph>};
70     };
71     $clean->(); # don't trust modules before us
72     my $rv = eval { require 'syscall.ph'; 1 } || eval { require 'sys/syscall.ph'; 1 };
73     $clean->(); # don't require modules after us trust us
74     $rv;
75 }
76
77
78 our (
79      $SYS_epoll_create,
80      $SYS_epoll_ctl,
81      $SYS_epoll_wait,
82      $SYS_signalfd4,
83      $SYS_renameat2,
84      );
85
86 my ($SYS_sendmsg, $SYS_recvmsg);
87 my $SYS_fstatfs; # don't need fstatfs64, just statfs.f_type
88 my ($FS_IOC_GETFLAGS, $FS_IOC_SETFLAGS);
89 my $SFD_CLOEXEC = 02000000; # Perl does not expose O_CLOEXEC
90 our $no_deprecated = 0;
91
92 if ($^O eq "linux") {
93     my (undef, undef, $release, undef, $machine) = POSIX::uname();
94     my ($maj, $min) = ($release =~ /\A([0-9]+)\.([0-9]+)/);
95     $SYS_renameat2 = 0 if "$maj.$min" < 3.15;
96     # whether the machine requires 64-bit numbers to be on 8-byte
97     # boundaries.
98     my $u64_mod_8 = 0;
99
100     # if we're running on an x86_64 kernel, but a 32-bit process,
101     # we need to use the x32 or i386 syscall numbers.
102     if ($machine eq "x86_64" && $Config{ptrsize} == 4) {
103         $machine = $Config{cppsymbols} =~ /\b__ILP32__=1\b/ ? 'x32' : 'i386';
104     }
105
106     # Similarly for mips64 vs mips
107     if ($machine eq "mips64" && $Config{ptrsize} == 4) {
108         $machine = "mips";
109     }
110
111     if ($machine =~ m/^i[3456]86$/) {
112         $SYS_epoll_create = 254;
113         $SYS_epoll_ctl    = 255;
114         $SYS_epoll_wait   = 256;
115         $SYS_signalfd4 = 327;
116         $SYS_renameat2 //= 353;
117         $SYS_fstatfs = 100;
118         $SYS_sendmsg = 370;
119         $SYS_recvmsg = 372;
120         $FS_IOC_GETFLAGS = 0x80046601;
121         $FS_IOC_SETFLAGS = 0x40046602;
122     } elsif ($machine eq "x86_64") {
123         $SYS_epoll_create = 213;
124         $SYS_epoll_ctl    = 233;
125         $SYS_epoll_wait   = 232;
126         $SYS_signalfd4 = 289;
127         $SYS_renameat2 //= 316;
128         $SYS_fstatfs = 138;
129         $SYS_sendmsg = 46;
130         $SYS_recvmsg = 47;
131         $FS_IOC_GETFLAGS = 0x80086601;
132         $FS_IOC_SETFLAGS = 0x40086602;
133     } elsif ($machine eq 'x32') {
134         $SYS_epoll_create = 1073742037;
135         $SYS_epoll_ctl = 1073742057;
136         $SYS_epoll_wait = 1073742056;
137         $SYS_signalfd4 = 1073742113;
138         $SYS_renameat2 //= 0x40000000 + 316;
139         $SYS_fstatfs = 138;
140         $SYS_sendmsg = 0x40000206;
141         $SYS_recvmsg = 0x40000207;
142         $FS_IOC_GETFLAGS = 0x80046601;
143         $FS_IOC_SETFLAGS = 0x40046602;
144     } elsif ($machine eq 'sparc64') {
145         $SYS_epoll_create = 193;
146         $SYS_epoll_ctl = 194;
147         $SYS_epoll_wait = 195;
148         $u64_mod_8 = 1;
149         $SYS_signalfd4 = 317;
150         $SYS_renameat2 //= 345;
151         $SFD_CLOEXEC = 020000000;
152         $SYS_fstatfs = 158;
153         $FS_IOC_GETFLAGS = 0x40086601;
154         $FS_IOC_SETFLAGS = 0x80086602;
155     } elsif ($machine =~ m/^parisc/) {
156         $SYS_epoll_create = 224;
157         $SYS_epoll_ctl    = 225;
158         $SYS_epoll_wait   = 226;
159         $u64_mod_8        = 1;
160         $SYS_signalfd4 = 309;
161     } elsif ($machine =~ m/^ppc64/) {
162         $SYS_epoll_create = 236;
163         $SYS_epoll_ctl    = 237;
164         $SYS_epoll_wait   = 238;
165         $u64_mod_8        = 1;
166         $SYS_signalfd4 = 313;
167         $SYS_renameat2 //= 357;
168         $SYS_fstatfs = 100;
169         $FS_IOC_GETFLAGS = 0x40086601;
170         $FS_IOC_SETFLAGS = 0x80086602;
171     } elsif ($machine eq "ppc") {
172         $SYS_epoll_create = 236;
173         $SYS_epoll_ctl    = 237;
174         $SYS_epoll_wait   = 238;
175         $u64_mod_8        = 1;
176         $SYS_signalfd4 = 313;
177         $SYS_renameat2 //= 357;
178         $SYS_fstatfs = 100;
179         $FS_IOC_GETFLAGS = 0x40086601;
180         $FS_IOC_SETFLAGS = 0x80086602;
181     } elsif ($machine =~ m/^s390/) {
182         $SYS_epoll_create = 249;
183         $SYS_epoll_ctl    = 250;
184         $SYS_epoll_wait   = 251;
185         $u64_mod_8        = 1;
186         $SYS_signalfd4 = 322;
187         $SYS_renameat2 //= 347;
188         $SYS_fstatfs = 100;
189     } elsif ($machine eq "ia64") {
190         $SYS_epoll_create = 1243;
191         $SYS_epoll_ctl    = 1244;
192         $SYS_epoll_wait   = 1245;
193         $u64_mod_8        = 1;
194         $SYS_signalfd4 = 289;
195     } elsif ($machine eq "alpha") {
196         # natural alignment, ints are 32-bits
197         $SYS_epoll_create = 407;
198         $SYS_epoll_ctl    = 408;
199         $SYS_epoll_wait   = 409;
200         $u64_mod_8        = 1;
201         $SYS_signalfd4 = 484;
202         $SFD_CLOEXEC = 010000000;
203     } elsif ($machine eq "aarch64") {
204         $SYS_epoll_create = 20;  # (sys_epoll_create1)
205         $SYS_epoll_ctl    = 21;
206         $SYS_epoll_wait   = 22;  # (sys_epoll_pwait)
207         $u64_mod_8        = 1;
208         $no_deprecated    = 1;
209         $SYS_signalfd4 = 74;
210         $SYS_renameat2 //= 276;
211         $SYS_fstatfs = 44;
212         $FS_IOC_GETFLAGS = 0x80086601;
213         $FS_IOC_SETFLAGS = 0x40086602;
214     } elsif ($machine =~ m/arm(v\d+)?.*l/) {
215         # ARM OABI
216         $SYS_epoll_create = 250;
217         $SYS_epoll_ctl    = 251;
218         $SYS_epoll_wait   = 252;
219         $u64_mod_8        = 1;
220         $SYS_signalfd4 = 355;
221         $SYS_renameat2 //= 382;
222         $SYS_fstatfs = 100;
223     } elsif ($machine =~ m/^mips64/) {
224         $SYS_epoll_create = 5207;
225         $SYS_epoll_ctl    = 5208;
226         $SYS_epoll_wait   = 5209;
227         $u64_mod_8        = 1;
228         $SYS_signalfd4 = 5283;
229         $SYS_renameat2 //= 5311;
230         $SYS_fstatfs = 5135;
231         $FS_IOC_GETFLAGS = 0x40046601;
232         $FS_IOC_SETFLAGS = 0x80046602;
233     } elsif ($machine =~ m/^mips/) {
234         $SYS_epoll_create = 4248;
235         $SYS_epoll_ctl    = 4249;
236         $SYS_epoll_wait   = 4250;
237         $u64_mod_8        = 1;
238         $SYS_signalfd4 = 4324;
239         $SYS_renameat2 //= 4351;
240         $SYS_fstatfs = 4100;
241         $FS_IOC_GETFLAGS = 0x40046601;
242         $FS_IOC_SETFLAGS = 0x80046602;
243     } else {
244         # as a last resort, try using the *.ph files which may not
245         # exist or may be wrong
246         _load_syscall();
247         $SYS_epoll_create = eval { &SYS_epoll_create; } || 0;
248         $SYS_epoll_ctl    = eval { &SYS_epoll_ctl;    } || 0;
249         $SYS_epoll_wait   = eval { &SYS_epoll_wait;   } || 0;
250
251         # Note: do NOT add new syscalls to depend on *.ph, here.
252         # Better to miss syscalls (so we can fallback to IO::Poll)
253         # than to use wrong ones, since the names are not stable
254         # (at least not on FreeBSD), if the actual numbers are.
255     }
256
257     if ($u64_mod_8) {
258         *epoll_wait = \&epoll_wait_mod8;
259         *epoll_ctl = \&epoll_ctl_mod8;
260     } else {
261         *epoll_wait = \&epoll_wait_mod4;
262         *epoll_ctl = \&epoll_ctl_mod4;
263     }
264 }
265 # use Inline::C for *BSD-only or general POSIX stuff.
266 # Linux guarantees stable syscall numbering, BSDs only offer a stable libc
267 # use scripts/syscall-list on Linux to detect new syscall numbers
268
269 ############################################################################
270 # epoll functions
271 ############################################################################
272
273 sub epoll_defined { $SYS_epoll_create ? 1 : 0; }
274
275 sub epoll_create {
276         syscall($SYS_epoll_create, $no_deprecated ? 0 : 100);
277 }
278
279 # epoll_ctl wrapper
280 # ARGS: (epfd, op, fd, events_mask)
281 sub epoll_ctl_mod4 {
282     syscall($SYS_epoll_ctl, $_[0]+0, $_[1]+0, $_[2]+0, pack("LLL", $_[3], $_[2], 0));
283 }
284 sub epoll_ctl_mod8 {
285     syscall($SYS_epoll_ctl, $_[0]+0, $_[1]+0, $_[2]+0, pack("LLLL", $_[3], 0, $_[2], 0));
286 }
287
288 # epoll_wait wrapper
289 # ARGS: (epfd, maxevents, timeout (milliseconds), arrayref)
290 #  arrayref: values modified to be [$fd, $event]
291 our $epoll_wait_events = '';
292 our $epoll_wait_size = 0;
293 sub epoll_wait_mod4 {
294         my ($epfd, $maxevents, $timeout_msec, $events) = @_;
295         # resize our static buffer if maxevents bigger than we've ever done
296         if ($maxevents > $epoll_wait_size) {
297                 $epoll_wait_size = $maxevents;
298                 vec($epoll_wait_events, $maxevents * 12 * 8 - 1, 1) = 0;
299         }
300         @$events = ();
301         my $ct = syscall($SYS_epoll_wait, $epfd, $epoll_wait_events,
302                         $maxevents, $timeout_msec);
303         for (0..$ct - 1) {
304                 # 12-byte struct epoll_event
305                 # 4 bytes uint32_t events mask (skipped, useless to us)
306                 # 8 bytes: epoll_data_t union (first 4 bytes are the fd)
307                 # So we skip the first 4 bytes and take the middle 4:
308                 $events->[$_] = unpack('L', substr($epoll_wait_events,
309                                                         12 * $_ + 4, 4));
310         }
311 }
312
313 sub epoll_wait_mod8 {
314         my ($epfd, $maxevents, $timeout_msec, $events) = @_;
315
316         # resize our static buffer if maxevents bigger than we've ever done
317         if ($maxevents > $epoll_wait_size) {
318                 $epoll_wait_size = $maxevents;
319                 vec($epoll_wait_events, $maxevents * 16 * 8 - 1, 1) = 0;
320         }
321         @$events = ();
322         my $ct = syscall($SYS_epoll_wait, $epfd, $epoll_wait_events,
323                         $maxevents, $timeout_msec,
324                         $no_deprecated ? undef : ());
325         for (0..$ct - 1) {
326                 # 16-byte struct epoll_event
327                 # 4 bytes uint32_t events mask (skipped, useless to us)
328                 # 4 bytes padding (skipped, useless)
329                 # 8 bytes epoll_data_t union (first 4 bytes are the fd)
330                 # So skip the first 8 bytes, take 4, and ignore the last 4:
331                 $events->[$_] = unpack('L', substr($epoll_wait_events,
332                                                         16 * $_ + 8, 4));
333         }
334 }
335
336 sub signalfd ($$) {
337         my ($signos, $nonblock) = @_;
338         if ($SYS_signalfd4) {
339                 my $set = POSIX::SigSet->new(@$signos);
340                 syscall($SYS_signalfd4, -1, "$$set",
341                         # $Config{sig_count} is NSIG, so this is NSIG/8:
342                         int($Config{sig_count}/8),
343                         # SFD_NONBLOCK == O_NONBLOCK for every architecture
344                         ($nonblock ? O_NONBLOCK : 0) |$SFD_CLOEXEC);
345         } else {
346                 $! = ENOSYS;
347                 undef;
348         }
349 }
350
351 sub _rename_noreplace_racy ($$) {
352         my ($old, $new) = @_;
353         if (link($old, $new)) {
354                 warn "unlink $old: $!\n" if !unlink($old) && $! != ENOENT;
355                 1
356         } else {
357                 undef;
358         }
359 }
360
361 # TODO: support FD args?
362 sub rename_noreplace ($$) {
363         my ($old, $new) = @_;
364         if ($SYS_renameat2) { # RENAME_NOREPLACE = 1, AT_FDCWD = -100
365                 my $ret = syscall($SYS_renameat2, -100, $old, -100, $new, 1);
366                 if ($ret == 0) {
367                         1; # like rename() perlop
368                 } elsif ($! == ENOSYS || $! == EINVAL) {
369                         undef $SYS_renameat2;
370                         _rename_noreplace_racy($old, $new);
371                 } else {
372                         undef
373                 }
374         } else {
375                 _rename_noreplace_racy($old, $new);
376         }
377 }
378
379 sub nodatacow_fh {
380         return if !defined($SYS_fstatfs);
381         my $buf = '';
382         vec($buf, 120 * 8 - 1, 1) = 0;
383         my ($fh) = @_;
384         syscall($SYS_fstatfs, fileno($fh), $buf) == 0 or
385                 return warn("fstatfs: $!\n");
386         my $f_type = unpack('l!', $buf); # statfs.f_type is a signed word
387         return if $f_type != 0x9123683E; # BTRFS_SUPER_MAGIC
388
389         $FS_IOC_GETFLAGS //
390                 return warn('FS_IOC_GETFLAGS undefined for platform');
391         ioctl($fh, $FS_IOC_GETFLAGS, $buf) //
392                 return warn("FS_IOC_GETFLAGS: $!\n");
393         my $attr = unpack('l!', $buf);
394         return if ($attr & 0x00800000); # FS_NOCOW_FL;
395         ioctl($fh, $FS_IOC_SETFLAGS, pack('l', $attr | 0x00800000)) //
396                 warn("FS_IOC_SETFLAGS: $!\n");
397 }
398
399 sub nodatacow_dir {
400         if (open my $fh, '<', $_[0]) { nodatacow_fh($fh) }
401 }
402
403 sub CMSG_ALIGN ($) { ($_[0] + SIZEOF_size_t - 1) & ~(SIZEOF_size_t - 1) }
404 use constant CMSG_ALIGN_SIZEOF_cmsghdr => CMSG_ALIGN(SIZEOF_cmsghdr);
405 sub CMSG_SPACE ($) { CMSG_ALIGN($_[0]) + CMSG_ALIGN_SIZEOF_cmsghdr }
406 sub CMSG_LEN ($) { CMSG_ALIGN_SIZEOF_cmsghdr + $_[0] }
407
408 if (defined($SYS_sendmsg) && defined($SYS_recvmsg)) {
409 no warnings 'once';
410 *send_cmd4 = sub ($$$$) {
411         my ($sock, $fds, undef, $flags) = @_;
412         my $iov = pack('P'.TMPL_size_t,
413                         $_[2] // NUL, length($_[2] // NUL) || 1);
414         my $cmsghdr = pack(TMPL_size_t . # cmsg_len
415                         'LL' .  # cmsg_level, cmsg_type,
416                         ('i' x scalar(@$fds)),
417                         CMSG_LEN(scalar(@$fds) * SIZEOF_int), # cmsg_len
418                         SOL_SOCKET, SCM_RIGHTS, # cmsg_{level,type}
419                         @$fds); # CMSG_DATA
420         my $mh = pack('PL' . # msg_name, msg_namelen (socklen_t (U32))
421                         BYTES_4_hole . # 4-byte padding on 64-bit
422                         'P'.TMPL_size_t . # msg_iov, msg_iovlen,
423                         'P'.TMPL_size_t . # msg_control, msg_controllen,
424                         'i', # msg_flags
425                         NUL, 0, # msg_name, msg_namelen (unused)
426                         @BYTES_4_hole,
427                         $iov, 1, # msg_iov, msg_iovlen
428                         $cmsghdr, # msg_control
429                         CMSG_SPACE(scalar(@$fds) * SIZEOF_int), # msg_controllen
430                         0); # msg_flags
431         my $sent;
432         my $try = 0;
433         do {
434                 $sent = syscall($SYS_sendmsg, fileno($sock), $mh, $flags);
435         } while ($sent < 0 &&
436                         ($!{ENOBUFS} || $!{ENOMEM} || $!{ETOOMANYREFS}) &&
437                         (++$try < 50) &&
438                         warn "sleeping on sendmsg: $! (#$try)\n" &&
439                         select(undef, undef, undef, 0.1) == 0);
440         $sent >= 0 ? $sent : undef;
441 };
442
443 *recv_cmd4 = sub ($$$) {
444         my ($sock, undef, $len) = @_;
445         vec($_[1], ($len + 1) * 8, 1) = 0;
446         vec(my $cmsghdr = '', 256 * 8 - 1, 1) = 1;
447         my $iov = pack('P'.TMPL_size_t, $_[1], $len);
448         my $mh = pack('PL' . # msg_name, msg_namelen (socklen_t (U32))
449                         BYTES_4_hole . # 4-byte padding on 64-bit
450                         'P'.TMPL_size_t . # msg_iov, msg_iovlen,
451                         'P'.TMPL_size_t . # msg_control, msg_controllen,
452                         'i', # msg_flags
453                         NUL, 0, # msg_name, msg_namelen (unused)
454                         @BYTES_4_hole,
455                         $iov, 1, # msg_iov, msg_iovlen
456                         $cmsghdr, # msg_control
457                         256, # msg_controllen
458                         0); # msg_flags
459         my $r = syscall($SYS_recvmsg, fileno($sock), $mh, 0);
460         return (undef) if $r < 0; # $! set
461         substr($_[1], $r, length($_[1]), '');
462         my @ret;
463         if ($r > 0) {
464                 my ($len, $lvl, $type, @fds) = unpack(TMPL_size_t . # cmsg_len
465                                         'LLi*', # cmsg_level, cmsg_type, @fds
466                                         $cmsghdr);
467                 if ($lvl == SOL_SOCKET && $type == SCM_RIGHTS) {
468                         $len -= CMSG_ALIGN_SIZEOF_cmsghdr;
469                         @ret = @fds[0..(($len / SIZEOF_int) - 1)];
470                 }
471         }
472         @ret;
473 };
474 }
475
476 1;
477
478 =head1 WARRANTY
479
480 This is free software. IT COMES WITHOUT WARRANTY OF ANY KIND.
481
482 =head1 AUTHORS
483
484 Brad Fitzpatrick <brad@danga.com>