How to use randRange method of prog Package

Best Syzkaller code snippet using prog.randRange

rand.go

Source:rand.go Github

copy

Full Screen

...24}25func (r *randGen) rand(n int) uint64 {26 return uint64(r.Intn(n))27}28func (r *randGen) randRange(begin, end uint64) uint64 {29 return begin + uint64(r.Intn(int(end-begin+1)))30}31func (r *randGen) bin() bool {32 return r.Intn(2) == 033}34func (r *randGen) oneOf(n int) bool {35 return r.Intn(n) == 036}37func (r *randGen) rand64() uint64 {38 v := uint64(r.Int63())39 if r.bin() {40 v |= 1 << 6341 }42 return v43}44// Some potentially interesting integers.45var specialInts = []uint64{46 0, 1, 31, 32, 63, 64, 127, 128,47 129, 255, 256, 257, 511, 512,48 1023, 1024, 1025, 2047, 2048, 4095, 4096,49 (1 << 15) - 1, (1 << 15), (1 << 15) + 1,50 (1 << 16) - 1, (1 << 16), (1 << 16) + 1,51 (1 << 31) - 1, (1 << 31), (1 << 31) + 1,52 (1 << 32) - 1, (1 << 32), (1 << 32) + 1,53}54func (r *randGen) randInt() uint64 {55 v := r.rand64()56 switch {57 case r.nOutOf(100, 182):58 v %= 1059 case r.nOutOf(50, 82):60 v = specialInts[r.Intn(len(specialInts))]61 case r.nOutOf(10, 32):62 v %= 25663 case r.nOutOf(10, 22):64 v %= 4 << 1065 case r.nOutOf(10, 12):66 v %= 64 << 1067 default:68 v %= 1 << 3169 }70 switch {71 case r.nOutOf(100, 107):72 case r.nOutOf(5, 7):73 v = uint64(-int64(v))74 default:75 v <<= uint(r.Intn(63))76 }77 return v78}79func (r *randGen) randRangeInt(begin uint64, end uint64) uint64 {80 if r.oneOf(100) {81 return r.randInt()82 }83 return begin + (r.Uint64() % (end - begin + 1))84}85// biasedRand returns a random int in range [0..n),86// probability of n-1 is k times higher than probability of 0.87func (r *randGen) biasedRand(n, k int) int {88 nf, kf := float64(n), float64(k)89 rf := nf * (kf/2 + 1) * r.Float64()90 bf := (-1 + math.Sqrt(1+2*kf*rf/nf)) * nf / kf91 return int(bf)92}93func (r *randGen) randArrayLen() uint64 {94 const maxLen = 1095 // biasedRand produces: 10, 9, ..., 1, 0,96 // we want: 1, 2, ..., 9, 10, 097 return uint64(maxLen-r.biasedRand(maxLen+1, 10)+1) % (maxLen + 1)98}99func (r *randGen) randBufLen() (n uint64) {100 switch {101 case r.nOutOf(50, 56):102 n = r.rand(256)103 case r.nOutOf(5, 6):104 n = 4 << 10105 }106 return107}108func (r *randGen) randPageCount() (n uint64) {109 switch {110 case r.nOutOf(100, 106):111 n = r.rand(4) + 1112 case r.nOutOf(5, 6):113 n = r.rand(20) + 1114 default:115 n = (r.rand(3) + 1) * 512116 }117 return118}119func (r *randGen) flags(vv []uint64) (v uint64) {120 switch {121 case r.nOutOf(90, 111):122 for stop := false; !stop; stop = r.bin() {123 v |= vv[r.rand(len(vv))]124 }125 case r.nOutOf(10, 21):126 v = vv[r.rand(len(vv))]127 case r.nOutOf(10, 11):128 v = 0129 default:130 v = r.rand64()131 }132 return133}134func (r *randGen) filename(s *state, typ *BufferType) string {135 fn := r.filenameImpl(s)136 if !typ.Varlen() {137 size := typ.Size()138 if uint64(len(fn)) < size {139 fn += string(make([]byte, size-uint64(len(fn))))140 }141 fn = fn[:size]142 }143 return fn144}145func (r *randGen) filenameImpl(s *state) string {146 dir := "."147 if r.oneOf(2) && len(s.files) != 0 {148 files := make([]string, 0, len(s.files))149 for f := range s.files {150 files = append(files, f)151 }152 dir = files[r.Intn(len(files))]153 if len(dir) > 0 && dir[len(dir)-1] == 0 {154 dir = dir[:len(dir)-1]155 }156 }157 if len(s.files) == 0 || r.oneOf(10) {158 // Generate a new name.159 for i := 0; ; i++ {160 f := fmt.Sprintf("%v/file%v\x00", dir, i)161 if !s.files[f] {162 return f163 }164 }165 }166 files := make([]string, 0, len(s.files))167 for f := range s.files {168 files = append(files, f)169 }170 return files[r.Intn(len(files))]171}172func (r *randGen) randString(s *state, t *BufferType) []byte {173 if len(t.Values) != 0 {174 return []byte(t.Values[r.Intn(len(t.Values))])175 }176 if len(s.strings) != 0 && r.bin() {177 // Return an existing string.178 // TODO(dvyukov): make s.strings indexed by string SubKind.179 strings := make([]string, 0, len(s.strings))180 for s := range s.strings {181 strings = append(strings, s)182 }183 return []byte(strings[r.Intn(len(strings))])184 }185 punct := []byte{'!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '\\',186 '/', ':', '.', ',', '-', '\'', '[', ']', '{', '}'}187 buf := new(bytes.Buffer)188 for r.nOutOf(3, 4) {189 switch {190 case r.nOutOf(10, 21):191 dict := r.target.StringDictionary192 if len(dict) != 0 {193 buf.WriteString(dict[r.Intn(len(dict))])194 }195 case r.nOutOf(10, 11):196 buf.Write([]byte{punct[r.Intn(len(punct))]})197 default:198 buf.Write([]byte{byte(r.Intn(256))})199 }200 }201 if r.oneOf(100) == t.NoZ {202 buf.Write([]byte{0})203 }204 return buf.Bytes()205}206func (r *randGen) allocAddr(s *state, typ Type, size uint64, data Arg) *PointerArg {207 return MakePointerArg(typ, s.ma.alloc(r, size), data)208}209func (r *randGen) allocVMA(s *state, typ Type, numPages uint64) *PointerArg {210 page := s.va.alloc(r, numPages)211 return MakeVmaPointerArg(typ, page*r.target.PageSize, numPages*r.target.PageSize)212}213func (r *randGen) createResource(s *state, res *ResourceType) (arg Arg, calls []*Call) {214 if r.inCreateResource {215 special := res.SpecialValues()216 return MakeResultArg(res, nil, special[r.Intn(len(special))]), nil217 }218 r.inCreateResource = true219 defer func() { r.inCreateResource = false }()220 kind := res.Desc.Name221 if r.oneOf(1000) {222 // Spoof resource subkind.223 var all []string224 for kind1 := range r.target.resourceMap {225 if r.target.isCompatibleResource(res.Desc.Kind[0], kind1) {226 all = append(all, kind1)227 }228 }229 kind = all[r.Intn(len(all))]230 }231 // Find calls that produce the necessary resources.232 metas0 := r.target.resourceCtors[kind]233 // TODO: reduce priority of less specialized ctors.234 var metas []*Syscall235 for _, meta := range metas0 {236 if s.ct == nil || s.ct.run[meta.ID] == nil {237 continue238 }239 metas = append(metas, meta)240 }241 if len(metas) == 0 {242 return MakeResultArg(res, nil, res.Default()), nil243 }244 // Now we have a set of candidate calls that can create the necessary resource.245 for i := 0; i < 1e3; i++ {246 // Generate one of them.247 meta := metas[r.Intn(len(metas))]248 calls := r.generateParticularCall(s, meta)249 s1 := newState(r.target, s.ct)250 s1.analyze(calls[len(calls)-1])251 // Now see if we have what we want.252 var allres []Arg253 for kind1, res1 := range s1.resources {254 if r.target.isCompatibleResource(kind, kind1) {255 allres = append(allres, res1...)256 }257 }258 if len(allres) != 0 {259 // Bingo!260 arg := MakeResultArg(res, allres[r.Intn(len(allres))], 0)261 return arg, calls262 }263 // Discard unsuccessful calls.264 // Note: s.ma/va have already noted allocations of the new objects265 // in discarded syscalls, ideally we should recreate state266 // by analyzing the program again.267 for _, c := range calls {268 ForeachArg(c, func(arg Arg, _ *ArgCtx) {269 if a, ok := arg.(*ResultArg); ok && a.Res != nil {270 delete(*a.Res.(ArgUsed).Used(), arg)271 }272 })273 }274 }275 // Generally we can loop several times, e.g. when we choose a call that returns276 // the resource in an array, but then generateArg generated that array of zero length.277 // But we must succeed eventually.278 var ctors []string279 for _, meta := range metas {280 ctors = append(ctors, meta.Name)281 }282 panic(fmt.Sprintf("failed to create a resource %v with %v",283 res.Desc.Kind[0], strings.Join(ctors, ", ")))284}285func (r *randGen) generateText(kind TextKind) []byte {286 switch kind {287 case Text_arm64:288 // Just a stub, need something better.289 text := make([]byte, 50)290 for i := range text {291 text[i] = byte(r.Intn(256))292 }293 return text294 default:295 cfg := createIfuzzConfig(kind)296 return ifuzz.Generate(cfg, r.Rand)297 }298}299func (r *randGen) mutateText(kind TextKind, text []byte) []byte {300 switch kind {301 case Text_arm64:302 return mutateData(r, text, 40, 60)303 default:304 cfg := createIfuzzConfig(kind)305 return ifuzz.Mutate(cfg, r.Rand, text)306 }307}308func createIfuzzConfig(kind TextKind) *ifuzz.Config {309 cfg := &ifuzz.Config{310 Len: 10,311 Priv: true,312 Exec: true,313 MemRegions: []ifuzz.MemRegion{314 {0 << 12, 1 << 12},315 {1 << 12, 1 << 12},316 {2 << 12, 1 << 12},317 {3 << 12, 1 << 12},318 {4 << 12, 1 << 12},319 {5 << 12, 1 << 12},320 {6 << 12, 1 << 12},321 {7 << 12, 1 << 12},322 {8 << 12, 1 << 12},323 {9 << 12, 1 << 12},324 {0xfec00000, 0x100}, // ioapic325 },326 }327 switch kind {328 case Text_x86_real:329 cfg.Mode = ifuzz.ModeReal16330 case Text_x86_16:331 cfg.Mode = ifuzz.ModeProt16332 case Text_x86_32:333 cfg.Mode = ifuzz.ModeProt32334 case Text_x86_64:335 cfg.Mode = ifuzz.ModeLong64336 }337 return cfg338}339// nOutOf returns true n out of outOf times.340func (r *randGen) nOutOf(n, outOf int) bool {341 if n <= 0 || n >= outOf {342 panic("bad probability")343 }344 v := r.Intn(outOf)345 return v < n346}347func (r *randGen) generateCall(s *state, p *Prog) []*Call {348 idx := 0349 if s.ct == nil {350 idx = r.Intn(len(r.target.Syscalls))351 } else {352 // 如果p.call为空,那么随机选择一个函数;否则从现有的函数中随机选择一个函数,353 // 根据这个函数的优先级列表随机生成函数;354 call := -1355 if len(p.Calls) != 0 {356 call = p.Calls[r.Intn(len(p.Calls))].Meta.ID357 }358 idx = s.ct.Choose(r.Rand, call)359 }360 meta := r.target.Syscalls[idx]361 return r.generateParticularCall(s, meta)362}363func (r *randGen) myGenerateCall(s *state, p *Prog) []*Call {364 idx := 0365 if s.ct == nil {366 idx = r.Intn(len(r.target.Syscalls))367 } else {368 // 如果p.call为空,那么随机选择一个函数;否则从现有的函数中随机选择一个函数,369 // 根据这个函数的优先级列表随机生成函数;370 call := -1371 if len(p.Calls) != 0 {372 // 选择最后一个函数373 call = p.Calls[len(p.Calls)-1].Meta.ID374 }375 // 全为0,重新选择函数376 if call != -1 && s.ct.run[call][len(r.target.Syscalls)-1] == 0 {377 call = -1378 }379 // 从选择的函数中选择下一个函数的下标380 idx = s.ct.MyChoose(r.Rand, call)381 }382 meta := r.target.Syscalls[idx]383 return r.generateParticularCall(s, meta)384}385func (r *randGen) generateParticularCall(s *state, meta *Syscall) (calls []*Call) {386 c := &Call{387 Meta: meta,388 Ret: MakeReturnArg(meta.Ret),389 }390 c.Args, calls = r.generateArgs(s, meta.Args)391 r.target.assignSizesCall(c)392 calls = append(calls, c)393 for _, c1 := range calls {394 r.target.SanitizeCall(c1)395 }396 return calls397}398// GenerateAllSyzProg generates a program that contains all pseudo syz_ calls for testing.399func (target *Target) GenerateAllSyzProg(rs rand.Source) *Prog {400 p := &Prog{401 Target: target,402 }403 r := newRand(target, rs)404 s := newState(target, nil)405 handled := make(map[string]bool)406 for _, meta := range target.Syscalls {407 if !strings.HasPrefix(meta.CallName, "syz_") || handled[meta.CallName] {408 continue409 }410 handled[meta.CallName] = true411 calls := r.generateParticularCall(s, meta)412 for _, c := range calls {413 s.analyze(c)414 p.Calls = append(p.Calls, c)415 }416 }417 if err := p.validate(); err != nil {418 panic(err)419 }420 return p421}422// GenerateSimpleProg generates the simplest non-empty program for testing423// (e.g. containing a single mmap).424func (target *Target) GenerateSimpleProg() *Prog {425 return &Prog{426 Target: target,427 Calls: []*Call{target.MakeMmap(0, target.PageSize)},428 }429}430func (target *Target) GenerateUberMmapProg() *Prog {431 return &Prog{432 Target: target,433 Calls: []*Call{target.MakeMmap(0, target.NumPages*target.PageSize)},434 }435}436func (r *randGen) generateArgs(s *state, types []Type) ([]Arg, []*Call) {437 var calls []*Call438 args := make([]Arg, len(types))439 // Generate all args. Size args have the default value 0 for now.440 for i, typ := range types {441 arg, calls1 := r.generateArg(s, typ)442 if arg == nil {443 panic(fmt.Sprintf("generated arg is nil for type '%v', types: %+v", typ.Name(), types))444 }445 args[i] = arg446 calls = append(calls, calls1...)447 }448 return args, calls449}450func (r *randGen) generateArg(s *state, typ Type) (arg Arg, calls []*Call) {451 return r.generateArgImpl(s, typ, false)452}453func (r *randGen) generateArgImpl(s *state, typ Type, ignoreSpecial bool) (arg Arg, calls []*Call) {454 if typ.Dir() == DirOut {455 // No need to generate something interesting for output scalar arguments.456 // But we still need to generate the argument itself so that it can be referenced457 // in subsequent calls. For the same reason we do generate pointer/array/struct458 // output arguments (their elements can be referenced in subsequent calls).459 switch typ.(type) {460 case *IntType, *FlagsType, *ConstType, *ProcType,461 *VmaType, *ResourceType:462 return r.target.defaultArg(typ), nil463 }464 }465 if typ.Optional() && r.oneOf(5) {466 return r.target.defaultArg(typ), nil467 }468 // Allow infinite recursion for optional pointers.469 if pt, ok := typ.(*PtrType); ok && typ.Optional() {470 switch pt.Type.(type) {471 case *StructType, *ArrayType, *UnionType:472 name := pt.Type.Name()473 r.recDepth[name]++474 defer func() {475 r.recDepth[name]--476 if r.recDepth[name] == 0 {477 delete(r.recDepth, name)478 }479 }()480 if r.recDepth[name] >= 3 {481 return MakeNullPointerArg(typ), nil482 }483 }484 }485 switch a := typ.(type) {486 case *ResourceType:487 switch {488 case r.nOutOf(1000, 1011):489 // Get an existing resource.490 var allres []Arg491 for name1, res1 := range s.resources {492 if name1 == "iocbptr" {493 continue494 }495 if r.target.isCompatibleResource(a.Desc.Name, name1) ||496 r.oneOf(20) && r.target.isCompatibleResource(a.Desc.Kind[0], name1) {497 allres = append(allres, res1...)498 }499 }500 if len(allres) != 0 {501 arg = MakeResultArg(a, allres[r.Intn(len(allres))], 0)502 } else {503 arg, calls = r.createResource(s, a)504 }505 case r.nOutOf(10, 11):506 // Create a new resource.507 arg, calls = r.createResource(s, a)508 default:509 special := a.SpecialValues()510 arg = MakeResultArg(a, nil, special[r.Intn(len(special))])511 }512 return arg, calls513 case *BufferType:514 switch a.Kind {515 case BufferBlobRand, BufferBlobRange:516 sz := r.randBufLen()517 if a.Kind == BufferBlobRange {518 sz = r.randRange(a.RangeBegin, a.RangeEnd)519 }520 if a.Dir() == DirOut {521 return MakeOutDataArg(a, sz), nil522 }523 data := make([]byte, sz)524 for i := range data {525 data[i] = byte(r.Intn(256))526 }527 return MakeDataArg(a, data), nil528 case BufferString:529 data := r.randString(s, a)530 if a.Dir() == DirOut {531 return MakeOutDataArg(a, uint64(len(data))), nil532 }533 return MakeDataArg(a, data), nil534 case BufferFilename:535 if a.Dir() == DirOut {536 var sz uint64537 switch {538 case !a.Varlen():539 sz = a.Size()540 case r.nOutOf(1, 3):541 sz = r.rand(100)542 case r.nOutOf(1, 2):543 sz = 108 // UNIX_PATH_MAX544 default:545 sz = 4096 // PATH_MAX546 }547 return MakeOutDataArg(a, sz), nil548 }549 return MakeDataArg(a, []byte(r.filename(s, a))), nil550 case BufferText:551 if a.Dir() == DirOut {552 return MakeOutDataArg(a, uint64(r.Intn(100))), nil553 }554 return MakeDataArg(a, r.generateText(a.Text)), nil555 default:556 panic("unknown buffer kind")557 }558 case *VmaType:559 npages := r.randPageCount()560 if a.RangeBegin != 0 || a.RangeEnd != 0 {561 npages = a.RangeBegin + uint64(r.Intn(int(a.RangeEnd-a.RangeBegin+1)))562 }563 arg := r.allocVMA(s, a, npages)564 return arg, nil565 case *FlagsType:566 return MakeConstArg(a, r.flags(a.Vals)), nil567 case *ConstType:568 return MakeConstArg(a, a.Val), nil569 case *IntType:570 v := r.randInt()571 switch a.Kind {572 case IntFileoff:573 switch {574 case r.nOutOf(90, 101):575 v = 0576 case r.nOutOf(10, 11):577 v = r.rand(100)578 default:579 v = r.randInt()580 }581 case IntRange:582 v = r.randRangeInt(a.RangeBegin, a.RangeEnd)583 }584 return MakeConstArg(a, v), nil585 case *ProcType:586 return MakeConstArg(a, r.rand(int(a.ValuesPerProc))), nil587 case *ArrayType:588 var count uint64589 switch a.Kind {590 case ArrayRandLen:591 count = r.randArrayLen()592 case ArrayRangeLen:593 count = r.randRange(a.RangeBegin, a.RangeEnd)594 }595 var inner []Arg596 var calls []*Call597 for i := uint64(0); i < count; i++ {598 arg1, calls1 := r.generateArg(s, a.Type)599 inner = append(inner, arg1)600 calls = append(calls, calls1...)601 }602 return MakeGroupArg(a, inner), calls603 case *StructType:604 if !ignoreSpecial {605 if gen := r.target.SpecialTypes[a.Name()]; gen != nil && a.Dir() != DirOut {606 arg, calls = gen(&Gen{r, s}, a, nil)607 return...

