1#!/usr/local/bin/perl
2# Copyright 2009 The Go Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style
4# license that can be found in the LICENSE file.
5
6# This program reads a file containing function prototypes
7# (like syscall_solaris.go) and generates system call bodies.
8# The prototypes are marked by lines beginning with "//sys"
9# and read like func declarations if //sys is replaced by func, but:
10#	* The parameter lists must give a name for each argument.
11#	  This includes return parameters.
12#	* The parameter lists must give a type for each argument:
13#	  the (x, y, z int) shorthand is not allowed.
14#	* If the return parameter is an error number, it must be named err.
15#	* If go func name needs to be different than its libc name,
16#	* or the function is not in libc, name could be specified
17#	* at the end, after "=" sign, like
18#	  //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt
19
20use strict;
21
22my $cmdline = "mksyscall_libc.pl " . join(' ', @ARGV);
23my $errors = 0;
24my $_32bit = "";
25my $tags = "";  # build tags
26my $newtags = ""; # new style build tags
27my $aix = 0;
28my $solaris = 0;
29
30binmode STDOUT;
31
32if($ARGV[0] eq "-b32") {
33	$_32bit = "big-endian";
34	shift;
35} elsif($ARGV[0] eq "-l32") {
36	$_32bit = "little-endian";
37	shift;
38}
39if($ARGV[0] eq "-aix") {
40	$aix = 1;
41	shift;
42}
43if($ARGV[0] eq "-solaris") {
44	$solaris = 1;
45	shift;
46}
47if($ARGV[0] eq "-tags") {
48	shift;
49	$tags = $ARGV[0];
50	shift;
51}
52
53
54if($ARGV[0] =~ /^-/) {
55	print STDERR "usage: mksyscall_libc.pl [-b32 | -l32] [-aix | -solaris] [-tags x,y] [file ...]\n";
56	exit 1;
57}
58
59sub parseparamlist($) {
60	my ($list) = @_;
61	$list =~ s/^\s*//;
62	$list =~ s/\s*$//;
63	if($list eq "") {
64		return ();
65	}
66	return split(/\s*,\s*/, $list);
67}
68
69sub parseparam($) {
70	my ($p) = @_;
71	if($p !~ /^(\S*) (\S*)$/) {
72		print STDERR "$ARGV:$.: malformed parameter: $p\n";
73		$errors = 1;
74		return ("xx", "int");
75	}
76	return ($1, $2);
77}
78
79my $package = "";
80my $text = "";
81my $dynimports = "";
82my $linknames = "";
83my @vars = ();
84while(<>) {
85	chomp;
86	s/\s+/ /g;
87	s/^\s+//;
88	s/\s+$//;
89	$package = $1 if !$package && /^package (\S+)$/;
90	my $nonblock = /^\/\/sysnb /;
91	next if !/^\/\/sys / && !$nonblock;
92
93	my $syscalldot = "";
94	$syscalldot = "syscall." if $package ne "syscall";
95
96	# Line must be of the form
97	#	func Open(path string, mode int, perm int) (fd int, err error)
98	# Split into name, in params, out params.
99	if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$/) {
100		print STDERR "$ARGV:$.: malformed //sys declaration\n";
101		$errors = 1;
102		next;
103	}
104	my ($nb, $func, $in, $out, $modname, $sysname) = ($1, $2, $3, $4, $5, $6);
105
106	# Split argument lists on comma.
107	my @in = parseparamlist($in);
108	my @out = parseparamlist($out);
109
110	# Try in vain to keep people from editing this file.
111	# The theory is that they jump into the middle of the file
112	# without reading the header.
113	$text .= "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n";
114
115	# So file name.
116	if($aix) {
117		if($modname eq "") {
118			$modname = "libc.a/shr_64.o";
119		} else {
120			print STDERR "$func: only syscall using libc are available\n";
121			$errors = 1;
122			next;
123		}
124
125	}
126	if($solaris) {
127		if($modname eq "") {
128			$modname = "libc";
129		}
130		$modname .= ".so";
131
132	}
133
134	# System call name.
135	if($sysname eq "") {
136		$sysname = "$func";
137	}
138
139	# System call pointer variable name.
140	my $sysvarname = "libc_${sysname}";
141
142	my $strconvfunc = "BytePtrFromString";
143	my $strconvtype = "*byte";
144
145	$sysname =~ y/A-Z/a-z/; # All libc functions are lowercase.
146
147	# Runtime import of function to allow cross-platform builds.
148	$dynimports .= "//go:cgo_import_dynamic ${sysvarname} ${sysname} \"$modname\"\n";
149	# Link symbol to proc address variable.
150	$linknames .= "//go:linkname ${sysvarname} ${sysvarname}\n";
151	# Library proc address variable.
152	push @vars, $sysvarname;
153
154	# Go function header.
155	$out = join(', ', @out);
156	if($out ne "") {
157		$out = " ($out)";
158	}
159	if($text ne "") {
160		$text .= "\n"
161	}
162	$text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out;
163
164	# Check if err return available
165	my $errvar = "";
166	foreach my $p (@out) {
167		my ($name, $type) = parseparam($p);
168		if($type eq "error") {
169			$errvar = $name;
170			last;
171		}
172	}
173
174	# Prepare arguments to Syscall.
175	my @args = ();
176	my $n = 0;
177	foreach my $p (@in) {
178		my ($name, $type) = parseparam($p);
179		if($type =~ /^\*/) {
180			push @args, "uintptr(unsafe.Pointer($name))";
181		} elsif($type eq "string" && $errvar ne "") {
182			$text .= "\tvar _p$n $strconvtype\n";
183			$text .= "\t_p$n, $errvar = $strconvfunc($name)\n";
184			$text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n";
185			push @args, "uintptr(unsafe.Pointer(_p$n))";
186			$n++;
187		} elsif($type eq "string") {
188			print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n";
189			$text .= "\tvar _p$n $strconvtype\n";
190			$text .= "\t_p$n, _ = $strconvfunc($name)\n";
191			push @args, "uintptr(unsafe.Pointer(_p$n))";
192			$n++;
193		} elsif($type =~ /^\[\](.*)/) {
194			# Convert slice into pointer, length.
195			# Have to be careful not to take address of &a[0] if len == 0:
196			# pass nil in that case.
197			$text .= "\tvar _p$n *$1\n";
198			$text .= "\tif len($name) > 0 {\n\t\t_p$n = \&$name\[0]\n\t}\n";
199			push @args, "uintptr(unsafe.Pointer(_p$n))", "uintptr(len($name))";
200			$n++;
201		} elsif($type eq "int64" && $_32bit ne "") {
202			if($_32bit eq "big-endian") {
203				push @args, "uintptr($name >> 32)", "uintptr($name)";
204			} else {
205				push @args, "uintptr($name)", "uintptr($name >> 32)";
206			}
207		} elsif($type eq "bool") {
208 			$text .= "\tvar _p$n uint32\n";
209			$text .= "\tif $name {\n\t\t_p$n = 1\n\t} else {\n\t\t_p$n = 0\n\t}\n";
210			push @args, "uintptr(_p$n)";
211			$n++;
212		} else {
213			push @args, "uintptr($name)";
214		}
215	}
216	my $nargs = @args;
217
218	my $asmfuncname="";
219	my $asmrawfuncname="";
220
221	if($aix){
222		$asmfuncname="syscall6";
223		$asmrawfuncname="rawSyscall6";
224	} else {
225		$asmfuncname="sysvicall6";
226		$asmrawfuncname="rawSysvicall6";
227	}
228
229	# Determine which form to use; pad args with zeros.
230	my $asm = "${syscalldot}${asmfuncname}";
231	if ($nonblock) {
232		$asm = "${syscalldot}${asmrawfuncname}";
233	}
234	if(@args <= 6) {
235		while(@args < 6) {
236			push @args, "0";
237		}
238	} else {
239		print STDERR "$ARGV:$.: too many arguments to system call\n";
240	}
241
242	# Actual call.
243	my $args = join(', ', @args);
244	my $call = "$asm(uintptr(unsafe.Pointer(&$sysvarname)), $nargs, $args)";
245
246	# Assign return values.
247	my $body = "";
248	my $failexpr = "";
249	my @ret = ("_", "_", "_");
250	my @pout= ();
251	my $do_errno = 0;
252	for(my $i=0; $i<@out; $i++) {
253		my $p = $out[$i];
254		my ($name, $type) = parseparam($p);
255		my $reg = "";
256		if($name eq "err") {
257			$reg = "e1";
258			$ret[2] = $reg;
259			$do_errno = 1;
260		} else {
261			$reg = sprintf("r%d", $i);
262			$ret[$i] = $reg;
263		}
264		if($type eq "bool") {
265			$reg = "$reg != 0";
266		}
267		if($type eq "int64" && $_32bit ne "") {
268			# 64-bit number in r1:r0 or r0:r1.
269			if($i+2 > @out) {
270				print STDERR "$ARGV:$.: not enough registers for int64 return\n";
271			}
272			if($_32bit eq "big-endian") {
273				$reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1);
274			} else {
275				$reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i);
276			}
277			$ret[$i] = sprintf("r%d", $i);
278			$ret[$i+1] = sprintf("r%d", $i+1);
279		}
280		if($reg ne "e1") {
281			$body .= "\t$name = $type($reg)\n";
282		}
283	}
284	if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") {
285		$text .= "\t$call\n";
286	} else {
287		$text .= "\t$ret[0], $ret[1], $ret[2] := $call\n";
288	}
289	$text .= $body;
290
291	if ($do_errno) {
292		$text .= "\tif e1 != 0 {\n";
293		$text .= "\t\terr = errnoErr(e1)\n";
294		$text .= "\t}\n";
295	}
296	$text .= "\treturn\n";
297	$text .= "}\n";
298}
299
300if($errors) {
301	exit 1;
302}
303
304# TODO: this assumes tags are just simply comma separated. For now this is all the uses.
305$newtags = $tags =~ s/,/ && /r;
306
307print <<EOF;
308// $cmdline
309// Code generated by the command above; DO NOT EDIT.
310
311//go:build $newtags
312
313package $package
314
315import "unsafe"
316EOF
317
318print "import \"syscall\"\n" if $package ne "syscall";
319
320my $vardecls = "\t" . join(",\n\t", @vars);
321$vardecls .= " libcFunc";
322
323chomp($_=<<EOF);
324
325$dynimports
326$linknames
327type libcFunc uintptr
328
329var (
330$vardecls
331)
332
333$text
334EOF
335print $_;
336exit 0;
337