Best Syzkaller code snippet using main.checkUsedFiles
manager.go
Source:manager.go
...510 }511 return false, false512}513func (mgr *Manager) runInstance(index int) (*Crash, error) {514 mgr.checkUsedFiles()515 inst, err := mgr.vmPool.Create(index)516 if err != nil {517 return nil, fmt.Errorf("failed to create instance: %v", err)518 }519 defer inst.Close()520 fwdAddr, err := inst.Forward(mgr.port)521 if err != nil {522 return nil, fmt.Errorf("failed to setup port forwarding: %v", err)523 }524 fuzzerBin, err := inst.Copy(mgr.cfg.SyzFuzzerBin)525 if err != nil {526 return nil, fmt.Errorf("failed to copy binary: %v", err)527 }528 // If SyzExecutorCmd is provided, it means that syz-executor is already in529 // the image, so no need to copy it.530 executorCmd := targets.Get(mgr.cfg.TargetOS, mgr.cfg.TargetArch).SyzExecutorCmd531 if executorCmd == "" {532 executorCmd, err = inst.Copy(mgr.cfg.SyzExecutorBin)533 if err != nil {534 return nil, fmt.Errorf("failed to copy binary: %v", err)535 }536 }537 fuzzerV := 0538 procs := mgr.cfg.Procs539 if *flagDebug {540 fuzzerV = 100541 procs = 1542 }543 // Run the fuzzer binary.544 start := time.Now()545 atomic.AddUint32(&mgr.numFuzzing, 1)546 defer atomic.AddUint32(&mgr.numFuzzing, ^uint32(0))547 cmd := instance.FuzzerCmd(fuzzerBin, executorCmd, fmt.Sprintf("vm-%v", index),548 mgr.cfg.TargetOS, mgr.cfg.TargetArch, fwdAddr, mgr.cfg.Sandbox, procs, fuzzerV,549 mgr.cfg.Cover, *flagDebug, false, false)550 outc, errc, err := inst.Run(time.Hour, mgr.vmStop, cmd)551 if err != nil {552 return nil, fmt.Errorf("failed to run fuzzer: %v", err)553 }554 rep := inst.MonitorExecution(outc, errc, mgr.reporter, vm.ExitTimeout)555 if rep == nil {556 // This is the only "OK" outcome.557 log.Logf(0, "vm-%v: running for %v, restarting", index, time.Since(start))558 return nil, nil559 }560 crash := &Crash{561 vmIndex: index,562 hub: false,563 Report: rep,564 }565 return crash, nil566}567func (mgr *Manager) emailCrash(crash *Crash) {568 if len(mgr.cfg.EmailAddrs) == 0 {569 return570 }571 args := []string{"-s", "syzkaller: " + crash.Title}572 args = append(args, mgr.cfg.EmailAddrs...)573 log.Logf(0, "sending email to %v", mgr.cfg.EmailAddrs)574 cmd := exec.Command("mailx", args...)575 cmd.Stdin = bytes.NewReader(crash.Report.Report)576 if _, err := osutil.Run(10*time.Minute, cmd); err != nil {577 log.Logf(0, "failed to send email: %v", err)578 }579}580func (mgr *Manager) saveCrash(crash *Crash) bool {581 if crash.Type == report.MemoryLeak {582 mgr.mu.Lock()583 mgr.memoryLeakFrames[crash.Frame] = true584 mgr.mu.Unlock()585 }586 if crash.Type == report.DataRace {587 mgr.mu.Lock()588 mgr.dataRaceFrames[crash.Frame] = true589 mgr.mu.Unlock()590 }591 if crash.Suppressed {592 log.Logf(0, "vm-%v: suppressed crash %v", crash.vmIndex, crash.Title)593 mgr.stats.crashSuppressed.inc()594 return false595 }596 corrupted := ""597 if crash.Corrupted {598 corrupted = " [corrupted]"599 }600 log.Logf(0, "vm-%v: crash: %v%v", crash.vmIndex, crash.Title, corrupted)601 if err := mgr.reporter.Symbolize(crash.Report); err != nil {602 log.Logf(0, "failed to symbolize report: %v", err)603 }604 mgr.stats.crashes.inc()605 mgr.mu.Lock()606 if !mgr.crashTypes[crash.Title] {607 mgr.crashTypes[crash.Title] = true608 mgr.stats.crashTypes.inc()609 }610 mgr.mu.Unlock()611 if mgr.dash != nil {612 if crash.Type == report.MemoryLeak {613 return true614 }615 dc := &dashapi.Crash{616 BuildID: mgr.cfg.Tag,617 Title: crash.Title,618 Corrupted: crash.Corrupted,619 Maintainers: crash.Maintainers,620 Log: crash.Output,621 Report: crash.Report.Report,622 }623 resp, err := mgr.dash.ReportCrash(dc)624 if err != nil {625 log.Logf(0, "failed to report crash to dashboard: %v", err)626 } else {627 // Don't store the crash locally, if we've successfully628 // uploaded it to the dashboard. These will just eat disk space.629 return resp.NeedRepro630 }631 }632 sig := hash.Hash([]byte(crash.Title))633 id := sig.String()634 dir := filepath.Join(mgr.crashdir, id)635 osutil.MkdirAll(dir)636 if err := osutil.WriteFile(filepath.Join(dir, "description"), []byte(crash.Title+"\n")); err != nil {637 log.Logf(0, "failed to write crash: %v", err)638 }639 // Save up to 100 reports. If we already have 100, overwrite the oldest one.640 // Newer reports are generally more useful. Overwriting is also needed641 // to be able to understand if a particular bug still happens or already fixed.642 oldestI := 0643 var oldestTime time.Time644 for i := 0; i < 100; i++ {645 info, err := os.Stat(filepath.Join(dir, fmt.Sprintf("log%v", i)))646 if err != nil {647 oldestI = i648 if i == 0 {649 go mgr.emailCrash(crash)650 }651 break652 }653 if oldestTime.IsZero() || info.ModTime().Before(oldestTime) {654 oldestI = i655 oldestTime = info.ModTime()656 }657 }658 osutil.WriteFile(filepath.Join(dir, fmt.Sprintf("log%v", oldestI)), crash.Output)659 if len(mgr.cfg.Tag) > 0 {660 osutil.WriteFile(filepath.Join(dir, fmt.Sprintf("tag%v", oldestI)), []byte(mgr.cfg.Tag))661 }662 if len(crash.Report.Report) > 0 {663 osutil.WriteFile(filepath.Join(dir, fmt.Sprintf("report%v", oldestI)), crash.Report.Report)664 }665 return mgr.needLocalRepro(crash)666}667const maxReproAttempts = 3668func (mgr *Manager) needLocalRepro(crash *Crash) bool {669 if !mgr.cfg.Reproduce || crash.Corrupted {670 return false671 }672 if mgr.checkResult == nil || (mgr.checkResult.Features[host.FeatureLeak].Enabled &&673 crash.Type != report.MemoryLeak) {674 // Leak checking is very slow, don't bother reproducing other crashes.675 return false676 }677 sig := hash.Hash([]byte(crash.Title))678 dir := filepath.Join(mgr.crashdir, sig.String())679 if osutil.IsExist(filepath.Join(dir, "repro.prog")) {680 return false681 }682 for i := 0; i < maxReproAttempts; i++ {683 if !osutil.IsExist(filepath.Join(dir, fmt.Sprintf("repro%v", i))) {684 return true685 }686 }687 return false688}689func (mgr *Manager) needRepro(crash *Crash) bool {690 if crash.hub {691 return true692 }693 if mgr.dash == nil {694 return mgr.needLocalRepro(crash)695 }696 if crash.Type == report.MemoryLeak {697 return true698 }699 cid := &dashapi.CrashID{700 BuildID: mgr.cfg.Tag,701 Title: crash.Title,702 Corrupted: crash.Corrupted,703 }704 needRepro, err := mgr.dash.NeedRepro(cid)705 if err != nil {706 log.Logf(0, "dashboard.NeedRepro failed: %v", err)707 }708 return needRepro709}710func (mgr *Manager) saveFailedRepro(rep *report.Report, stats *repro.Stats) {711 if rep.Type == report.MemoryLeak {712 // Don't send failed leak repro attempts to dashboard713 // as we did not send the crash itself.714 return715 }716 if mgr.dash != nil {717 cid := &dashapi.CrashID{718 BuildID: mgr.cfg.Tag,719 Title: rep.Title,720 }721 if err := mgr.dash.ReportFailedRepro(cid); err != nil {722 log.Logf(0, "failed to report failed repro to dashboard: %v", err)723 } else {724 return725 }726 }727 dir := filepath.Join(mgr.crashdir, hash.String([]byte(rep.Title)))728 osutil.MkdirAll(dir)729 for i := 0; i < maxReproAttempts; i++ {730 name := filepath.Join(dir, fmt.Sprintf("repro%v", i))731 if !osutil.IsExist(name) {732 saveReproStats(name, stats)733 break734 }735 }736}737func (mgr *Manager) saveRepro(res *repro.Result, stats *repro.Stats, hub bool) {738 rep := res.Report739 if err := mgr.reporter.Symbolize(rep); err != nil {740 log.Logf(0, "failed to symbolize repro: %v", err)741 }742 opts := fmt.Sprintf("# %+v\n", res.Opts)743 prog := res.Prog.Serialize()744 // Append this repro to repro list to send to hub if it didn't come from hub originally.745 if !hub {746 progForHub := []byte(fmt.Sprintf("# %+v\n# %v\n# %v\n%s",747 res.Opts, res.Report.Title, mgr.cfg.Tag, prog))748 mgr.mu.Lock()749 mgr.newRepros = append(mgr.newRepros, progForHub)750 mgr.mu.Unlock()751 }752 var cprogText []byte753 if res.CRepro {754 cprog, err := csource.Write(res.Prog, res.Opts)755 if err == nil {756 formatted, err := csource.Format(cprog)757 if err == nil {758 cprog = formatted759 }760 cprogText = cprog761 } else {762 log.Logf(0, "failed to write C source: %v", err)763 }764 }765 if mgr.dash != nil {766 // Note: we intentionally don't set Corrupted for reproducers:767 // 1. This is reproducible so can be debugged even with corrupted report.768 // 2. Repro re-tried 3 times and still got corrupted report at the end,769 // so maybe corrupted report detection is broken.770 // 3. Reproduction is expensive so it's good to persist the result.771 dc := &dashapi.Crash{772 BuildID: mgr.cfg.Tag,773 Title: res.Report.Title,774 Maintainers: res.Report.Maintainers,775 Log: res.Report.Output,776 Report: res.Report.Report,777 ReproOpts: res.Opts.Serialize(),778 ReproSyz: res.Prog.Serialize(),779 ReproC: cprogText,780 }781 if _, err := mgr.dash.ReportCrash(dc); err != nil {782 log.Logf(0, "failed to report repro to dashboard: %v", err)783 } else {784 // Don't store the crash locally, if we've successfully785 // uploaded it to the dashboard. These will just eat disk space.786 return787 }788 }789 dir := filepath.Join(mgr.crashdir, hash.String([]byte(rep.Title)))790 osutil.MkdirAll(dir)791 if err := osutil.WriteFile(filepath.Join(dir, "description"), []byte(rep.Title+"\n")); err != nil {792 log.Logf(0, "failed to write crash: %v", err)793 }794 osutil.WriteFile(filepath.Join(dir, "repro.prog"), append([]byte(opts), prog...))795 if len(mgr.cfg.Tag) > 0 {796 osutil.WriteFile(filepath.Join(dir, "repro.tag"), []byte(mgr.cfg.Tag))797 }798 if len(rep.Output) > 0 {799 osutil.WriteFile(filepath.Join(dir, "repro.log"), rep.Output)800 }801 if len(rep.Report) > 0 {802 osutil.WriteFile(filepath.Join(dir, "repro.report"), rep.Report)803 }804 if len(cprogText) > 0 {805 osutil.WriteFile(filepath.Join(dir, "repro.cprog"), cprogText)806 }807 saveReproStats(filepath.Join(dir, "repro.stats"), stats)808}809func saveReproStats(filename string, stats *repro.Stats) {810 text := ""811 if stats != nil {812 text = fmt.Sprintf("Extracting prog: %v\nMinimizing prog: %v\n"+813 "Simplifying prog options: %v\nExtracting C: %v\nSimplifying C: %v\n\n\n%s",814 stats.ExtractProgTime, stats.MinimizeProgTime,815 stats.SimplifyProgTime, stats.ExtractCTime, stats.SimplifyCTime, stats.Log)816 }817 osutil.WriteFile(filename, []byte(text))818}819func (mgr *Manager) getMinimizedCorpus() (corpus, repros [][]byte) {820 mgr.mu.Lock()821 defer mgr.mu.Unlock()822 mgr.minimizeCorpus()823 corpus = make([][]byte, 0, len(mgr.corpus))824 for _, inp := range mgr.corpus {825 corpus = append(corpus, inp.Prog)826 }827 repros = mgr.newRepros828 mgr.newRepros = nil829 return830}831func (mgr *Manager) addNewCandidates(progs [][]byte) {832 candidates := make([]rpctype.RPCCandidate, len(progs))833 for i, inp := range progs {834 candidates[i] = rpctype.RPCCandidate{835 Prog: inp,836 Minimized: false, // don't trust programs from hub837 Smashed: false,838 }839 }840 mgr.mu.Lock()841 defer mgr.mu.Unlock()842 mgr.candidates = append(mgr.candidates, candidates...)843 if mgr.phase == phaseTriagedCorpus {844 mgr.phase = phaseQueriedHub845 }846}847func (mgr *Manager) minimizeCorpus() {848 if mgr.phase < phaseLoadedCorpus || len(mgr.corpus) <= mgr.lastMinCorpus*103/100 {849 return850 }851 inputs := make([]signal.Context, 0, len(mgr.corpus))852 for _, inp := range mgr.corpus {853 inputs = append(inputs, signal.Context{854 Signal: inp.Signal.Deserialize(),855 Context: inp,856 })857 }858 newCorpus := make(map[string]rpctype.RPCInput)859 // Note: inputs are unsorted (based on map iteration).860 // This gives some intentional non-determinism during minimization.861 for _, ctx := range signal.Minimize(inputs) {862 inp := ctx.(rpctype.RPCInput)863 newCorpus[hash.String(inp.Prog)] = inp864 }865 log.Logf(1, "minimized corpus: %v -> %v", len(mgr.corpus), len(newCorpus))866 mgr.corpus = newCorpus867 mgr.lastMinCorpus = len(newCorpus)868 // From time to time we get corpus explosion due to different reason:869 // generic bugs, per-OS bugs, problems with fallback coverage, kcov bugs, etc.870 // This has bad effect on the instance and especially on instances871 // connected via hub. Do some per-syscall sanity checking to prevent this.872 for call, info := range mgr.collectSyscallInfoUnlocked() {873 if mgr.cfg.Cover {874 // If we have less than 1K inputs per this call,875 // accept all new inputs unconditionally.876 if info.count < 1000 {877 continue878 }879 // If we have more than 3K already, don't accept any more.880 // Between 1K and 3K look at amount of coverage we are getting from these programs.881 // Empirically, real coverage for the most saturated syscalls is ~30-60882 // per program (even when we have a thousand of them). For explosion883 // case coverage tend to be much lower (~0.3-5 per program).884 if info.count < 3000 && len(info.cov)/info.count >= 10 {885 continue886 }887 } else {888 // If we don't have real coverage, signal is weak.889 // If we have more than several hundreds, there is something wrong.890 if info.count < 300 {891 continue892 }893 }894 if mgr.saturatedCalls[call] {895 continue896 }897 mgr.saturatedCalls[call] = true898 log.Logf(0, "coverage for %v has saturated, not accepting more inputs", call)899 }900 // Don't minimize persistent corpus until fuzzers have triaged all inputs from it.901 if mgr.phase < phaseTriagedCorpus {902 return903 }904 for key := range mgr.corpusDB.Records {905 _, ok1 := mgr.corpus[key]906 _, ok2 := mgr.disabledHashes[key]907 if !ok1 && !ok2 {908 mgr.corpusDB.Delete(key)909 }910 }911 mgr.corpusDB.BumpVersion(currentDBVersion)912}913type CallCov struct {914 count int915 cov cover.Cover916}917func (mgr *Manager) collectSyscallInfo() map[string]*CallCov {918 mgr.mu.Lock()919 defer mgr.mu.Unlock()920 return mgr.collectSyscallInfoUnlocked()921}922func (mgr *Manager) collectSyscallInfoUnlocked() map[string]*CallCov {923 if mgr.checkResult == nil {924 return nil925 }926 calls := make(map[string]*CallCov)927 for _, call := range mgr.checkResult.EnabledCalls[mgr.cfg.Sandbox] {928 calls[mgr.target.Syscalls[call].Name] = new(CallCov)929 }930 for _, inp := range mgr.corpus {931 if calls[inp.Call] == nil {932 calls[inp.Call] = new(CallCov)933 }934 cc := calls[inp.Call]935 cc.count++936 cc.cov.Merge(inp.Cover)937 }938 return calls939}940func (mgr *Manager) fuzzerConnect() ([]rpctype.RPCInput, BugFrames) {941 mgr.mu.Lock()942 defer mgr.mu.Unlock()943 mgr.minimizeCorpus()944 corpus := make([]rpctype.RPCInput, 0, len(mgr.corpus))945 for _, inp := range mgr.corpus {946 corpus = append(corpus, inp)947 }948 memoryLeakFrames := make([]string, 0, len(mgr.memoryLeakFrames))949 for frame := range mgr.memoryLeakFrames {950 memoryLeakFrames = append(memoryLeakFrames, frame)951 }952 dataRaceFrames := make([]string, 0, len(mgr.dataRaceFrames))953 for frame := range mgr.dataRaceFrames {954 dataRaceFrames = append(dataRaceFrames, frame)955 }956 return corpus, BugFrames{memoryLeaks: memoryLeakFrames, dataRaces: dataRaceFrames}957}958func (mgr *Manager) machineChecked(a *rpctype.CheckArgs, enabledSyscalls map[*prog.Syscall]bool) {959 mgr.mu.Lock()960 defer mgr.mu.Unlock()961 if len(mgr.cfg.EnabledSyscalls) != 0 && len(a.DisabledCalls[mgr.cfg.Sandbox]) != 0 {962 disabled := make(map[string]string)963 for _, dc := range a.DisabledCalls[mgr.cfg.Sandbox] {964 disabled[mgr.target.Syscalls[dc.ID].Name] = dc.Reason965 }966 for _, id := range mgr.configEnabledSyscalls {967 name := mgr.target.Syscalls[id].Name968 if reason := disabled[name]; reason != "" {969 log.Logf(0, "disabling %v: %v", name, reason)970 }971 }972 }973 if a.Error != "" {974 log.Fatalf("machine check: %v", a.Error)975 }976 log.Logf(0, "machine check:")977 log.Logf(0, "%-24v: %v/%v", "syscalls", len(enabledSyscalls), len(mgr.target.Syscalls))978 for _, feat := range a.Features.Supported() {979 log.Logf(0, "%-24v: %v", feat.Name, feat.Reason)980 }981 mgr.checkResult = a982 mgr.targetEnabledSyscalls = enabledSyscalls983 mgr.loadCorpus()984 mgr.firstConnect = time.Now()985}986func (mgr *Manager) newInput(inp rpctype.RPCInput, sign signal.Signal) bool {987 mgr.mu.Lock()988 defer mgr.mu.Unlock()989 if mgr.saturatedCalls[inp.Call] {990 return false991 }992 sig := hash.String(inp.Prog)993 if old, ok := mgr.corpus[sig]; ok {994 // The input is already present, but possibly with diffent signal/coverage/call.995 sign.Merge(old.Signal.Deserialize())996 old.Signal = sign.Serialize()997 var cov cover.Cover998 cov.Merge(old.Cover)999 cov.Merge(inp.Cover)1000 old.Cover = cov.Serialize()1001 mgr.corpus[sig] = old1002 } else {1003 mgr.corpus[sig] = inp1004 mgr.corpusDB.Save(sig, inp.Prog, 0)1005 if err := mgr.corpusDB.Flush(); err != nil {1006 log.Logf(0, "failed to save corpus database: %v", err)1007 }1008 }1009 return true1010}1011func (mgr *Manager) candidateBatch(size int) []rpctype.RPCCandidate {1012 mgr.mu.Lock()1013 defer mgr.mu.Unlock()1014 var res []rpctype.RPCCandidate1015 for i := 0; i < size && len(mgr.candidates) > 0; i++ {1016 last := len(mgr.candidates) - 11017 res = append(res, mgr.candidates[last])1018 mgr.candidates[last] = rpctype.RPCCandidate{}1019 mgr.candidates = mgr.candidates[:last]1020 }1021 if len(mgr.candidates) == 0 {1022 mgr.candidates = nil1023 if mgr.phase == phaseLoadedCorpus {1024 if mgr.cfg.HubClient != "" {1025 mgr.phase = phaseTriagedCorpus1026 go mgr.hubSyncLoop()1027 } else {1028 mgr.phase = phaseTriagedHub1029 }1030 } else if mgr.phase == phaseQueriedHub {1031 mgr.phase = phaseTriagedHub1032 }1033 }1034 return res1035}1036func (mgr *Manager) rotateCorpus() bool {1037 mgr.mu.Lock()1038 defer mgr.mu.Unlock()1039 return mgr.phase == phaseTriagedHub1040}1041func (mgr *Manager) collectUsedFiles() {1042 if mgr.vmPool == nil {1043 return1044 }1045 addUsedFile := func(f string) {1046 if f == "" {1047 return1048 }1049 stat, err := os.Stat(f)1050 if err != nil {1051 log.Fatalf("failed to stat %v: %v", f, err)1052 }1053 mgr.usedFiles[f] = stat.ModTime()1054 }1055 cfg := mgr.cfg1056 addUsedFile(cfg.SyzFuzzerBin)1057 addUsedFile(cfg.SyzExecprogBin)1058 addUsedFile(cfg.SyzExecutorBin)1059 addUsedFile(cfg.SSHKey)1060 if vmlinux := filepath.Join(cfg.KernelObj, mgr.sysTarget.KernelObject); osutil.IsExist(vmlinux) {1061 addUsedFile(vmlinux)1062 }1063 if cfg.Image != "9p" {1064 addUsedFile(cfg.Image)1065 }1066}1067func (mgr *Manager) checkUsedFiles() {1068 for f, mod := range mgr.usedFiles {1069 stat, err := os.Stat(f)1070 if err != nil {1071 log.Fatalf("failed to stat %v: %v", f, err)1072 }1073 if mod != stat.ModTime() {1074 log.Fatalf("file %v that syz-manager uses has been modified by an external program\n"+1075 "this can lead to arbitrary syz-manager misbehavior\n"+1076 "modification time has changed: %v -> %v\n"+1077 "don't modify files that syz-manager uses. exiting to prevent harm",1078 f, mod, stat.ModTime())1079 }1080 }1081}...
checkUsedFiles
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World!")4 checkUsedFiles()5}6import (7func main() {8 fmt.Println("Hello World!")9 checkUsedFiles()10}
checkUsedFiles
Using AI Code Generation
1import (2func main() {3 obj := new(main)4 obj.checkUsedFiles()5}6import (7func (obj *main) checkUsedFiles() {8 dir, err := os.Getwd()9 if err != nil {10 fmt.Println(err)11 }12 files, err := ioutil.ReadDir(dir)13 if err != nil {14 fmt.Println(err)15 }16 for _, f := range files {17 if !f.IsDir() {18 if strings.HasSuffix(f.Name(), ".go") {19 allFiles = append(allFiles, f.Name())20 }21 }22 }23 for _, f := range files {24 if !f.IsDir() {25 if strings.HasSuffix(f.Name(), ".go") {26 content, err := ioutil.ReadFile(f.Name())27 if err != nil {28 fmt.Println(err)29 }30 for _, f1 := range allFiles {31 if !f.IsDir() {32 if strings.HasSuffix(f1, ".go") {33 if f1 != f.Name() {34 if strings.Contains(string(content), f1) {35 fmt.Println(f1 + " is used in " + f.Name())36 }37 }38 }39 }40 }41 }42 }
checkUsedFiles
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4}5import (6func main() {7 fmt.Println("Hello, playground")8}9import (10func main() {11 fmt.Println("Hello, playground")12}13import (14func main() {15 fmt.Println("Hello, playground")16}17import (18func main() {19 fmt.Println("Hello, playground")20}21import (22func main() {23 fmt.Println("Hello, playground")24}25import (26func main() {27 fmt.Println("Hello, playground")28}29import (30func main() {31 fmt.Println("Hello, playground")32}33import (34func main() {35 fmt.Println("Hello, playground")36}37import (38func main() {39 fmt.Println("Hello, playground")40}41import (42func main() {43 fmt.Println("Hello, playground")44}45import (46func main() {47 fmt.Println("Hello, playground")48}49import (50func main() {51 fmt.Println("Hello, playground")52}53import (54func main() {55 fmt.Println("Hello, playground")56}57import (58func main() {59 fmt.Println("Hello, playground")60}61import (62func main() {63 fmt.Println("Hello, playground")64}65import (66func main() {67 fmt.Println("Hello, playground")68}69import (70func main() {71 fmt.Println("Hello, playground")72}73import (74func main() {75 fmt.Println("Hello, playground")76}77import (78func main() {79 fmt.Println("Hello, playground")80}81import (
checkUsedFiles
Using AI Code Generation
1import (2func main() {3 var p = new(Package)4 p.checkUsedFiles()5}6import (7func main() {8 var p = new(Package)9 p.checkUsedFiles()10}11import (12func main() {13 var p = new(Package)14 p.checkUsedFiles()15}16import (17func main() {18 var p = new(Package)19 p.checkUsedFiles()20}21import (22func main() {23 var p = new(Package)24 p.checkUsedFiles()25}26import (27func main() {28 var p = new(Package)29 p.checkUsedFiles()30}31import (32func main() {33 var p = new(Package)34 p.checkUsedFiles()35}36import (37func main() {38 var p = new(Package)39 p.checkUsedFiles()40}41import (42func main() {43 var p = new(Package)44 p.checkUsedFiles()45}46import (47func main() {48 var p = new(Package)
checkUsedFiles
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 m.checkUsedFiles()5}6import (7func main() {8 fmt.Println("Hello, playground")9}10func (m main) checkUsedFiles() {11 dir, err := os.Getwd()12 if err != nil {13 fmt.Println("Error in getting current directory")14 } else {15 err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {16 if err != nil {17 }18 if !info.IsDir() {19 if info.Name() != "main.go" {20 fmt.Println(info.Name())21 }22 }23 })24 if err != nil {25 fmt.Println("Error in getting files")26 }27 }28}
checkUsedFiles
Using AI Code Generation
1import (2func main() {3 reader := bufio.NewReader(os.Stdin)4 fmt.Print("Enter the file name: ")5 fileName, _ := reader.ReadString('6 fileName = strings.TrimSuffix(fileName, "7 mainObj := mainClass{}8 mainObj.checkUsedFiles(path, fileName)9}10type mainClass struct {11}12func (m mainClass) checkUsedFiles(path string, fileName string) {13 files, err := ioutil.ReadDir(path)14 if err != nil {15 log.Fatal(err)16 }17 for _, file := range files {18 if file.IsDir() {19 dirPath, err := filepath.Abs(file.Name())20 if err != nil {21 log.Fatal(err)22 }23 m.checkUsedFiles(dirPath, fileName)24 } else {25 extension := filepath.Ext(file.Name())26 if extension == ".go" {27 filePath, err := filepath.Abs(file.Name())28 if err != nil {29 log.Fatal(err)30 }31 fileData, err := os.Open(filePath)32 if err != nil {33 log.Fatal(err)34 }35 defer fileData.Close()36 scanner := bufio.NewScanner(fileData)37 for scanner.Scan() {
checkUsedFiles
Using AI Code Generation
1import (2func main() {3if checkUsedFiles("1.go") {4fmt.Println("File is used")5} else {6fmt.Println("File is not used")7}8}9import (10func main() {11if checkUsedFiles("2.go") {12fmt.Println("File is used")13} else {14fmt.Println("File is not used")15}16}
checkUsedFiles
Using AI Code Generation
1import (2func main() {3 usedFiles, err := checkUsedFiles(path)4 if err != nil {5 fmt.Println("Error in checkUsedFiles method")6 }7 fmt.Println(usedFiles)8}9func checkUsedFiles(path string) ([]string, error) {10 err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {11 files = append(files, path)12 })13 if err != nil {14 }15 for _, file := range files {16 f, err := os.Open(file)17 if err != nil {18 }19 defer f.Close()20 fi, err := f.Stat()21 if err != nil {22 }23 if fi.Mode().IsRegular() {24 usedFiles = append(usedFiles, file)25 }26 }27}
checkUsedFiles
Using AI Code Generation
1import (2func main() {3 var files = []string{4 }5 var unusedFiles = checkUsedFiles(root, files)6 fmt.Println(unusedFiles)7}8func checkUsedFiles(root string, files []string) []string {9 filepath.Walk(root, func(path string, info os.FileInfo, err error) error {10 if err != nil {11 }12 for _, file := range files {13 if file == info.Name() {14 unusedFiles = append(unusedFiles, file)15 }16 }17 })18 if err != nil {19 fmt.Println(err)20 }21}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!