| 1 |
// Copyright 2013 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 |
|
| 5 |
/* |
| 6 |
mkwinsyscall generates windows system call bodies |
| 7 |
|
| 8 |
It parses all files specified on command line containing function |
| 9 |
prototypes (like syscall_windows.go) and prints system call bodies |
| 10 |
to standard output. |
| 11 |
|
| 12 |
The prototypes are marked by lines beginning with "//sys" and read |
| 13 |
like func declarations if //sys is replaced by func, but: |
| 14 |
|
| 15 |
- The parameter lists must give a name for each argument. This |
| 16 |
includes return parameters. |
| 17 |
|
| 18 |
- The parameter lists must give a type for each argument: |
| 19 |
the (x, y, z int) shorthand is not allowed. |
| 20 |
|
| 21 |
- If the return parameter is an error number, it must be named err. |
| 22 |
|
| 23 |
- If go func name needs to be different from its winapi dll name, |
| 24 |
the winapi name could be specified at the end, after "=" sign, like |
| 25 |
//sys LoadLibrary(libname string) (handle uint32, err error) = LoadLibraryA |
| 26 |
|
| 27 |
- Each function that returns err needs to supply a condition, that |
| 28 |
return value of winapi will be tested against to detect failure. |
| 29 |
This would set err to windows "last-error", otherwise it will be nil. |
| 30 |
The value can be provided at end of //sys declaration, like |
| 31 |
//sys LoadLibrary(libname string) (handle uint32, err error) [failretval==-1] = LoadLibraryA |
| 32 |
and is [failretval==0] by default. |
| 33 |
|
| 34 |
- If the function name ends in a "?", then the function not existing is non- |
| 35 |
fatal, and an error will be returned instead of panicking. |
| 36 |
|
| 37 |
Usage: |
| 38 |
|
| 39 |
mkwinsyscall [flags] [path ...] |
| 40 |
|
| 41 |
The flags are: |
| 42 |
|
| 43 |
-output |
| 44 |
Specify output file name (outputs to console if blank). |
| 45 |
-trace |
| 46 |
Generate print statement after every syscall. |
| 47 |
*/ |
| 48 |
package main |
| 49 |
|
| 50 |
import ( |
| 51 |
"bufio" |
| 52 |
"bytes" |
| 53 |
"errors" |
| 54 |
"flag" |
| 55 |
"fmt" |
| 56 |
"go/format" |
| 57 |
"go/parser" |
| 58 |
"go/token" |
| 59 |
"io" |
| 60 |
"log" |
| 61 |
"os" |
| 62 |
"path/filepath" |
| 63 |
"runtime" |
| 64 |
"sort" |
| 65 |
"strings" |
| 66 |
"text/template" |
| 67 |
) |
| 68 |
|
| 69 |
var ( |
| 70 |
filename = flag.String("output", "", "output file name (standard output if omitted)") |
| 71 |
printTraceFlag = flag.Bool("trace", false, "generate print statement after every syscall") |
| 72 |
systemDLL = flag.Bool("systemdll", true, "whether all DLLs should be loaded from the Windows system directory") |
| 73 |
) |
| 74 |
|
| 75 |
func trim(s string) string { |
| 76 |
return strings.Trim(s, " \t") |
| 77 |
} |
| 78 |
|
| 79 |
var packageName string |
| 80 |
|
| 81 |
func packagename() string { |
| 82 |
return packageName |
| 83 |
} |
| 84 |
|
| 85 |
func windowsdot() string { |
| 86 |
if packageName == "windows" { |
| 87 |
return "" |
| 88 |
} |
| 89 |
return "windows." |
| 90 |
} |
| 91 |
|
| 92 |
func syscalldot() string { |
| 93 |
if packageName == "syscall" { |
| 94 |
return "" |
| 95 |
} |
| 96 |
return "syscall." |
| 97 |
} |
| 98 |
|
| 99 |
// Param is function parameter |
| 100 |
type Param struct { |
| 101 |
Name string |
| 102 |
Type string |
| 103 |
fn *Fn |
| 104 |
tmpVarIdx int |
| 105 |
} |
| 106 |
|
| 107 |
// tmpVar returns temp variable name that will be used to represent p during syscall. |
| 108 |
func (p *Param) tmpVar() string { |
| 109 |
if p.tmpVarIdx < 0 { |
| 110 |
p.tmpVarIdx = p.fn.curTmpVarIdx |
| 111 |
p.fn.curTmpVarIdx++ |
| 112 |
} |
| 113 |
return fmt.Sprintf("_p%d", p.tmpVarIdx) |
| 114 |
} |
| 115 |
|
| 116 |
// BoolTmpVarCode returns source code for bool temp variable. |
| 117 |
func (p *Param) BoolTmpVarCode() string { |
| 118 |
const code = `var %[1]s uint32 |
| 119 |
if %[2]s { |
| 120 |
%[1]s = 1 |
| 121 |
}` |
| 122 |
return fmt.Sprintf(code, p.tmpVar(), p.Name) |
| 123 |
} |
| 124 |
|
| 125 |
// BoolPointerTmpVarCode returns source code for bool temp variable. |
| 126 |
func (p *Param) BoolPointerTmpVarCode() string { |
| 127 |
const code = `var %[1]s uint32 |
| 128 |
if *%[2]s { |
| 129 |
%[1]s = 1 |
| 130 |
}` |
| 131 |
return fmt.Sprintf(code, p.tmpVar(), p.Name) |
| 132 |
} |
| 133 |
|
| 134 |
// SliceTmpVarCode returns source code for slice temp variable. |
| 135 |
func (p *Param) SliceTmpVarCode() string { |
| 136 |
const code = `var %s *%s |
| 137 |
if len(%s) > 0 { |
| 138 |
%s = &%s[0] |
| 139 |
}` |
| 140 |
tmp := p.tmpVar() |
| 141 |
return fmt.Sprintf(code, tmp, p.Type[2:], p.Name, tmp, p.Name) |
| 142 |
} |
| 143 |
|
| 144 |
// StringTmpVarCode returns source code for string temp variable. |
| 145 |
func (p *Param) StringTmpVarCode() string { |
| 146 |
errvar := p.fn.Rets.ErrorVarName() |
| 147 |
if errvar == "" { |
| 148 |
errvar = "_" |
| 149 |
} |
| 150 |
tmp := p.tmpVar() |
| 151 |
const code = `var %s %s |
| 152 |
%s, %s = %s(%s)` |
| 153 |
s := fmt.Sprintf(code, tmp, p.fn.StrconvType(), tmp, errvar, p.fn.StrconvFunc(), p.Name) |
| 154 |
if errvar == "-" { |
| 155 |
return s |
| 156 |
} |
| 157 |
const morecode = ` |
| 158 |
if %s != nil { |
| 159 |
return |
| 160 |
}` |
| 161 |
return s + fmt.Sprintf(morecode, errvar) |
| 162 |
} |
| 163 |
|
| 164 |
// TmpVarCode returns source code for temp variable. |
| 165 |
func (p *Param) TmpVarCode() string { |
| 166 |
switch { |
| 167 |
case p.Type == "bool": |
| 168 |
return p.BoolTmpVarCode() |
| 169 |
case p.Type == "*bool": |
| 170 |
return p.BoolPointerTmpVarCode() |
| 171 |
case strings.HasPrefix(p.Type, "[]"): |
| 172 |
return p.SliceTmpVarCode() |
| 173 |
default: |
| 174 |
return "" |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
// TmpVarReadbackCode returns source code for reading back the temp variable into the original variable. |
| 179 |
func (p *Param) TmpVarReadbackCode() string { |
| 180 |
switch { |
| 181 |
case p.Type == "*bool": |
| 182 |
return fmt.Sprintf("*%s = %s != 0", p.Name, p.tmpVar()) |
| 183 |
default: |
| 184 |
return "" |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
// TmpVarHelperCode returns source code for helper's temp variable. |
| 189 |
func (p *Param) TmpVarHelperCode() string { |
| 190 |
if p.Type != "string" { |
| 191 |
return "" |
| 192 |
} |
| 193 |
return p.StringTmpVarCode() |
| 194 |
} |
| 195 |
|
| 196 |
// SyscallArgList returns source code fragments representing p parameter |
| 197 |
// in syscall. Slices are translated into 2 syscall parameters: pointer to |
| 198 |
// the first element and length. |
| 199 |
func (p *Param) SyscallArgList() []string { |
| 200 |
t := p.HelperType() |
| 201 |
var s string |
| 202 |
switch { |
| 203 |
case t == "*bool": |
| 204 |
s = fmt.Sprintf("unsafe.Pointer(&%s)", p.tmpVar()) |
| 205 |
case t[0] == '*': |
| 206 |
s = fmt.Sprintf("unsafe.Pointer(%s)", p.Name) |
| 207 |
case t == "bool": |
| 208 |
s = p.tmpVar() |
| 209 |
case strings.HasPrefix(t, "[]"): |
| 210 |
return []string{ |
| 211 |
fmt.Sprintf("uintptr(unsafe.Pointer(%s))", p.tmpVar()), |
| 212 |
fmt.Sprintf("uintptr(len(%s))", p.Name), |
| 213 |
} |
| 214 |
default: |
| 215 |
s = p.Name |
| 216 |
} |
| 217 |
return []string{fmt.Sprintf("uintptr(%s)", s)} |
| 218 |
} |
| 219 |
|
| 220 |
// IsError determines if p parameter is used to return error. |
| 221 |
func (p *Param) IsError() bool { |
| 222 |
return p.Name == "err" && p.Type == "error" |
| 223 |
} |
| 224 |
|
| 225 |
// HelperType returns type of parameter p used in helper function. |
| 226 |
func (p *Param) HelperType() string { |
| 227 |
if p.Type == "string" { |
| 228 |
return p.fn.StrconvType() |
| 229 |
} |
| 230 |
return p.Type |
| 231 |
} |
| 232 |
|
| 233 |
// join concatenates parameters ps into a string with sep separator. |
| 234 |
// Each parameter is converted into string by applying fn to it |
| 235 |
// before conversion. |
| 236 |
func join(ps []*Param, fn func(*Param) string, sep string) string { |
| 237 |
if len(ps) == 0 { |
| 238 |
return "" |
| 239 |
} |
| 240 |
a := make([]string, 0) |
| 241 |
for _, p := range ps { |
| 242 |
a = append(a, fn(p)) |
| 243 |
} |
| 244 |
return strings.Join(a, sep) |
| 245 |
} |
| 246 |
|
| 247 |
// Rets describes function return parameters. |
| 248 |
type Rets struct { |
| 249 |
Name string |
| 250 |
Type string |
| 251 |
ReturnsError bool |
| 252 |
FailCond string |
| 253 |
fnMaybeAbsent bool |
| 254 |
} |
| 255 |
|
| 256 |
// ErrorVarName returns error variable name for r. |
| 257 |
func (r *Rets) ErrorVarName() string { |
| 258 |
if r.ReturnsError { |
| 259 |
return "err" |
| 260 |
} |
| 261 |
if r.Type == "error" { |
| 262 |
return r.Name |
| 263 |
} |
| 264 |
return "" |
| 265 |
} |
| 266 |
|
| 267 |
// ToParams converts r into slice of *Param. |
| 268 |
func (r *Rets) ToParams() []*Param { |
| 269 |
ps := make([]*Param, 0) |
| 270 |
if len(r.Name) > 0 { |
| 271 |
ps = append(ps, &Param{Name: r.Name, Type: r.Type}) |
| 272 |
} |
| 273 |
if r.ReturnsError { |
| 274 |
ps = append(ps, &Param{Name: "err", Type: "error"}) |
| 275 |
} |
| 276 |
return ps |
| 277 |
} |
| 278 |
|
| 279 |
// List returns source code of syscall return parameters. |
| 280 |
func (r *Rets) List() string { |
| 281 |
s := join(r.ToParams(), func(p *Param) string { return p.Name + " " + p.Type }, ", ") |
| 282 |
if len(s) > 0 { |
| 283 |
s = "(" + s + ")" |
| 284 |
} else if r.fnMaybeAbsent { |
| 285 |
s = "(err error)" |
| 286 |
} |
| 287 |
return s |
| 288 |
} |
| 289 |
|
| 290 |
// PrintList returns source code of trace printing part correspondent |
| 291 |
// to syscall return values. |
| 292 |
func (r *Rets) PrintList() string { |
| 293 |
return join(r.ToParams(), func(p *Param) string { return fmt.Sprintf(`"%s=", %s, `, p.Name, p.Name) }, `", ", `) |
| 294 |
} |
| 295 |
|
| 296 |
// SetReturnValuesCode returns source code that accepts syscall return values. |
| 297 |
func (r *Rets) SetReturnValuesCode() string { |
| 298 |
if r.Name == "" && !r.ReturnsError { |
| 299 |
return "" |
| 300 |
} |
| 301 |
retvar := "r0" |
| 302 |
if r.Name == "" { |
| 303 |
retvar = "r1" |
| 304 |
} |
| 305 |
errvar := "_" |
| 306 |
if r.ReturnsError { |
| 307 |
errvar = "e1" |
| 308 |
} |
| 309 |
return fmt.Sprintf("%s, _, %s := ", retvar, errvar) |
| 310 |
} |
| 311 |
|
| 312 |
func (r *Rets) useLongHandleErrorCode(retvar string) string { |
| 313 |
const code = `if %s { |
| 314 |
err = errnoErr(e1) |
| 315 |
}` |
| 316 |
cond := retvar + " == 0" |
| 317 |
if r.FailCond != "" { |
| 318 |
cond = strings.Replace(r.FailCond, "failretval", retvar, 1) |
| 319 |
} |
| 320 |
return fmt.Sprintf(code, cond) |
| 321 |
} |
| 322 |
|
| 323 |
// SetErrorCode returns source code that sets return parameters. |
| 324 |
func (r *Rets) SetErrorCode() string { |
| 325 |
const code = `if r0 != 0 { |
| 326 |
%s = %sErrno(r0) |
| 327 |
}` |
| 328 |
const ntstatus = `if r0 != 0 { |
| 329 |
ntstatus = %sNTStatus(r0) |
| 330 |
}` |
| 331 |
if r.Name == "" && !r.ReturnsError { |
| 332 |
return "" |
| 333 |
} |
| 334 |
if r.Name == "" { |
| 335 |
return r.useLongHandleErrorCode("r1") |
| 336 |
} |
| 337 |
if r.Type == "error" && r.Name == "ntstatus" { |
| 338 |
return fmt.Sprintf(ntstatus, windowsdot()) |
| 339 |
} |
| 340 |
if r.Type == "error" { |
| 341 |
return fmt.Sprintf(code, r.Name, syscalldot()) |
| 342 |
} |
| 343 |
s := "" |
| 344 |
switch { |
| 345 |
case r.Type[0] == '*': |
| 346 |
s = fmt.Sprintf("%s = (%s)(unsafe.Pointer(r0))", r.Name, r.Type) |
| 347 |
case r.Type == "bool": |
| 348 |
s = fmt.Sprintf("%s = r0 != 0", r.Name) |
| 349 |
default: |
| 350 |
s = fmt.Sprintf("%s = %s(r0)", r.Name, r.Type) |
| 351 |
} |
| 352 |
if !r.ReturnsError { |
| 353 |
return s |
| 354 |
} |
| 355 |
return s + "\n\t" + r.useLongHandleErrorCode(r.Name) |
| 356 |
} |
| 357 |
|
| 358 |
// Fn describes syscall function. |
| 359 |
type Fn struct { |
| 360 |
Name string |
| 361 |
Params []*Param |
| 362 |
Rets *Rets |
| 363 |
PrintTrace bool |
| 364 |
dllname string |
| 365 |
dllfuncname string |
| 366 |
src string |
| 367 |
// TODO: get rid of this field and just use parameter index instead |
| 368 |
curTmpVarIdx int // insure tmp variables have uniq names |
| 369 |
} |
| 370 |
|
| 371 |
// extractParams parses s to extract function parameters. |
| 372 |
func extractParams(s string, f *Fn) ([]*Param, error) { |
| 373 |
s = trim(s) |
| 374 |
if s == "" { |
| 375 |
return nil, nil |
| 376 |
} |
| 377 |
a := strings.Split(s, ",") |
| 378 |
ps := make([]*Param, len(a)) |
| 379 |
for i := range ps { |
| 380 |
s2 := trim(a[i]) |
| 381 |
b := strings.Split(s2, " ") |
| 382 |
if len(b) != 2 { |
| 383 |
b = strings.Split(s2, "\t") |
| 384 |
if len(b) != 2 { |
| 385 |
return nil, errors.New("Could not extract function parameter from \"" + s2 + "\"") |
| 386 |
} |
| 387 |
} |
| 388 |
ps[i] = &Param{ |
| 389 |
Name: trim(b[0]), |
| 390 |
Type: trim(b[1]), |
| 391 |
fn: f, |
| 392 |
tmpVarIdx: -1, |
| 393 |
} |
| 394 |
} |
| 395 |
return ps, nil |
| 396 |
} |
| 397 |
|
| 398 |
// extractSection extracts text out of string s starting after start |
| 399 |
// and ending just before end. found return value will indicate success, |
| 400 |
// and prefix, body and suffix will contain correspondent parts of string s. |
| 401 |
func extractSection(s string, start, end rune) (prefix, body, suffix string, found bool) { |
| 402 |
s = trim(s) |
| 403 |
if strings.HasPrefix(s, string(start)) { |
| 404 |
// no prefix |
| 405 |
body = s[1:] |
| 406 |
} else { |
| 407 |
a := strings.SplitN(s, string(start), 2) |
| 408 |
if len(a) != 2 { |
| 409 |
return "", "", s, false |
| 410 |
} |
| 411 |
prefix = a[0] |
| 412 |
body = a[1] |
| 413 |
} |
| 414 |
a := strings.SplitN(body, string(end), 2) |
| 415 |
if len(a) != 2 { |
| 416 |
return "", "", "", false |
| 417 |
} |
| 418 |
return prefix, a[0], a[1], true |
| 419 |
} |
| 420 |
|
| 421 |
// newFn parses string s and return created function Fn. |
| 422 |
func newFn(s string) (*Fn, error) { |
| 423 |
s = trim(s) |
| 424 |
f := &Fn{ |
| 425 |
Rets: &Rets{}, |
| 426 |
src: s, |
| 427 |
PrintTrace: *printTraceFlag, |
| 428 |
} |
| 429 |
// function name and args |
| 430 |
prefix, body, s, found := extractSection(s, '(', ')') |
| 431 |
if !found || prefix == "" { |
| 432 |
return nil, errors.New("Could not extract function name and parameters from \"" + f.src + "\"") |
| 433 |
} |
| 434 |
f.Name = prefix |
| 435 |
var err error |
| 436 |
f.Params, err = extractParams(body, f) |
| 437 |
if err != nil { |
| 438 |
return nil, err |
| 439 |
} |
| 440 |
// return values |
| 441 |
_, body, s, found = extractSection(s, '(', ')') |
| 442 |
if found { |
| 443 |
r, err := extractParams(body, f) |
| 444 |
if err != nil { |
| 445 |
return nil, err |
| 446 |
} |
| 447 |
switch len(r) { |
| 448 |
case 0: |
| 449 |
case 1: |
| 450 |
if r[0].IsError() { |
| 451 |
f.Rets.ReturnsError = true |
| 452 |
} else { |
| 453 |
f.Rets.Name = r[0].Name |
| 454 |
f.Rets.Type = r[0].Type |
| 455 |
} |
| 456 |
case 2: |
| 457 |
if !r[1].IsError() { |
| 458 |
return nil, errors.New("Only last windows error is allowed as second return value in \"" + f.src + "\"") |
| 459 |
} |
| 460 |
f.Rets.ReturnsError = true |
| 461 |
f.Rets.Name = r[0].Name |
| 462 |
f.Rets.Type = r[0].Type |
| 463 |
default: |
| 464 |
return nil, errors.New("Too many return values in \"" + f.src + "\"") |
| 465 |
} |
| 466 |
} |
| 467 |
// fail condition |
| 468 |
_, body, s, found = extractSection(s, '[', ']') |
| 469 |
if found { |
| 470 |
f.Rets.FailCond = body |
| 471 |
} |
| 472 |
// dll and dll function names |
| 473 |
s = trim(s) |
| 474 |
if s == "" { |
| 475 |
return f, nil |
| 476 |
} |
| 477 |
if !strings.HasPrefix(s, "=") { |
| 478 |
return nil, errors.New("Could not extract dll name from \"" + f.src + "\"") |
| 479 |
} |
| 480 |
s = trim(s[1:]) |
| 481 |
if i := strings.LastIndex(s, "."); i >= 0 { |
| 482 |
f.dllname = s[:i] |
| 483 |
f.dllfuncname = s[i+1:] |
| 484 |
} else { |
| 485 |
f.dllfuncname = s |
| 486 |
} |
| 487 |
if f.dllfuncname == "" { |
| 488 |
return nil, fmt.Errorf("function name is not specified in %q", s) |
| 489 |
} |
| 490 |
if n := f.dllfuncname; strings.HasSuffix(n, "?") { |
| 491 |
f.dllfuncname = n[:len(n)-1] |
| 492 |
f.Rets.fnMaybeAbsent = true |
| 493 |
} |
| 494 |
return f, nil |
| 495 |
} |
| 496 |
|
| 497 |
// DLLName returns DLL name for function f. |
| 498 |
func (f *Fn) DLLName() string { |
| 499 |
if f.dllname == "" { |
| 500 |
return "kernel32" |
| 501 |
} |
| 502 |
return f.dllname |
| 503 |
} |
| 504 |
|
| 505 |
// DLLVar returns a valid Go identifier that represents DLLName. |
| 506 |
func (f *Fn) DLLVar() string { |
| 507 |
id := strings.Map(func(r rune) rune { |
| 508 |
switch r { |
| 509 |
case '.', '-': |
| 510 |
return '_' |
| 511 |
default: |
| 512 |
return r |
| 513 |
} |
| 514 |
}, f.DLLName()) |
| 515 |
if !token.IsIdentifier(id) { |
| 516 |
panic(fmt.Errorf("could not create Go identifier for DLLName %q", f.DLLName())) |
| 517 |
} |
| 518 |
return id |
| 519 |
} |
| 520 |
|
| 521 |
// DLLFuncName returns DLL function name for function f. |
| 522 |
func (f *Fn) DLLFuncName() string { |
| 523 |
if f.dllfuncname == "" { |
| 524 |
return f.Name |
| 525 |
} |
| 526 |
return f.dllfuncname |
| 527 |
} |
| 528 |
|
| 529 |
// ParamList returns source code for function f parameters. |
| 530 |
func (f *Fn) ParamList() string { |
| 531 |
return join(f.Params, func(p *Param) string { return p.Name + " " + p.Type }, ", ") |
| 532 |
} |
| 533 |
|
| 534 |
// HelperParamList returns source code for helper function f parameters. |
| 535 |
func (f *Fn) HelperParamList() string { |
| 536 |
return join(f.Params, func(p *Param) string { return p.Name + " " + p.HelperType() }, ", ") |
| 537 |
} |
| 538 |
|
| 539 |
// ParamPrintList returns source code of trace printing part correspondent |
| 540 |
// to syscall input parameters. |
| 541 |
func (f *Fn) ParamPrintList() string { |
| 542 |
return join(f.Params, func(p *Param) string { return fmt.Sprintf(`"%s=", %s, `, p.Name, p.Name) }, `", ", `) |
| 543 |
} |
| 544 |
|
| 545 |
// SyscallN returns a string representing the SyscallN function. |
| 546 |
func (f *Fn) SyscallN() string { |
| 547 |
return syscalldot() + "SyscallN" |
| 548 |
} |
| 549 |
|
| 550 |
// SyscallParamList returns source code for SyscallX parameters for function f. |
| 551 |
func (f *Fn) SyscallParamList() string { |
| 552 |
a := make([]string, 0) |
| 553 |
for _, p := range f.Params { |
| 554 |
a = append(a, p.SyscallArgList()...) |
| 555 |
} |
| 556 |
|
| 557 |
// Check if the number exceeds the current SyscallN limit |
| 558 |
if len(a) > 42 { |
| 559 |
panic("too many arguments to system call") |
| 560 |
} |
| 561 |
|
| 562 |
return strings.Join(a, ", ") |
| 563 |
} |
| 564 |
|
| 565 |
// HelperCallParamList returns source code of call into function f helper. |
| 566 |
func (f *Fn) HelperCallParamList() string { |
| 567 |
a := make([]string, 0, len(f.Params)) |
| 568 |
for _, p := range f.Params { |
| 569 |
s := p.Name |
| 570 |
if p.Type == "string" { |
| 571 |
s = p.tmpVar() |
| 572 |
} |
| 573 |
a = append(a, s) |
| 574 |
} |
| 575 |
return strings.Join(a, ", ") |
| 576 |
} |
| 577 |
|
| 578 |
// MaybeAbsent returns source code for handling functions that are possibly unavailable. |
| 579 |
func (p *Fn) MaybeAbsent() string { |
| 580 |
if !p.Rets.fnMaybeAbsent { |
| 581 |
return "" |
| 582 |
} |
| 583 |
const code = `%[1]s = proc%[2]s.Find() |
| 584 |
if %[1]s != nil { |
| 585 |
return |
| 586 |
}` |
| 587 |
errorVar := p.Rets.ErrorVarName() |
| 588 |
if errorVar == "" { |
| 589 |
errorVar = "err" |
| 590 |
} |
| 591 |
return fmt.Sprintf(code, errorVar, p.DLLFuncName()) |
| 592 |
} |
| 593 |
|
| 594 |
// IsUTF16 is true, if f is W (utf16) function. It is false |
| 595 |
// for all A (ascii) functions. |
| 596 |
func (f *Fn) IsUTF16() bool { |
| 597 |
s := f.DLLFuncName() |
| 598 |
return s[len(s)-1] == 'W' |
| 599 |
} |
| 600 |
|
| 601 |
// StrconvFunc returns name of Go string to OS string function for f. |
| 602 |
func (f *Fn) StrconvFunc() string { |
| 603 |
if f.IsUTF16() { |
| 604 |
return syscalldot() + "UTF16PtrFromString" |
| 605 |
} |
| 606 |
return syscalldot() + "BytePtrFromString" |
| 607 |
} |
| 608 |
|
| 609 |
// StrconvType returns Go type name used for OS string for f. |
| 610 |
func (f *Fn) StrconvType() string { |
| 611 |
if f.IsUTF16() { |
| 612 |
return "*uint16" |
| 613 |
} |
| 614 |
return "*byte" |
| 615 |
} |
| 616 |
|
| 617 |
// HasStringParam is true, if f has at least one string parameter. |
| 618 |
// Otherwise it is false. |
| 619 |
func (f *Fn) HasStringParam() bool { |
| 620 |
for _, p := range f.Params { |
| 621 |
if p.Type == "string" { |
| 622 |
return true |
| 623 |
} |
| 624 |
} |
| 625 |
return false |
| 626 |
} |
| 627 |
|
| 628 |
// HelperName returns name of function f helper. |
| 629 |
func (f *Fn) HelperName() string { |
| 630 |
if !f.HasStringParam() { |
| 631 |
return f.Name |
| 632 |
} |
| 633 |
return "_" + f.Name |
| 634 |
} |
| 635 |
|
| 636 |
// DLL is a DLL's filename and a string that is valid in a Go identifier that should be used when |
| 637 |
// naming a variable that refers to the DLL. |
| 638 |
type DLL struct { |
| 639 |
Name string |
| 640 |
Var string |
| 641 |
} |
| 642 |
|
| 643 |
// Source files and functions. |
| 644 |
type Source struct { |
| 645 |
Funcs []*Fn |
| 646 |
DLLFuncNames []*Fn |
| 647 |
Files []string |
| 648 |
StdLibImports []string |
| 649 |
ExternalImports []string |
| 650 |
} |
| 651 |
|
| 652 |
func (src *Source) Import(pkg string) { |
| 653 |
src.StdLibImports = append(src.StdLibImports, pkg) |
| 654 |
sort.Strings(src.StdLibImports) |
| 655 |
} |
| 656 |
|
| 657 |
func (src *Source) ExternalImport(pkg string) { |
| 658 |
src.ExternalImports = append(src.ExternalImports, pkg) |
| 659 |
sort.Strings(src.ExternalImports) |
| 660 |
} |
| 661 |
|
| 662 |
// ParseFiles parses files listed in fs and extracts all syscall |
| 663 |
// functions listed in sys comments. It returns source files |
| 664 |
// and functions collection *Source if successful. |
| 665 |
func ParseFiles(fs []string) (*Source, error) { |
| 666 |
src := &Source{ |
| 667 |
Funcs: make([]*Fn, 0), |
| 668 |
Files: make([]string, 0), |
| 669 |
StdLibImports: []string{ |
| 670 |
"unsafe", |
| 671 |
}, |
| 672 |
ExternalImports: make([]string, 0), |
| 673 |
} |
| 674 |
for _, file := range fs { |
| 675 |
if err := src.ParseFile(file); err != nil { |
| 676 |
return nil, err |
| 677 |
} |
| 678 |
} |
| 679 |
src.DLLFuncNames = make([]*Fn, 0, len(src.Funcs)) |
| 680 |
uniq := make(map[string]bool, len(src.Funcs)) |
| 681 |
for _, fn := range src.Funcs { |
| 682 |
name := fn.DLLFuncName() |
| 683 |
if !uniq[name] { |
| 684 |
src.DLLFuncNames = append(src.DLLFuncNames, fn) |
| 685 |
uniq[name] = true |
| 686 |
} |
| 687 |
} |
| 688 |
return src, nil |
| 689 |
} |
| 690 |
|
| 691 |
// DLLs return dll names for a source set src. |
| 692 |
func (src *Source) DLLs() []DLL { |
| 693 |
uniq := make(map[string]bool) |
| 694 |
r := make([]DLL, 0) |
| 695 |
for _, f := range src.Funcs { |
| 696 |
id := f.DLLVar() |
| 697 |
if _, found := uniq[id]; !found { |
| 698 |
uniq[id] = true |
| 699 |
r = append(r, DLL{f.DLLName(), id}) |
| 700 |
} |
| 701 |
} |
| 702 |
sort.Slice(r, func(i, j int) bool { |
| 703 |
return r[i].Var < r[j].Var |
| 704 |
}) |
| 705 |
return r |
| 706 |
} |
| 707 |
|
| 708 |
// ParseFile adds additional file path to a source set src. |
| 709 |
func (src *Source) ParseFile(path string) error { |
| 710 |
file, err := os.Open(path) |
| 711 |
if err != nil { |
| 712 |
return err |
| 713 |
} |
| 714 |
defer file.Close() |
| 715 |
|
| 716 |
s := bufio.NewScanner(file) |
| 717 |
for s.Scan() { |
| 718 |
t := trim(s.Text()) |
| 719 |
if len(t) < 7 { |
| 720 |
continue |
| 721 |
} |
| 722 |
if !strings.HasPrefix(t, "//sys") { |
| 723 |
continue |
| 724 |
} |
| 725 |
t = t[5:] |
| 726 |
if !(t[0] == ' ' || t[0] == '\t') { |
| 727 |
continue |
| 728 |
} |
| 729 |
f, err := newFn(t[1:]) |
| 730 |
if err != nil { |
| 731 |
return err |
| 732 |
} |
| 733 |
src.Funcs = append(src.Funcs, f) |
| 734 |
} |
| 735 |
if err := s.Err(); err != nil { |
| 736 |
return err |
| 737 |
} |
| 738 |
src.Files = append(src.Files, path) |
| 739 |
sort.Slice(src.Funcs, func(i, j int) bool { |
| 740 |
fi, fj := src.Funcs[i], src.Funcs[j] |
| 741 |
if fi.DLLName() == fj.DLLName() { |
| 742 |
return fi.DLLFuncName() < fj.DLLFuncName() |
| 743 |
} |
| 744 |
return fi.DLLName() < fj.DLLName() |
| 745 |
}) |
| 746 |
|
| 747 |
// get package name |
| 748 |
fset := token.NewFileSet() |
| 749 |
_, err = file.Seek(0, 0) |
| 750 |
if err != nil { |
| 751 |
return err |
| 752 |
} |
| 753 |
pkg, err := parser.ParseFile(fset, "", file, parser.PackageClauseOnly) |
| 754 |
if err != nil { |
| 755 |
return err |
| 756 |
} |
| 757 |
packageName = pkg.Name.Name |
| 758 |
|
| 759 |
return nil |
| 760 |
} |
| 761 |
|
| 762 |
// IsStdRepo reports whether src is part of standard library. |
| 763 |
func (src *Source) IsStdRepo() (bool, error) { |
| 764 |
if len(src.Files) == 0 { |
| 765 |
return false, errors.New("no input files provided") |
| 766 |
} |
| 767 |
abspath, err := filepath.Abs(src.Files[0]) |
| 768 |
if err != nil { |
| 769 |
return false, err |
| 770 |
} |
| 771 |
goroot := runtime.GOROOT() |
| 772 |
if runtime.GOOS == "windows" { |
| 773 |
abspath = strings.ToLower(abspath) |
| 774 |
goroot = strings.ToLower(goroot) |
| 775 |
} |
| 776 |
sep := string(os.PathSeparator) |
| 777 |
if !strings.HasSuffix(goroot, sep) { |
| 778 |
goroot += sep |
| 779 |
} |
| 780 |
return strings.HasPrefix(abspath, goroot), nil |
| 781 |
} |
| 782 |
|
| 783 |
// Generate output source file from a source set src. |
| 784 |
func (src *Source) Generate(w io.Writer) error { |
| 785 |
const ( |
| 786 |
pkgStd = iota // any package in std library |
| 787 |
pkgXSysWindows // x/sys/windows package |
| 788 |
pkgOther |
| 789 |
) |
| 790 |
isStdRepo, err := src.IsStdRepo() |
| 791 |
if err != nil { |
| 792 |
return err |
| 793 |
} |
| 794 |
var pkgtype int |
| 795 |
switch { |
| 796 |
case isStdRepo: |
| 797 |
pkgtype = pkgStd |
| 798 |
case packageName == "windows": |
| 799 |
// TODO: this needs better logic than just using package name |
| 800 |
pkgtype = pkgXSysWindows |
| 801 |
default: |
| 802 |
pkgtype = pkgOther |
| 803 |
} |
| 804 |
if *systemDLL { |
| 805 |
switch pkgtype { |
| 806 |
case pkgStd: |
| 807 |
src.Import("internal/syscall/windows/sysdll") |
| 808 |
case pkgXSysWindows: |
| 809 |
default: |
| 810 |
src.ExternalImport("golang.org/x/sys/windows") |
| 811 |
} |
| 812 |
} |
| 813 |
if packageName != "syscall" { |
| 814 |
src.Import("syscall") |
| 815 |
} |
| 816 |
funcMap := template.FuncMap{ |
| 817 |
"packagename": packagename, |
| 818 |
"syscalldot": syscalldot, |
| 819 |
"newlazydll": func(dll string) string { |
| 820 |
arg := "\"" + dll + ".dll\"" |
| 821 |
if !*systemDLL { |
| 822 |
return syscalldot() + "NewLazyDLL(" + arg + ")" |
| 823 |
} |
| 824 |
switch pkgtype { |
| 825 |
case pkgStd: |
| 826 |
return syscalldot() + "NewLazyDLL(sysdll.Add(" + arg + "))" |
| 827 |
case pkgXSysWindows: |
| 828 |
return "NewLazySystemDLL(" + arg + ")" |
| 829 |
default: |
| 830 |
return "windows.NewLazySystemDLL(" + arg + ")" |
| 831 |
} |
| 832 |
}, |
| 833 |
} |
| 834 |
t := template.Must(template.New("main").Funcs(funcMap).Parse(srcTemplate)) |
| 835 |
err = t.Execute(w, src) |
| 836 |
if err != nil { |
| 837 |
return errors.New("Failed to execute template: " + err.Error()) |
| 838 |
} |
| 839 |
return nil |
| 840 |
} |
| 841 |
|
| 842 |
func writeTempSourceFile(data []byte) (string, error) { |
| 843 |
f, err := os.CreateTemp("", "mkwinsyscall-generated-*.go") |
| 844 |
if err != nil { |
| 845 |
return "", err |
| 846 |
} |
| 847 |
_, err = f.Write(data) |
| 848 |
if closeErr := f.Close(); err == nil { |
| 849 |
err = closeErr |
| 850 |
} |
| 851 |
if err != nil { |
| 852 |
os.Remove(f.Name()) // best effort |
| 853 |
return "", err |
| 854 |
} |
| 855 |
return f.Name(), nil |
| 856 |
} |
| 857 |
|
| 858 |
func usage() { |
| 859 |
fmt.Fprintf(os.Stderr, "usage: mkwinsyscall [flags] [path ...]\n") |
| 860 |
flag.PrintDefaults() |
| 861 |
os.Exit(1) |
| 862 |
} |
| 863 |
|
| 864 |
func main() { |
| 865 |
flag.Usage = usage |
| 866 |
flag.Parse() |
| 867 |
if len(flag.Args()) <= 0 { |
| 868 |
fmt.Fprintf(os.Stderr, "no files to parse provided\n") |
| 869 |
usage() |
| 870 |
} |
| 871 |
|
| 872 |
src, err := ParseFiles(flag.Args()) |
| 873 |
if err != nil { |
| 874 |
log.Fatal(err) |
| 875 |
} |
| 876 |
|
| 877 |
var buf bytes.Buffer |
| 878 |
if err := src.Generate(&buf); err != nil { |
| 879 |
log.Fatal(err) |
| 880 |
} |
| 881 |
|
| 882 |
data, err := format.Source(buf.Bytes()) |
| 883 |
if err != nil { |
| 884 |
log.Printf("failed to format source: %v", err) |
| 885 |
f, err := writeTempSourceFile(buf.Bytes()) |
| 886 |
if err != nil { |
| 887 |
log.Fatalf("failed to write unformatted source to file: %v", err) |
| 888 |
} |
| 889 |
log.Fatalf("for diagnosis, wrote unformatted source to %v", f) |
| 890 |
} |
| 891 |
if *filename == "" { |
| 892 |
_, err = os.Stdout.Write(data) |
| 893 |
} else { |
| 894 |
err = os.WriteFile(*filename, data, 0644) |
| 895 |
} |
| 896 |
if err != nil { |
| 897 |
log.Fatal(err) |
| 898 |
} |
| 899 |
} |
| 900 |
|
| 901 |
// TODO: use println instead to print in the following template |
| 902 |
const srcTemplate = ` |
| 903 |
|
| 904 |
{{define "main"}}// Code generated by 'go generate'; DO NOT EDIT. |
| 905 |
|
| 906 |
package {{packagename}} |
| 907 |
|
| 908 |
import ( |
| 909 |
{{range .StdLibImports}}"{{.}}" |
| 910 |
{{end}} |
| 911 |
|
| 912 |
{{range .ExternalImports}}"{{.}}" |
| 913 |
{{end}} |
| 914 |
) |
| 915 |
|
| 916 |
var _ unsafe.Pointer |
| 917 |
|
| 918 |
// Do the interface allocations only once for common |
| 919 |
// Errno values. |
| 920 |
const ( |
| 921 |
errnoERROR_IO_PENDING = 997 |
| 922 |
) |
| 923 |
|
| 924 |
var ( |
| 925 |
errERROR_IO_PENDING error = {{syscalldot}}Errno(errnoERROR_IO_PENDING) |
| 926 |
errERROR_EINVAL error = {{syscalldot}}EINVAL |
| 927 |
) |
| 928 |
|
| 929 |
// errnoErr returns common boxed Errno values, to prevent |
| 930 |
// allocations at runtime. |
| 931 |
func errnoErr(e {{syscalldot}}Errno) error { |
| 932 |
switch e { |
| 933 |
case 0: |
| 934 |
return errERROR_EINVAL |
| 935 |
case errnoERROR_IO_PENDING: |
| 936 |
return errERROR_IO_PENDING |
| 937 |
} |
| 938 |
// TODO: add more here, after collecting data on the common |
| 939 |
// error values see on Windows. (perhaps when running |
| 940 |
// all.bat?) |
| 941 |
return e |
| 942 |
} |
| 943 |
|
| 944 |
var ( |
| 945 |
{{template "dlls" .}} |
| 946 |
{{template "funcnames" .}}) |
| 947 |
{{range .Funcs}}{{if .HasStringParam}}{{template "helperbody" .}}{{end}}{{template "funcbody" .}}{{end}} |
| 948 |
{{end}} |
| 949 |
|
| 950 |
{{/* help functions */}} |
| 951 |
|
| 952 |
{{define "dlls"}}{{range .DLLs}} mod{{.Var}} = {{newlazydll .Name}} |
| 953 |
{{end}}{{end}} |
| 954 |
|
| 955 |
{{define "funcnames"}}{{range .DLLFuncNames}} proc{{.DLLFuncName}} = mod{{.DLLVar}}.NewProc("{{.DLLFuncName}}") |
| 956 |
{{end}}{{end}} |
| 957 |
|
| 958 |
{{define "helperbody"}} |
| 959 |
func {{.Name}}({{.ParamList}}) {{template "results" .}}{ |
| 960 |
{{template "helpertmpvars" .}} return {{.HelperName}}({{.HelperCallParamList}}) |
| 961 |
} |
| 962 |
{{end}} |
| 963 |
|
| 964 |
{{define "funcbody"}} |
| 965 |
func {{.HelperName}}({{.HelperParamList}}) {{template "results" .}}{ |
| 966 |
{{template "maybeabsent" .}} {{template "tmpvars" .}} {{template "syscall" .}} {{template "tmpvarsreadback" .}} |
| 967 |
{{template "seterror" .}}{{template "printtrace" .}} return |
| 968 |
} |
| 969 |
{{end}} |
| 970 |
|
| 971 |
{{define "helpertmpvars"}}{{range .Params}}{{if .TmpVarHelperCode}} {{.TmpVarHelperCode}} |
| 972 |
{{end}}{{end}}{{end}} |
| 973 |
|
| 974 |
{{define "maybeabsent"}}{{if .MaybeAbsent}}{{.MaybeAbsent}} |
| 975 |
{{end}}{{end}} |
| 976 |
|
| 977 |
{{define "tmpvars"}}{{range .Params}}{{if .TmpVarCode}} {{.TmpVarCode}} |
| 978 |
{{end}}{{end}}{{end}} |
| 979 |
|
| 980 |
{{define "results"}}{{if .Rets.List}}{{.Rets.List}} {{end}}{{end}} |
| 981 |
|
| 982 |
{{define "syscall"}}{{.Rets.SetReturnValuesCode}}{{.SyscallN}}(proc{{.DLLFuncName}}.Addr(), {{.SyscallParamList}}){{end}} |
| 983 |
|
| 984 |
{{define "tmpvarsreadback"}}{{range .Params}}{{if .TmpVarReadbackCode}} |
| 985 |
{{.TmpVarReadbackCode}}{{end}}{{end}}{{end}} |
| 986 |
|
| 987 |
{{define "seterror"}}{{if .Rets.SetErrorCode}} {{.Rets.SetErrorCode}} |
| 988 |
{{end}}{{end}} |
| 989 |
|
| 990 |
{{define "printtrace"}}{{if .PrintTrace}} print("SYSCALL: {{.Name}}(", {{.ParamPrintList}}") (", {{.Rets.PrintList}}")\n") |
| 991 |
{{end}}{{end}} |
| 992 |
|
| 993 |
` |