How to use check method of compiler Package

Best Syzkaller code snippet using compiler.check

compiler.go

Source:compiler.go Github

copy

Full Screen

...118 }119 }120 return compiler.text[compiler.curr]121}122func (compiler *compiler) check(tt scanner.TokenType) bool {123 return compiler.current().Type == tt124}125func (compiler *compiler) declaration() Node {126 var state Node127 switch compiler.current().Type {128 case scanner.TokenGlobal:129 state = compiler.global()130 case scanner.TokenLocal:131 state = compiler.local()132 default:133 state = compiler.statement()134 }135 // Lua allows semicolons but they are not required136 if compiler.check(scanner.TokenSemicolon) {137 compiler.consume(scanner.TokenSemicolon)138 }139 return state140}141func (compiler *compiler) global() Node {142 compiler.consume(scanner.TokenGlobal)143 return compiler.variableDeclaration(func(names []Identifier, values []Node) Node {144 return GlobalDeclaration{145 names: names,146 values: values,147 }148 })149}150func (compiler *compiler) local() Node {151 compiler.consume(scanner.TokenLocal)152 return compiler.variableDeclaration(func(names []Identifier, values []Node) Node {153 return LocalDeclaration{154 names: names,155 values: values,156 }157 })158}159func (compiler *compiler) variableDeclaration(constructor func([]Identifier, []Node) Node) Node {160 names := []Identifier{compiler.identifier()}161 for compiler.check(scanner.TokenComma) {162 compiler.consume(scanner.TokenComma)163 names = append(names, compiler.identifier())164 }165 if !compiler.check(scanner.TokenEqual) {166 return constructor(names, nil)167 }168 compiler.consume(scanner.TokenEqual)169 values := []Node{compiler.rightHandSideExpression()}170 for compiler.check(scanner.TokenComma) {171 values = append(values, compiler.rightHandSideExpression())172 }173 return constructor(names, values)174}175func (compiler *compiler) statement() Node {176 switch compiler.current().Type {177 case scanner.TokenAssert:178 compiler.consume(scanner.TokenAssert)179 return AssertStatement{180 value: compiler.expression(),181 }182 case scanner.TokenFunction:183 return compiler.function()184 case scanner.TokenWhile:185 return compiler.whileStatement()186 case scanner.TokenFor:187 return compiler.forStatement()188 case scanner.TokenIf:189 return compiler.ifStatement()190 case scanner.TokenDo:191 compiler.consume(scanner.TokenDo)192 block := compiler.block()193 compiler.consume(scanner.TokenEnd)194 return block195 case scanner.TokenReturn:196 return compiler.returnStatement()197 default:198 return compiler.assignment()199 }200}201func (compiler *compiler) function() Node {202 compiler.consume(scanner.TokenFunction)203 name := compiler.identifier()204 parameters := compiler.parameters()205 var declarations []Node206 // todo: better error messages about non-terminated function207 for !compiler.check(scanner.TokenEnd) && !compiler.check(scanner.TokenEof) {208 declarations = append(declarations, compiler.declaration())209 }210 compiler.consume(scanner.TokenEnd)211 var body Node212 if len(declarations) == 1 {213 body = declarations[0]214 } else {215 body = BlockStatement{declarations}216 }217 return FunctionNode{name, parameters, body}218}219func (compiler *compiler) parameters() []Identifier {220 compiler.consume(scanner.TokenLeftParen)221 var identifiers []Identifier222 for !compiler.check(scanner.TokenEof) && !compiler.check(scanner.TokenRightParen) {223 identifiers = append(identifiers, compiler.identifier())224 if compiler.check(scanner.TokenComma) {225 compiler.consume(scanner.TokenComma)226 } else {227 break228 }229 }230 compiler.consume(scanner.TokenRightParen)231 return identifiers232}233// todo: depend on calling context for bracket words (if/then/end, while/do/end)234func (compiler *compiler) block() BlockStatement {235 var block BlockStatement236 for !compiler.terminateBlock() {237 block.statements = append(block.statements, compiler.declaration())238 }239 return block240}241// It's critical to check the type after the block so that you don't accidentally242// allow, for example: `do x = 1 then`243func (compiler *compiler) terminateBlock() bool {244 switch compiler.current().Type {245 case scanner.TokenEnd, scanner.TokenElse:246 return true247 default:248 return false249 }250}251func (compiler *compiler) whileStatement() Node {252 compiler.consume(scanner.TokenWhile)253 expression := compiler.expression()254 compiler.consume(scanner.TokenDo)255 body := compiler.block()256 compiler.consume(scanner.TokenEnd)257 return WhileStatement{258 condition: expression,259 body: body,260 }261}262func (compiler *compiler) forStatement() Node {263 compiler.consume(scanner.TokenFor)264 variable := compiler.identifier()265 if compiler.check(scanner.TokenEqual) {266 return compiler.numericFor(variable)267 } else if compiler.check(scanner.TokenComma) || compiler.check(scanner.TokenIn) {268 return compiler.genericFor(variable)269 } else {270 compiler.error("Expected '=' or 'in' in for statement.")271 return NumericForStatement{variable, nil, nil}272 }273}274func (compiler *compiler) genericFor(variable Identifier) Node {275 targets := []Identifier{variable}276 for compiler.check(scanner.TokenComma) {277 compiler.consume(scanner.TokenComma)278 targets = append(targets, compiler.identifier())279 }280 compiler.consume(scanner.TokenIn)281 // Use rightHandSideExpression because we actually do a282 // multiple assignment with these283 iterator := []Node{compiler.rightHandSideExpression()}284 for compiler.check(scanner.TokenComma) {285 compiler.consume(scanner.TokenComma)286 iterator = append(iterator, compiler.rightHandSideExpression())287 }288 compiler.consume(scanner.TokenDo)289 body := compiler.block()290 compiler.consume(scanner.TokenEnd)291 return GenericForStatement{292 targets: targets,293 iterator: iterator,294 body: body,295 }296}297func (compiler *compiler) numericFor(variable Identifier) Node {298 compiler.consume(scanner.TokenEqual)299 // Doesn't use rightHandSideExpression because we only300 // use the first return from any calls in this position301 values := []Node{compiler.expression()}302 for compiler.check(scanner.TokenComma) {303 compiler.consume(scanner.TokenComma)304 values = append(values, compiler.expression())305 }306 compiler.consume(scanner.TokenDo)307 body := compiler.block()308 compiler.consume(scanner.TokenEnd)309 return NumericForStatement{310 variable: variable,311 values: values,312 body: body,313 }314}315func (compiler *compiler) ifStatement() Node {316 compiler.consume(scanner.TokenIf)317 condition := compiler.expression()318 compiler.consume(scanner.TokenThen)319 body := compiler.block()320 if compiler.check(scanner.TokenElse) {321 compiler.consume(scanner.TokenElse)322 counterfactual := compiler.block()323 compiler.consume(scanner.TokenEnd)324 return IfStatement{325 condition: condition,326 body: body,327 counterfactual: counterfactual,328 }329 } else {330 compiler.consume(scanner.TokenEnd)331 return IfStatement{332 condition: condition,333 body: body,334 }335 }336}337func (compiler *compiler) returnStatement() Node {338 compiler.consume(scanner.TokenReturn)339 if compiler.check(scanner.TokenEnd) || compiler.check(scanner.TokenElse) {340 return ReturnStatement{341 arity: 1,342 values: []Node{NilPrimary()},343 }344 }345 var expressions []Node = []Node{compiler.expression()}346 for compiler.check(scanner.TokenComma) {347 compiler.consume(scanner.TokenComma)348 expressions = append(expressions, compiler.expression())349 }350 // todo: overflow351 return ReturnStatement{352 arity: byte(len(expressions)),353 values: expressions,354 }355}356func (compiler *compiler) assignment() Node {357 expression := compiler.expression()358 if compiler.check(scanner.TokenEqual) || compiler.check(scanner.TokenComma) {359 return compiler.multipleAssignment(expression)360 } else {361 return Expression{expression: expression}362 }363}364func (compiler *compiler) multipleAssignment(node Node) Node {365 // add all variables plus passed-in node to list366 variables := []Node{node}367 for compiler.check(scanner.TokenComma) {368 compiler.consume(scanner.TokenComma)369 // todo: actually allow assignment to expression if it resolves a variable???370 variables = append(variables, compiler.expression())371 }372 compiler.consume(scanner.TokenEqual)373 values := []Node{compiler.rightHandSideExpression()}374 for compiler.check(scanner.TokenComma) {375 compiler.consume(scanner.TokenComma)376 expression := compiler.rightHandSideExpression()377 values = append(values, expression)378 }379 assignment := MultipleAssignment{380 variables: variables,381 values: values,382 }383 // add all expressions to right of equals to list inside assign384 return assignment385}386func (compiler *compiler) rightHandSideExpression() Node {387 expression := compiler.expression()388 switch expression.(type) {389 case *Call:390 expression.assign(nil)391 }392 return expression393}394func (compiler *compiler) identifier() Identifier {395 ident := compiler.current().Text396 compiler.consume(scanner.TokenIdentifier)397 return Identifier(ident)398}399func (compiler *compiler) expression() Node {400 return compiler.logicOr()401}402func (compiler *compiler) logicOr() Node {403 node := compiler.logicAnd()404 if compiler.current().Type != scanner.TokenOr {405 return node406 }407 lor := LogicOr{node, nil}408 for {409 if compiler.check(scanner.TokenOr) {410 compiler.advance()411 lor.or = append(lor.or, compiler.logicAnd())412 } else {413 return node414 }415 }416}417func (compiler *compiler) logicAnd() Node {418 node := compiler.comparison()419 if compiler.current().Type != scanner.TokenAnd {420 return node421 }422 land := LogicAnd{node, nil}423 for {424 if compiler.check(scanner.TokenAnd) {425 compiler.advance()426 land.and = append(land.and, compiler.comparison())427 } else {428 return land429 }430 }431}432func (compiler *compiler) comparison() Node {433 term := compiler.term()434 if !compiler.isComparison() {435 return term436 }437 compare := Comparison{term, nil}438 for compiler.isComparison() {439 token := compiler.current().Type440 compiler.advance()441 compItem := ComparisonItem{442 term: compiler.term(),443 compareOp: token,444 }445 compare.items = append(compare.items, compItem)446 }447 return compare448}449func (compiler *compiler) isComparison() bool {450 switch compiler.current().Type {451 case scanner.TokenLess, scanner.TokenGreater, scanner.TokenLessEqual,452 scanner.TokenGreaterEqual, scanner.TokenTildeEqual, scanner.TokenEqualEqual:453 return true454 default:455 return false456 }457}458func (compiler *compiler) term() Node {459 factor := compiler.factor()460 if !compiler.isTerm() {461 return factor462 }463 term := Term{factor, nil}464 for compiler.isTerm() {465 token := compiler.current().Type466 compiler.advance()467 termItem := TermItem{468 factor: compiler.factor(),469 termOp: token,470 }471 term.items = append(term.items, termItem)472 }473 return term474}475func (compiler *compiler) isTerm() bool {476 token := compiler.current().Type477 switch token {478 case scanner.TokenMinus, scanner.TokenPlus:479 return true480 default:481 return false482 }483}484func (compiler *compiler) factor() Node {485 unary := compiler.unary()486 if !compiler.isFactor() {487 return unary488 }489 factor := Factor{unary, nil}490 for compiler.isFactor() {491 token := compiler.current().Type492 compiler.advance()493 factorItem := FactorItem{494 unary: compiler.unary(),495 factorOp: token,496 }497 factor.items = append(factor.items, factorItem)498 }499 return factor500}501func (compiler *compiler) isFactor() bool {502 token := compiler.current().Type503 switch token {504 case scanner.TokenStar, scanner.TokenSlash:505 return true506 default:507 return false508 }509}510func (compiler *compiler) unary() Node {511 switch compiler.current().Type {512 case scanner.TokenMinus:513 compiler.advance()514 return NegateUnary{compiler.unary()}515 case scanner.TokenBang:516 compiler.advance()517 return NotUnary{compiler.unary()}518 default:519 return compiler.exponent()520 }521}522func (compiler *compiler) exponent() Node {523 call := compiler.call()524 if compiler.check(scanner.TokenCaret) {525 compiler.consume(scanner.TokenCaret)526 exp := compiler.call()527 return Exponent{call, &exp}528 } else {529 return call530 }531}532func (compiler *compiler) call() Node {533 primary := compiler.primary()534 for compiler.isCall() {535 switch compiler.current().Type {536 case scanner.TokenDot:537 compiler.consume(scanner.TokenDot)538 attribute := compiler.identifier()539 primary = TableAccessor{540 primary,541 StringPrimary(string(attribute)),542 }543 case scanner.TokenLeftBracket:544 compiler.consume(scanner.TokenLeftBracket)545 attribute := compiler.expression()546 compiler.consume(scanner.TokenRightBracket)547 primary = TableAccessor{548 primary,549 attribute,550 }551 case scanner.TokenLeftParen:552 args := compiler.arguments()553 primary = &Call{554 base: primary,555 arguments: args,556 isAssignment: false,557 }558 }559 }560 return primary561}562func (compiler *compiler) isCall() bool {563 switch compiler.current().Type {564 case scanner.TokenDot, scanner.TokenLeftBracket, scanner.TokenLeftParen:565 return true566 default:567 return false568 }569}570func (compiler *compiler) arguments() []Node {571 var args []Node572 compiler.consume(scanner.TokenLeftParen)573 for !compiler.check(scanner.TokenRightParen) {574 args = append(args, compiler.expression())575 if !compiler.check(scanner.TokenRightParen) {576 compiler.consume(scanner.TokenComma)577 }578 }579 compiler.consume(scanner.TokenRightParen)580 return args581}582func (compiler *compiler) primary() Node {583 switch compiler.current().Type {584 case scanner.TokenTrue:585 compiler.advance()586 return BooleanPrimary(true)587 case scanner.TokenFalse:588 compiler.advance()589 return BooleanPrimary(false)590 case scanner.TokenNumber:591 flt, err := strconv.ParseFloat(592 compiler.current().Text,593 64,594 )595 if err != nil {596 compiler.error(fmt.Sprint("Cannot parse number: ", compiler.current().Text))597 }598 compiler.advance()599 return NumberPrimary(flt)600 case scanner.TokenString:601 str := StringPrimary(compiler.current().Text)602 compiler.advance()603 return str604 case scanner.TokenNil:605 n := NilPrimary()606 compiler.advance()607 return n608 case scanner.TokenIdentifier:609 return compiler.variable()610 case scanner.TokenLeftBrace:611 return compiler.tableLiteral()612 case scanner.TokenLeftParen:613 return compiler.grouping()614 default:615 compiler.error(fmt.Sprint("Unexpected token: ", compiler.current()))616 compiler.advance()617 return NilPrimary()618 }619}620func (compiler *compiler) grouping() Node {621 compiler.consume(scanner.TokenLeftParen)622 node := compiler.expression()623 compiler.consume(scanner.TokenRightParen)624 return node625}626func (compiler *compiler) variable() Node {627 name := compiler.current().Text628 compiler.advance()629 return VariablePrimary{Identifier(name)}630}631func (compiler *compiler) getLocal(name Identifier) int {632 for i, local := range compiler.locals {633 if local.name == name {634 return i635 }636 }637 return -1638}639func (compiler *compiler) getUpvalue(name Identifier) int {640 for i, upvalue := range compiler.upvalues {641 if upvalue.name == name {642 return i643 }644 }645 if compiler.parent == nil {646 // no enclosing scope, no upvalue647 return -1648 }649 for i, local := range compiler.parent.locals {650 // this won't resolve at top level because we checked in the calling context651 if local.name == name {652 // found one, make an upvalue pointing to the local653 return compiler.makeUpvalue(name, i, true)654 }655 }656 // check the enclosing scope657 upvalue := compiler.parent.getUpvalue(name)658 if upvalue == -1 {659 // it's just a global660 return upvalue661 } else {662 // the enclosing scope has an upvalue, make an upvalue pointing at that one663 return compiler.makeUpvalue(name, upvalue, false)664 }665}666func (compiler *compiler) makeUpvalue(name Identifier, index int, isLocal bool) int {667 upvalue := len(compiler.upvalues)668 compiler.upvalues = append(compiler.upvalues, &Upvalue{669 name: name,670 index: index,671 isLocal: isLocal,672 })673 return upvalue674}675func (compiler *compiler) tableLiteral() TableLiteral {676 compiler.advance()677 var pairs []Node678 // todo: handle unterminated brace679 for compiler.current().Type != scanner.TokenRightBrace {680 pairs = append(pairs, compiler.pair())681 }682 compiler.consume(scanner.TokenRightBrace)683 return TableLiteral{pairs}684}685func (compiler *compiler) pair() Node {686 switch {687 case compiler.check(scanner.TokenLeftBracket):688 return compiler.literalPair()689 case compiler.check(scanner.TokenIdentifier) && compiler.peek().Type == scanner.TokenEqual:690 return compiler.stringPair()691 default:692 return compiler.value()693 }694}695func (compiler *compiler) literalPair() Node {696 compiler.consume(scanner.TokenLeftBracket)697 expr := compiler.expression()698 compiler.consume(scanner.TokenRightBracket)699 compiler.consume(scanner.TokenEqual)700 value := compiler.expression()701 if compiler.check(scanner.TokenComma) {702 compiler.consume(scanner.TokenComma)703 }704 return LiteralPair{705 key: expr,706 value: value,707 }708}709func (compiler *compiler) stringPair() Node {710 ident := compiler.identifier()711 compiler.consume(scanner.TokenEqual)712 expr := compiler.expression()713 if compiler.check(scanner.TokenComma) {714 compiler.consume(scanner.TokenComma)715 }716 return StringPair{717 key: StringPrimary(string(ident)),718 value: expr,719 }720}721func (compiler *compiler) value() Node {722 expr := compiler.expression()723 if compiler.check(scanner.TokenComma) {724 compiler.consume(scanner.TokenComma)725 }726 return Value{expr}727}728func (compiler *compiler) advance() {729 compiler.curr += 1730}731func (compiler *compiler) consume(tt scanner.TokenType) {732 if compiler.current().Type != tt {733 compiler.error(fmt.Sprint("Expected type ", tt, ", found ", compiler.current().Type))734 }735 compiler.advance()736}737// todo: use longer values for more constants...

Full Screen

Full Screen

cc_test.go

Source:cc_test.go Github

copy

Full Screen

1// Copyright 2017 The Go Authors. All rights reserved.2// Use of this source code is governed by a BSD-style3// license that can be found in the LICENSE file.4// sanitizers_test checks the use of Go with sanitizers like msan, asan, etc.5// See https://github.com/google/sanitizers.6package sanitizers_test7import (8 "bytes"9 "encoding/json"10 "errors"11 "fmt"12 "io/ioutil"13 "os"14 "os/exec"15 "path/filepath"16 "regexp"17 "strconv"18 "strings"19 "sync"20 "syscall"21 "testing"22 "unicode"23)24var overcommit struct {25 sync.Once26 value int27 err error28}29// requireOvercommit skips t if the kernel does not allow overcommit.30func requireOvercommit(t *testing.T) {31 t.Helper()32 overcommit.Once.Do(func() {33 var out []byte34 out, overcommit.err = ioutil.ReadFile("/proc/sys/vm/overcommit_memory")35 if overcommit.err != nil {36 return37 }38 overcommit.value, overcommit.err = strconv.Atoi(string(bytes.TrimSpace(out)))39 })40 if overcommit.err != nil {41 t.Skipf("couldn't determine vm.overcommit_memory (%v); assuming no overcommit", overcommit.err)42 }43 if overcommit.value == 2 {44 t.Skip("vm.overcommit_memory=2")45 }46}47var env struct {48 sync.Once49 m map[string]string50 err error51}52// goEnv returns the output of $(go env) as a map.53func goEnv(key string) (string, error) {54 env.Once.Do(func() {55 var out []byte56 out, env.err = exec.Command("go", "env", "-json").Output()57 if env.err != nil {58 return59 }60 env.m = make(map[string]string)61 env.err = json.Unmarshal(out, &env.m)62 })63 if env.err != nil {64 return "", env.err65 }66 v, ok := env.m[key]67 if !ok {68 return "", fmt.Errorf("`go env`: no entry for %v", key)69 }70 return v, nil71}72// replaceEnv sets the key environment variable to value in cmd.73func replaceEnv(cmd *exec.Cmd, key, value string) {74 if cmd.Env == nil {75 cmd.Env = os.Environ()76 }77 cmd.Env = append(cmd.Env, key+"="+value)78}79// mustRun executes t and fails cmd with a well-formatted message if it fails.80func mustRun(t *testing.T, cmd *exec.Cmd) {81 t.Helper()82 out, err := cmd.CombinedOutput()83 if err != nil {84 t.Fatalf("%#q exited with %v\n%s", strings.Join(cmd.Args, " "), err, out)85 }86}87// cc returns a cmd that executes `$(go env CC) $(go env GOGCCFLAGS) $args`.88func cc(args ...string) (*exec.Cmd, error) {89 CC, err := goEnv("CC")90 if err != nil {91 return nil, err92 }93 GOGCCFLAGS, err := goEnv("GOGCCFLAGS")94 if err != nil {95 return nil, err96 }97 // Split GOGCCFLAGS, respecting quoting.98 //99 // TODO(bcmills): This code also appears in100 // misc/cgo/testcarchive/carchive_test.go, and perhaps ought to go in101 // src/cmd/dist/test.go as well. Figure out where to put it so that it can be102 // shared.103 var flags []string104 quote := '\000'105 start := 0106 lastSpace := true107 backslash := false108 for i, c := range GOGCCFLAGS {109 if quote == '\000' && unicode.IsSpace(c) {110 if !lastSpace {111 flags = append(flags, GOGCCFLAGS[start:i])112 lastSpace = true113 }114 } else {115 if lastSpace {116 start = i117 lastSpace = false118 }119 if quote == '\000' && !backslash && (c == '"' || c == '\'') {120 quote = c121 backslash = false122 } else if !backslash && quote == c {123 quote = '\000'124 } else if (quote == '\000' || quote == '"') && !backslash && c == '\\' {125 backslash = true126 } else {127 backslash = false128 }129 }130 }131 if !lastSpace {132 flags = append(flags, GOGCCFLAGS[start:])133 }134 cmd := exec.Command(CC, flags...)135 cmd.Args = append(cmd.Args, args...)136 return cmd, nil137}138type version struct {139 name string140 major, minor int141}142var compiler struct {143 sync.Once144 version145 err error146}147// compilerVersion detects the version of $(go env CC).148//149// It returns a non-nil error if the compiler matches a known version schema but150// the version could not be parsed, or if $(go env CC) could not be determined.151func compilerVersion() (version, error) {152 compiler.Once.Do(func() {153 compiler.err = func() error {154 compiler.name = "unknown"155 cmd, err := cc("--version")156 if err != nil {157 return err158 }159 out, err := cmd.Output()160 if err != nil {161 // Compiler does not support "--version" flag: not Clang or GCC.162 return nil163 }164 var match [][]byte165 if bytes.HasPrefix(out, []byte("gcc")) {166 compiler.name = "gcc"167 cmd, err := cc("-dumpversion")168 if err != nil {169 return err170 }171 out, err := cmd.Output()172 if err != nil {173 // gcc, but does not support gcc's "-dumpversion" flag?!174 return err175 }176 gccRE := regexp.MustCompile(`(\d+)\.(\d+)`)177 match = gccRE.FindSubmatch(out)178 } else {179 clangRE := regexp.MustCompile(`clang version (\d+)\.(\d+)`)180 if match = clangRE.FindSubmatch(out); len(match) > 0 {181 compiler.name = "clang"182 }183 }184 if len(match) < 3 {185 return nil // "unknown"186 }187 if compiler.major, err = strconv.Atoi(string(match[1])); err != nil {188 return err189 }190 if compiler.minor, err = strconv.Atoi(string(match[2])); err != nil {191 return err192 }193 return nil194 }()195 })196 return compiler.version, compiler.err197}198type compilerCheck struct {199 once sync.Once200 err error201 skip bool // If true, skip with err instead of failing with it.202}203type config struct {204 sanitizer string205 cFlags, ldFlags, goFlags []string206 sanitizerCheck, runtimeCheck compilerCheck207}208var configs struct {209 sync.Mutex210 m map[string]*config211}212// configure returns the configuration for the given sanitizer.213func configure(sanitizer string) *config {214 configs.Lock()215 defer configs.Unlock()216 if c, ok := configs.m[sanitizer]; ok {217 return c218 }219 c := &config{220 sanitizer: sanitizer,221 cFlags: []string{"-fsanitize=" + sanitizer},222 ldFlags: []string{"-fsanitize=" + sanitizer},223 }224 if testing.Verbose() {225 c.goFlags = append(c.goFlags, "-x")226 }227 switch sanitizer {228 case "memory":229 c.goFlags = append(c.goFlags, "-msan")230 case "thread":231 c.goFlags = append(c.goFlags, "--installsuffix=tsan")232 compiler, _ := compilerVersion()233 if compiler.name == "gcc" {234 c.cFlags = append(c.cFlags, "-fPIC")235 c.ldFlags = append(c.ldFlags, "-fPIC", "-static-libtsan")236 }237 default:238 panic(fmt.Sprintf("unrecognized sanitizer: %q", sanitizer))239 }240 if configs.m == nil {241 configs.m = make(map[string]*config)242 }243 configs.m[sanitizer] = c244 return c245}246// goCmd returns a Cmd that executes "go $subcommand $args" with appropriate247// additional flags and environment.248func (c *config) goCmd(subcommand string, args ...string) *exec.Cmd {249 cmd := exec.Command("go", subcommand)250 cmd.Args = append(cmd.Args, c.goFlags...)251 cmd.Args = append(cmd.Args, args...)252 replaceEnv(cmd, "CGO_CFLAGS", strings.Join(c.cFlags, " "))253 replaceEnv(cmd, "CGO_LDFLAGS", strings.Join(c.ldFlags, " "))254 return cmd255}256// skipIfCSanitizerBroken skips t if the C compiler does not produce working257// binaries as configured.258func (c *config) skipIfCSanitizerBroken(t *testing.T) {259 check := &c.sanitizerCheck260 check.once.Do(func() {261 check.skip, check.err = c.checkCSanitizer()262 })263 if check.err != nil {264 t.Helper()265 if check.skip {266 t.Skip(check.err)267 }268 t.Fatal(check.err)269 }270}271var cMain = []byte(`272int main() {273 return 0;274}275`)276func (c *config) checkCSanitizer() (skip bool, err error) {277 dir, err := ioutil.TempDir("", c.sanitizer)278 if err != nil {279 return false, fmt.Errorf("failed to create temp directory: %v", err)280 }281 defer os.RemoveAll(dir)282 src := filepath.Join(dir, "return0.c")283 if err := ioutil.WriteFile(src, cMain, 0600); err != nil {284 return false, fmt.Errorf("failed to write C source file: %v", err)285 }286 dst := filepath.Join(dir, "return0")287 cmd, err := cc(c.cFlags...)288 if err != nil {289 return false, err290 }291 cmd.Args = append(cmd.Args, c.ldFlags...)292 cmd.Args = append(cmd.Args, "-o", dst, src)293 out, err := cmd.CombinedOutput()294 if err != nil {295 if bytes.Contains(out, []byte("-fsanitize")) &&296 (bytes.Contains(out, []byte("unrecognized")) ||297 bytes.Contains(out, []byte("unsupported"))) {298 return true, errors.New(string(out))299 }300 return true, fmt.Errorf("%#q failed: %v\n%s", strings.Join(cmd.Args, " "), err, out)301 }302 if out, err := exec.Command(dst).CombinedOutput(); err != nil {303 if os.IsNotExist(err) {304 return true, fmt.Errorf("%#q failed to produce executable: %v", strings.Join(cmd.Args, " "), err)305 }306 snippet := bytes.SplitN(out, []byte{'\n'}, 2)[0]307 return true, fmt.Errorf("%#q generated broken executable: %v\n%s", strings.Join(cmd.Args, " "), err, snippet)308 }309 return false, nil310}311// skipIfRuntimeIncompatible skips t if the Go runtime is suspected not to work312// with cgo as configured.313func (c *config) skipIfRuntimeIncompatible(t *testing.T) {314 check := &c.runtimeCheck315 check.once.Do(func() {316 check.skip, check.err = c.checkRuntime()317 })318 if check.err != nil {319 t.Helper()320 if check.skip {321 t.Skip(check.err)322 }323 t.Fatal(check.err)324 }325}326func (c *config) checkRuntime() (skip bool, err error) {327 if c.sanitizer != "thread" {328 return false, nil329 }330 // libcgo.h sets CGO_TSAN if it detects TSAN support in the C compiler.331 // Dump the preprocessor defines to check that works.332 // (Sometimes it doesn't: see https://golang.org/issue/15983.)333 cmd, err := cc(c.cFlags...)334 if err != nil {335 return false, err336 }337 cmd.Args = append(cmd.Args, "-dM", "-E", "../../../src/runtime/cgo/libcgo.h")338 cmdStr := strings.Join(cmd.Args, " ")339 out, err := cmd.CombinedOutput()340 if err != nil {341 return false, fmt.Errorf("%#q exited with %v\n%s", cmdStr, err, out)342 }343 if !bytes.Contains(out, []byte("#define CGO_TSAN")) {344 return true, fmt.Errorf("%#q did not define CGO_TSAN", cmdStr)345 }...

Full Screen

Full Screen

security_test.go

Source:security_test.go Github

copy

Full Screen

...85 {"-x", "@obj"},86}87func TestCheckCompilerFlags(t *testing.T) {88 for _, f := range goodCompilerFlags {89 if err := checkCompilerFlags("test", "test", f); err != nil {90 t.Errorf("unexpected error for %q: %v", f, err)91 }92 }93 for _, f := range badCompilerFlags {94 if err := checkCompilerFlags("test", "test", f); err == nil {95 t.Errorf("missing error for %q", f)96 }97 }98}99var goodLinkerFlags = [][]string{100 {"-Fbar"},101 {"-lbar"},102 {"-Lbar"},103 {"-fpic"},104 {"-fno-pic"},105 {"-fPIC"},106 {"-fno-PIC"},107 {"-fpie"},108 {"-fno-pie"},109 {"-fPIE"},110 {"-fno-PIE"},111 {"-fsanitize=hands"},112 {"-g"},113 {"-ggdb"},114 {"-march=souza"},115 {"-mcpu=123"},116 {"-mfpu=123"},117 {"-mtune=happybirthday"},118 {"-pic"},119 {"-pthread"},120 {"-Wl,-rpath,foo"},121 {"-Wl,-rpath,$ORIGIN/foo"},122 {"-Wl,--warn-error"},123 {"-Wl,--no-warn-error"},124 {"foo.so"},125 {"_世界.dll"},126 {"./x.o"},127 {"libcgosotest.dylib"},128 {"-F", "framework"},129 {"-l", "."},130 {"-l", "/etc/passwd"},131 {"-l", "世界"},132 {"-L", "framework"},133 {"-framework", "Chocolate"},134 {"-v"},135 {"-Wl,-framework", "-Wl,Chocolate"},136 {"-Wl,-framework,Chocolate"},137 {"-Wl,-unresolved-symbols=ignore-all"},138}139var badLinkerFlags = [][]string{140 {"-DFOO"},141 {"-Dfoo=bar"},142 {"-W"},143 {"-Wall"},144 {"-fobjc-arc"},145 {"-fno-objc-arc"},146 {"-fomit-frame-pointer"},147 {"-fno-omit-frame-pointer"},148 {"-fsplit-stack"},149 {"-fno-split-stack"},150 {"-fstack-xxx"},151 {"-fno-stack-xxx"},152 {"-mstack-overflow"},153 {"-mno-stack-overflow"},154 {"-mnop-fun-dllimport"},155 {"-std=c99"},156 {"-xc"},157 {"-D", "FOO"},158 {"-D", "foo=bar"},159 {"-I", "FOO"},160 {"-L", "@foo"},161 {"-L", "-foo"},162 {"-x", "c"},163 {"-D@X"},164 {"-D-X"},165 {"-I@dir"},166 {"-I-dir"},167 {"-O@1"},168 {"-Wa,-foo"},169 {"-W@foo"},170 {"-g@gdb"},171 {"-g-gdb"},172 {"-march=@dawn"},173 {"-march=-dawn"},174 {"-std=@c99"},175 {"-std=-c99"},176 {"-x@c"},177 {"-x-c"},178 {"-D", "@foo"},179 {"-D", "-foo"},180 {"-I", "@foo"},181 {"-I", "-foo"},182 {"-l", "@foo"},183 {"-l", "-foo"},184 {"-framework", "-Caffeine"},185 {"-framework", "@Home"},186 {"-Wl,-framework,-Caffeine"},187 {"-Wl,-framework", "-Wl,@Home"},188 {"-Wl,-framework", "@Home"},189 {"-Wl,-framework,Chocolate,@Home"},190 {"-x", "--c"},191 {"-x", "@obj"},192 {"-Wl,-rpath,@foo"},193 {"../x.o"},194}195func TestCheckLinkerFlags(t *testing.T) {196 for _, f := range goodLinkerFlags {197 if err := checkLinkerFlags("test", "test", f); err != nil {198 t.Errorf("unexpected error for %q: %v", f, err)199 }200 }201 for _, f := range badLinkerFlags {202 if err := checkLinkerFlags("test", "test", f); err == nil {203 t.Errorf("missing error for %q", f)204 }205 }206}207func TestCheckFlagAllowDisallow(t *testing.T) {208 if err := checkCompilerFlags("TEST", "test", []string{"-disallow"}); err == nil {209 t.Fatalf("missing error for -disallow")210 }211 os.Setenv("CGO_TEST_ALLOW", "-disallo")212 if err := checkCompilerFlags("TEST", "test", []string{"-disallow"}); err == nil {213 t.Fatalf("missing error for -disallow with CGO_TEST_ALLOW=-disallo")214 }215 os.Setenv("CGO_TEST_ALLOW", "-disallow")216 if err := checkCompilerFlags("TEST", "test", []string{"-disallow"}); err != nil {217 t.Fatalf("unexpected error for -disallow with CGO_TEST_ALLOW=-disallow: %v", err)218 }219 os.Unsetenv("CGO_TEST_ALLOW")220 if err := checkCompilerFlags("TEST", "test", []string{"-Wall"}); err != nil {221 t.Fatalf("unexpected error for -Wall: %v", err)222 }223 os.Setenv("CGO_TEST_DISALLOW", "-Wall")224 if err := checkCompilerFlags("TEST", "test", []string{"-Wall"}); err == nil {225 t.Fatalf("missing error for -Wall with CGO_TEST_DISALLOW=-Wall")226 }227 os.Setenv("CGO_TEST_ALLOW", "-Wall") // disallow wins228 if err := checkCompilerFlags("TEST", "test", []string{"-Wall"}); err == nil {229 t.Fatalf("missing error for -Wall with CGO_TEST_DISALLOW=-Wall and CGO_TEST_ALLOW=-Wall")230 }231 os.Setenv("CGO_TEST_ALLOW", "-fplugin.*")232 os.Setenv("CGO_TEST_DISALLOW", "-fplugin=lint.so")233 if err := checkCompilerFlags("TEST", "test", []string{"-fplugin=faster.so"}); err != nil {234 t.Fatalf("unexpected error for -fplugin=faster.so: %v", err)235 }236 if err := checkCompilerFlags("TEST", "test", []string{"-fplugin=lint.so"}); err == nil {237 t.Fatalf("missing error for -fplugin=lint.so: %v", err)238 }239}...

Full Screen

Full Screen

check

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fset := token.NewFileSet()4 f, err := parser.ParseFile(fset, "1.go", nil, parser.AllErrors)5 if err != nil {6 log.Fatal(err)7 }8 ast.Print(fset, f)9 fmt.Println("check")10 err = parser.CheckFile(fset, "1.go", nil, parser.AllErrors)11 if err != nil {12 log.Fatal(err)13 }14 fmt.Println("no error")15}16import "fmt"17func main() {18 fmt.Println("hello world")19}20Traversing the AST using ast.Inspect() method21import (22func main() {23 fset := token.NewFileSet()24 f, err := parser.ParseFile(fset, "1.go", nil, parser.AllErrors)25 if err != nil {26 log.Fatal(err)27 }28 ast.Print(fset, f)29 fmt.Println("check")30 err = parser.CheckFile(fset, "1.go", nil, parser.AllErrors)31 if err != nil {32 log.Fatal(err)33 }34 fmt.Println("no error")

Full Screen

Full Screen

check

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(reflect.TypeOf(a))4 fmt.Println(reflect.ValueOf(a).Kind())5 fmt.Println(reflect.ValueOf(a).Type())6}7import (8func main() {9 fmt.Println(reflect.TypeOf(a))10 fmt.Println(reflect.ValueOf(a).Kind())11 fmt.Println(reflect.ValueOf(a).Type())12 fmt.Println(reflect.ValueOf(a).Int())13}14import (15func main() {16 fmt.Println(reflect.TypeOf(a))17 fmt.Println(reflect.ValueOf(a).Kind())18 fmt.Println(reflect.ValueOf(a).Type())19 fmt.Println(reflect.ValueOf(a).Int())20 fmt.Println(reflect.ValueOf(a).Bool())21}22import (23func main() {24 fmt.Println(reflect.TypeOf(a))25 fmt.Println(reflect.ValueOf(a).Kind())26 fmt.Println(reflect.ValueOf(a).Type())27 fmt.Println(reflect.ValueOf(a).Int())28 fmt.Println(reflect.ValueOf(a).Bool())29 fmt.Println(reflect.ValueOf(a).String())30}31import (32func main() {33 fmt.Println(reflect.TypeOf(a))34 fmt.Println(reflect.ValueOf(a).Kind())35 fmt.Println(reflect.ValueOf(a).Type())36 fmt.Println(reflect.ValueOf(a).Int())37 fmt.Println(reflect.ValueOf(a).Bool())38 fmt.Println(reflect.ValueOf(a).String())39 fmt.Println(reflect.ValueOf(a).Float())40}41import

Full Screen

Full Screen

check

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 a := compiler{}4 a.check()5}6import "fmt"7func main() {8 a := compiler{}9 a.check()10}11import "fmt"12func main() {13 a := compiler{}14 a.check()15}16import "fmt"17func main() {18 a := compiler{}19 a.check()20}21import "fmt"22func main() {23 a := compiler{}24 a.check()25}26import "fmt"27func main() {28 a := compiler{}29 a.check()30}31import "fmt"32func main() {33 a := compiler{}34 a.check()35}36import "fmt"37func main() {38 a := compiler{}39 a.check()40}41import "fmt"42func main() {43 a := compiler{}44 a.check()45}46import "fmt"47func main() {48 a := compiler{}49 a.check()50}51import "fmt"52func main() {53 a := compiler{}54 a.check()55}56import "fmt"57func main() {58 a := compiler{}59 a.check()60}61import "fmt"62func main() {63 a := compiler{}64 a.check()65}66import "fmt"67func main() {68 a := compiler{}69 a.check()70}

Full Screen

Full Screen

check

Using AI Code Generation

copy

Full Screen

1import (2type Compiler struct {3}4func (c Compiler) check() {5 fmt.Println("Checking code for", c.language)6}7func main() {8 c := Compiler{"Go"}9 c.check()10}11import (12type Compiler struct {13}14func (c Compiler) check() {15 fmt.Println("Checking code for", c.language)16}17func main() {18 c := Compiler{"Go"}19 c.check()20}21import (22type Compiler struct {23}24func (c Compiler) check() {25 fmt.Println("Checking code for", c.language)26}27func main() {28 c := Compiler{"Go"}29 c.check()30}31import (32type Compiler struct {33}34func (c Compiler) check() {35 fmt.Println("Checking code for", c.language)36}37func main() {38 c := Compiler{"Go"}39 c.check()40}41import (42type Compiler struct {43}44func (c Compiler) check() {45 fmt.Println("Checking code for", c.language)46}47func main() {48 c := Compiler{"Go"}49 c.check()50}

Full Screen

Full Screen

check

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if compiler == "gc" {4 fmt.Println("The compiler is gc")5 } else {6 fmt.Println("The compiler is not gc")7 }8}

Full Screen

Full Screen

check

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 c := Compiler.NewCompiler()5 c.Check()6}7func Check() {8 fmt.Println("Checking...")9}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful