Debian Codegraph @

tools/mkwinsyscall/mkwinsyscall.go

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