summaryrefslogtreecommitdiffhomepage
path: root/cmd/parse-syscall-annotations/main.go
blob: 0b7954a6c769487bfe09c1ab258ed8f7cafc546c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This program will take a single golang source file, or a directory containing
// many source files and produce a JSON output which represent any comments
// containing compatibility metadata.

// Command parse-syscall-annotations parses syscall annotations from Godoc and
// generates a JSON file with the parsed syscall info.
//
// Annotations take the form:
// @Syscall(<name>, <arg>:<value>, ...)
//
// Supported args and values are:
// - arg: A syscall option. This entry only applies to the syscall when given this option.
// - support: Indicates support level
//   - FULL: Full support
//   - PARTIAL: Partial support. Details should be provided in note.
//   - UNIMPLEMENTED: Unimplemented
// - returns: Indicates a known return value. Implies PARTIAL support. Values are syscall errors.
//            This is treated as a string so you can use something like "returns:EPERM or ENOSYS".
// - issue: A GitHub issue number.
// - note: A note

package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
	"text/template"
)

var (
	srcDir  = flag.String("dir", "./", "The source directory")
	jsonOut = flag.Bool("json", false, "Output info as json")

	r  *regexp.Regexp
	r2 *regexp.Regexp

	mdTemplate = template.Must(template.New("name").Parse(`+++
title = "Syscall Reference"
description = "Syscall Compatibility Reference Documentation"
weight = 10
+++

This table is a reference of Linux syscalls and their compatibility status in
gVisor. gVisor does not support all syscalls and some syscalls may have a
partial implementation.

Of {{ .Total }} syscalls, {{ .Implemented }} syscalls have a full or partial
implementation. There are currently {{ .Unimplemented }} unimplemented
syscalls. {{ .Unknown }} syscalls are not yet documented.

<table>
  <thead>
    <tr>
      <th>#</th>
      <th>Name</th>
      <th>Support</th>
      <th>GitHub Issue</th>
      <th>Notes</th>
    </tr>
  </thead>
  <tbody>{{ range .Syscalls }}{{ if ne .Support "Unknown" }}
    <tr>
      <td><a class="doc-table-anchor" id="{{ .Name }}{{ if index .Metadata "arg" }}({{ index .Metadata "arg" }}){{ end }}"></a>{{ .Number }}</td>
      <td><a href="http://man7.org/linux/man-pages/man2/{{ .Name }}.2.html" target="_blank" rel="noopener">{{ .Name }}{{ if index .Metadata "arg" }}({{ index .Metadata "arg" }}){{ end }}</a></td>
      <td>{{ .Support }}</td>
      <td>{{ if index .Metadata "issue" }}<a href="https://github.com/google/gvisor/issues/{{ index .Metadata "issue" }}">#{{ index .Metadata "issue" }}</a>{{ end }}</td>
      <td>{{ .Note }}</td>
    </tr>{{ end }}{{ end }}
  </tbody>
</table>
`))
)

// Syscall represents a function implementation of a syscall.
type Syscall struct {
	File string
	Line int

	Number int
	Name   string

	Metadata map[string]string
}

const (
	UNKNOWN = iota
	UNIMPLEMENTED
	PARTIAL_SUPPORT
	FULL_SUPPORT
)

func (s *Syscall) SupportLevel() int {
	supportLevel := UNKNOWN
	switch strings.ToUpper(s.Metadata["support"]) {
	case "FULL":
		supportLevel = FULL_SUPPORT
	case "PARTIAL":
		supportLevel = PARTIAL_SUPPORT
	case "UNIMPLEMENTED":
		supportLevel = UNIMPLEMENTED
	}

	// If an arg or returns is specifed treat that as a partial implementation even if
	// there is full support for the argument.
	if s.Metadata["arg"] != "" {
		supportLevel = PARTIAL_SUPPORT
	}
	if s.Metadata["returns"] != "" && supportLevel == UNKNOWN {
		returns := strings.ToUpper(s.Metadata["returns"])
		// Default to PARTIAL support if only returns is specified
		supportLevel = PARTIAL_SUPPORT

		// If ENOSYS is returned unequivically, treat it as unimplemented.
		if returns == "ENOSYS" {
			supportLevel = UNIMPLEMENTED
		}
	}

	return supportLevel
}

func (s *Syscall) Support() string {
	l := s.SupportLevel()
	switch l {
	case FULL_SUPPORT:
		return "Full"
	case PARTIAL_SUPPORT:
		return "Partial"
	case UNIMPLEMENTED:
		return "Unimplemented"
	default:
		return "Unknown"
	}
}

func (s *Syscall) Note() string {
	note := s.Metadata["note"]
	returns := s.Metadata["returns"]
	// Add "Returns ENOSYS" note by default if support:UNIMPLEMENTED
	if returns == "" && s.SupportLevel() == UNIMPLEMENTED {
		returns = "ENOSYS"
	}
	if returns != "" {
		return_note := fmt.Sprintf("Returns %s", returns)
		if note != "" {
			note = return_note + "; " + note
		} else {
			note = return_note
		}
	}
	if note == "" && s.SupportLevel() == FULL_SUPPORT {
		note = "Full Support"
	}
	return note
}

type Report struct {
	Implemented   int
	Unimplemented int
	Unknown       int
	Total         int
	Syscalls      []*Syscall
}

func init() {
	// Build a regex that will attempt to match all fields in tokens.

	// Regexp for matching syscall definitions
	s := "@Syscall\\(([^\\),]+)([^\\)]+)\\)"
	r = regexp.MustCompile(s)

	// Regexp for matching metadata
	s2 := "([^\\ ),]+):([^\\),]+)"
	r2 = regexp.MustCompile(s2)

	ReverseSyscallMap = make(map[string]int)
	for no, name := range SyscallMap {
		ReverseSyscallMap[name] = no
	}
}

// parseDoc parses all comments in a file and returns the parsed syscall
// information.
func parseDoc(fs *token.FileSet, f *ast.File) []*Syscall {
	syscalls := []*Syscall{}
	for _, cg := range f.Comments {
		for _, line := range strings.Split(cg.Text(), "\n") {
			if syscall := parseLine(fs, line); syscall != nil {
				pos := fs.Position(cg.Pos())
				syscall.File = pos.Filename
				syscall.Line = pos.Line

				syscalls = append(syscalls, syscall)
			}
		}
	}
	return syscalls
}

// parseLine parses a single line of Godoc and returns the parsed syscall
// information. If no information is found, nil is returned.
// Syscall declarations take the form:
// @Syscall(<name>, <verb>:<value>, ...)
func parseLine(fs *token.FileSet, line string) *Syscall {
	s := r.FindAllStringSubmatch(line, -1)
	if len(s) > 0 {
		name := strings.ToLower(s[0][1])
		if n, ok := ReverseSyscallMap[name]; ok {
			syscall := Syscall{}
			syscall.Name = name
			syscall.Number = n
			syscall.Metadata = make(map[string]string)
			s2 := r2.FindAllStringSubmatch(s[0][2], -1)
			for _, match := range s2 {
				syscall.Metadata[match[1]] = match[2]
			}
			return &syscall
		} else {
			log.Printf("Warning: unknown syscall %q", name)
		}
	}
	return nil
}

func main() {
	flag.Parse()

	var syscalls []*Syscall

	err := filepath.Walk(*srcDir, func(path string, info os.FileInfo, err error) error {
		if info != nil && info.IsDir() {
			fs := token.NewFileSet()
			d, err := parser.ParseDir(fs, path, nil, parser.ParseComments)
			if err != nil {
				return err
			}

			for _, p := range d {
				for _, f := range p.Files {
					s := parseDoc(fs, f)
					syscalls = append(syscalls, s...)
				}
			}
		}

		return nil
	})

	if err != nil {
		fmt.Printf("failed to walk dir %s: %v", *srcDir, err)
		os.Exit(1)
	}

	var fullList []*Syscall
	for no, name := range SyscallMap {
		found := false
		for _, s := range syscalls {
			if s.Number == no {
				fullList = append(fullList, s)
				found = true
			}
		}
		if !found {
			fullList = append(fullList, &Syscall{
				Name:   name,
				Number: no,
			})
		}
	}

	// Sort the syscalls by number.
	sort.Slice(fullList, func(i, j int) bool {
		return fullList[i].Number < fullList[j].Number
	})

	if *jsonOut {
		j, err := json.Marshal(fullList)
		if err != nil {
			fmt.Printf("failed to marshal JSON: %v", err)
			os.Exit(1)
		}
		os.Stdout.Write(j)
		return
	}

	// Count syscalls and group by syscall number and support level
	supportMap := map[int]int{}
	for _, s := range fullList {
		supportLevel := s.SupportLevel()

		// If we already have set a higher level of support
		// keep the current value
		if current, ok := supportMap[s.Number]; ok && supportLevel < current {
			continue
		}

		supportMap[s.Number] = supportLevel
	}
	report := Report{
		Syscalls: fullList,
	}
	for _, s := range supportMap {
		switch s {
		case FULL_SUPPORT:
			report.Implemented += 1
		case PARTIAL_SUPPORT:
			report.Implemented += 1
		case UNIMPLEMENTED:
			report.Unimplemented += 1
		case UNKNOWN:
			report.Unknown += 1
		}
		report.Total += 1
	}

	err = mdTemplate.Execute(os.Stdout, report)
	if err != nil {
		fmt.Printf("failed to execute template: %v", err)
		os.Exit(1)
		return
	}
}