mksyscall_windows.go 22 KB

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