Full Screen

Full Screen

randRange

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 rand.Seed(time.Now().UnixNano())4 for i := 0; i < 10; i++ {5 fmt.Println(randRange(1, 10))6 }7}8import (9func randRange(min, max int) int {10 return rand.Intn(max-min) + min11}

Full Screen

Full Screen

randRange

Using AI Code Generation

copy

Full Screen

1import (2type prog struct {3}4func (p *prog) randRange(min, max int) int {5 rand.Seed(time.Now().Unix())6 return rand.Intn(max-min) + min7}8func main() {9 p := prog{}10 fmt.Println(p.randRange(1, 10))11}

Full Screen

Full Screen

randRange

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "math/rand"3import "time"4func main() {5 fmt.Println(randRange(10, 20))6}7func randRange(min, max int) int {8 rand.Seed(time.Now().Unix())9 return rand.Intn(max-min) + min10}

Full Screen

Full Screen

randRange

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 rand.Seed(time.Now().Unix())4 fmt.Println(randRange(1, 100))5}6func randRange(min, max int) int {7 return rand.Intn(max-min) + min8}9import (10func main() {11 rand.Seed(time.Now().Unix())12 fmt.Println(randRange(1, 100))13}14func randRange(min, max int) int {15 return rand.Intn(max-min) + min16}17import (18func main() {19 rand.Seed(time.Now().Unix())20 fmt.Println(randRange(1, 100))21}22func randRange(min, max int) int {23 return rand.Intn(max-min) + min24}25import (26func main() {27 rand.Seed(time.Now().Unix())28 fmt.Println(randRange(1, 100))29}

Full Screen

Full Screen

randRange

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 num = prog.RandRange(1, 10)4 fmt.Println("Random number between 1 and 10:", num)5}6import (7func RandRange(min, max int) int {8 rand.Seed(time.Now().UnixNano())9 return rand.Intn(max-min) + min10}

Full Screen

Full Screen

randRange

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 rand.Seed(time.Now().UnixNano())4 fmt.Println("Random number in range 0-10:", randRange(0, 10))5 fmt.Println("Random number in range 0-100:", randRange(0, 100))6 fmt.Println("Random number in range 0-500:", randRange(0, 500))7 fmt.Println("Random number in range 0-10000:", randRange(0, 10000))8}9import "math/rand"10func randRange(min, max int) int {11 return rand.Intn(max-min) + min12}

Full Screen

Full Screen

randRange

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "math/rand"3import "time"4func main() {5 rand.Seed(time.Now().Unix())6 fmt.Println(randRange(1, 10))7}8import "fmt"9import "math/rand"10import "time"11func main() {12 rand.Seed(time.Now().Unix())13 fmt.Println(randRange(1, 10))14}15import "fmt"16import "math/rand"17import "time"18func main() {19 rand.Seed(time.Now().Unix())20 fmt.Println(randRange(1, 10))21}22import "fmt"23import "math/rand"24import "time"25func main() {26 rand.Seed(time.Now().Unix())27 fmt.Println(randRange(1, 10))28}29import "fmt"30import "math/rand"31import "time"32func main() {33 rand.Seed(time.Now().Unix())34 fmt.Println(randRange(1, 10))35}36import "fmt"37import "math/rand"38import "time"39func main() {40 rand.Seed(time.Now().Unix())41 fmt.Println(randRange(1, 10))42}43import "fmt"44import "math/rand"45import "time"

Full Screen

Full Screen

randRange

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 prog1.randRange(1, 100)4 prog1.randRange(1, 100)5 prog1.randRange(1, 100)6}7import (8type prog struct {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