How to use populateDir method of main Package

Best Syzkaller code snippet using main.populateDir

imagegen.go

Source:imagegen.go Github

copy

Full Screen

...506 if err != nil {507 tool.Fail(err)508 }509 defer os.RemoveAll(templateDir)510 if err := populateDir(templateDir); err != nil {511 tool.Fail(err)512 }513 shutdown := make(chan struct{})514 osutil.HandleInterrupts(shutdown)515 procs := runtime.NumCPU()516 requests := make(chan *Image, procs)517 go func() {518 for _, image := range images {519 image.templateDir = templateDir520 requests <- image521 }522 close(requests)523 }()524 for p := 0; p < procs; p++ {525 go func() {526 for image := range requests {527 select {528 case <-shutdown:529 image.done <- errShutdown530 default:531 image.done <- image.generate()532 }533 }534 }()535 }536 printResults(images, shutdown, *flagKeepImage, *flagVerbose)537}538func printResults(images []*Image, shutdown chan struct{}, keepImage, verbose bool) {539 good, failed := 0, 0540 hashes := make(map[uint32][]*Image)541 for _, image := range images {542 err := <-image.done543 if image.disk != "" && !keepImage {544 os.Remove(image.disk)545 }546 select {547 case <-shutdown:548 err = errShutdown549 default:550 }551 if err == errShutdown {552 continue553 }554 size := fmt.Sprintf("%vKB", image.size>>10)555 if image.size >= 1<<20 {556 size = fmt.Sprintf("%vMB", image.size>>20)557 }558 res := "ok"559 if err != nil {560 res = fmt.Sprintf("failed:\n\t%v", err)561 }562 if verbose || err != nil {563 fmt.Printf("#%02v: mkfs.%v[%5v] %v: %v\n", image.index, image.fs.Name, size, image.flags, res)564 }565 if err != nil {566 failed++567 continue568 }569 hashes[image.hash] = append(hashes[image.hash], image)570 good++571 }572 fmt.Printf("generated images: %v/%v\n", good, len(images))573 for _, image := range images {574 group := hashes[image.hash]575 if len(group) <= 1 {576 continue577 }578 delete(hashes, image.hash)579 fmt.Printf("equal images:\n")580 for _, image := range group {581 fmt.Printf("\tmkfs.%v %v\n", image.fs.Name, image.flags)582 }583 }584 if failed != 0 {585 os.Exit(1)586 }587}588func generateImages(target *prog.Target, flagFS string, list bool) ([]*Image, error) {589 var images []*Image590 for _, fs := range fileSystems {591 if flagFS != "" && flagFS != fs.Name {592 continue593 }594 index := 0595 enumerateFlags(target, &images, &index, fs, fs.MkfsFlags, 0)596 if list {597 fmt.Printf("%v [%v images]\n", fs.Name, index)598 continue599 }600 files, err := filepath.Glob(filepath.Join("sys", targets.Linux, "test", "syz_mount_image_"+fs.Name+"_*"))601 if err != nil {602 return nil, fmt.Errorf("error reading output dir: %v", err)603 }604 for _, file := range files {605 if err := os.Remove(file); err != nil {606 return nil, fmt.Errorf("error removing output file: %v", err)607 }608 }609 }610 return images, nil611}612func enumerateFlags(target *prog.Target, images *[]*Image, index *int, fs FileSystem, flags []string, flagsIndex int) {613 if flagsIndex == len(fs.MkfsFlagCombinations) {614 *images = append(*images, &Image{615 target: target,616 fs: fs,617 flags: append([]string{}, flags...),618 index: *index,619 done: make(chan error, 1),620 })621 *index++622 return623 }624 for _, flag := range fs.MkfsFlagCombinations[flagsIndex] {625 flags1 := flags626 for _, f := range strings.Split(flag, " ") {627 if f != "" {628 flags1 = append(flags1, f)629 }630 }631 enumerateFlags(target, images, index, fs, flags1, flagsIndex+1)632 }633}634func (image *Image) generate() error {635 var err error636 for image.size = image.fs.MinSize; image.size <= 128<<20; image.size *= 2 {637 if err = image.generateSize(); err == nil {638 return nil639 }640 }641 return err642}643func (image *Image) generateSize() error {644 outFile := filepath.Join("sys", targets.Linux, "test",645 fmt.Sprintf("syz_mount_image_%v_%v", image.fs.Name, image.index))646 image.disk = outFile + ".img"647 f, err := os.Create(image.disk)648 if err != nil {649 return err650 }651 f.Close()652 if err := os.Truncate(image.disk, int64(image.size)); err != nil {653 return err654 }655 if image.fs.Mkfs == nil {656 if _, err := runCmd("mkfs."+image.fs.Name, append(image.flags, image.disk)...); err != nil {657 return err658 }659 } else {660 if err := image.fs.Mkfs(image); err != nil {661 return err662 }663 }664 if !image.fs.ReadOnly {665 // This does not work with runCmd -- sudo does not show password prompt on console.666 cmd := exec.Command("sudo", os.Args[0], "-populate", image.disk, "-fs", image.fs.Name)667 if out, err := cmd.CombinedOutput(); err != nil {668 return fmt.Errorf("image population failed: %v\n%s", err, out)669 }670 }671 data, err := ioutil.ReadFile(image.disk)672 if err != nil {673 return err674 }675 image.hash = crc32.ChecksumIEEE(data)676 out, err := writeImage(image.fs, data)677 if err != nil {678 return err679 }680 p, err := image.target.Deserialize(out, prog.Strict)681 if err != nil {682 return fmt.Errorf("failed to deserialize resulting program: %v", err)683 }684 exec := make([]byte, prog.ExecBufferSize)685 if _, err := p.SerializeForExec(exec); err != nil {686 return fmt.Errorf("failed to serialize for execution: %v", err)687 }688 return osutil.WriteFile(outFile, out)689}690// Runs under sudo in a subprocess.691func populate(disk, fs string) error {692 output, err := runCmd("losetup", "-f", "--show", "-P", disk)693 if err != nil {694 return err695 }696 loop := strings.TrimSpace(string(output))697 defer runCmd("losetup", "-d", loop)698 dir, err := ioutil.TempDir("", "syz-imagegen")699 if err != nil {700 return err701 }702 defer os.RemoveAll(dir)703 if _, err := runCmd("mount", "-t", fs, loop, dir); err != nil {704 return fmt.Errorf("%v\n%s", err, output)705 }706 defer runCmd("umount", dir)707 return populateDir(dir)708}709func populateDir(dir string) error {710 zeros := func(size int) []byte {711 return make([]byte, size)712 }713 nonzeros := func(size int) []byte {714 const fill = "syzkaller"715 return bytes.Repeat([]byte(fill), size/len(fill)+1)[:size]716 }717 if err := os.Mkdir(filepath.Join(dir, "file0"), 0777); err != nil {718 return err719 }720 if err := ioutil.WriteFile(filepath.Join(dir, "file0", "file0"), nonzeros(1050), 0777); err != nil {721 return err722 }723 os.Symlink(filepath.Join(dir, "file0", "file0"), filepath.Join(dir, "file0", "file1"))...

Full Screen

Full Screen

oxfstool.go

Source:oxfstool.go Github

copy

Full Screen

...70 }71 }72 return kind, size, err73}74func populateDir(fileSet []string, files map[string]ofile, n int) *dirTree {75 var dT dirTree76 c := len(fileSet)77 if c > n {78 sz := c / (n + 1)79 fmt.Println("sz:", sz)80 dT.Name = make([]string, n)81 dT.P = make([]*dirTree, n)82 dT.P0 = populateDir(fileSet[0:sz], files, n)83 for i := 1; i <= n; i++ {84 e := i * sz85 dT.Name[i-1] = fileSet[e]86 z := (i + 1) * sz87 if i == n {88 z = c89 }90 dT.P[i-1] = populateDir(fileSet[e+1:z], files, n)91 }92 } else {93 dT.Name = make([]string, c)94 dT.P = make([]*dirTree, c)95 for e := 0; e < c; e++ {96 dT.Name[e] = fileSet[e]97 }98 }99 return &dT100}101func produceFileData(f *os.File, outfmt int, thisSector int, data []byte) (_ int, _ int, err error) {102 sectorsize := 1024103 if outfmt == EXTENDED || outfmt == PADDEDEXTENDED {104 sectorsize = 4096105 }106 if outfmt == ORIGINAL || outfmt == EXTENDED {107 _, err = f.Seek(((int64(thisSector)/29)-1)*int64(sectorsize), 0)108 } else {109 _, err = f.Seek(PADOFFSET+((int64(thisSector)/29)*int64(sectorsize))-1, 0)110 }111 if err == nil {112 _, err = f.Write(data)113 }114 return thisSector, thisSector + 29, err115}116func produceIndirectBlock(f *os.File, ib *iblock, outfmt int) (err error) {117 if outfmt == ORIGINAL {118 _, err = f.Seek((int64(ib.A/29)-1)*1024, 0)119 } else {120 _, err = f.Seek(PADOFFSET+((int64(ib.A/29))*1024)-1, 0)121 }122 if err == nil {123 err = binary.Write(f, binary.LittleEndian, ib.E)124 }125 return err126}127func produceXIndirectBlock(f *os.File, xb *xblock, outfmt int) (err error) {128 if outfmt == EXTENDED {129 _, err = f.Seek((int64(xb.A/29)-1)*4096, 0)130 } else {131 _, err = f.Seek(PADOFFSET+((int64(xb.A/29))*4096)-1, 0)132 }133 if err == nil {134 err = binary.Write(f, binary.LittleEndian, xb.E)135 }136 return err137}138func produceFile(f *os.File, e ofile, name string, outfmt int, thisSector int, iFHP int, FHPp *oxfsgo.OXFS_HeaderPage) (_ int, _ int, _ int, _ int, err error) {139 nextFree := thisSector140 cFHP := iFHP141 FHPpBmap := 0142 if outfmt == ORIGINAL || outfmt == PADDEDORIGINAL {143 nextFree = thisSector + 29144 var hdrPage oxfsgo.OBFS_FileHeader145 fillsize := 1024 - oxfsgo.OBFS_HeaderSize146 hdrPage.Mark = oxfsgo.OBFS_HeaderMark147 hdrPage.Aleng = int32(len(e.Data)+oxfsgo.OBFS_HeaderSize) / 1024148 hdrPage.Bleng = int32(len(e.Data)+oxfsgo.OBFS_HeaderSize) % 1024149 for x, ch := range []byte(name) {150 hdrPage.Name[x] = ch151 }152 if len(e.Data) >= 1024-oxfsgo.OBFS_HeaderSize {153 copy(hdrPage.Fill[0:fillsize], e.Data[0:fillsize])154 } else {155 copy(hdrPage.Fill[0:len(e.Data)], e.Data[:])156 }157 hdrPage.Sec[0] = oxfsgo.OBFS_DiskAdr(thisSector)158 var ib iblock159 indirectUsed := false160 for n := 1; n <= int(hdrPage.Aleng); n++ {161 var dAdr int162 thisstart := fillsize + ((n - 1) * 1024)163 thisend := thisstart + 1024164 if thisend > len(e.Data) {165 thisend = len(e.Data)166 }167 dAdr, nextFree, err = produceFileData(f, outfmt, nextFree, e.Data[thisstart:thisend])168 if n < oxfsgo.OBFS_SecTabSize {169 hdrPage.Sec[n] = oxfsgo.OBFS_DiskAdr(dAdr)170 } else if ((n - oxfsgo.OBFS_SecTabSize) / 256) < oxfsgo.OBFS_ExTabSize {171 ni := n - oxfsgo.OBFS_SecTabSize172 if ni%256 == 0 {173 if indirectUsed {174 _ = produceIndirectBlock(f, &ib, outfmt)175 }176 indirectUsed = true177 hdrPage.Ext[ni/256] = oxfsgo.OBFS_DiskAdr(nextFree)178 ib.A = int64(nextFree)179 nextFree = nextFree + 29180 }181 ib.E[ni%256] = uint32(dAdr)182 } else {183 // silently truncate file that is too large184 }185 }186 if indirectUsed {187 _ = produceIndirectBlock(f, &ib, outfmt)188 }189 if outfmt == ORIGINAL {190 _, err = f.Seek((int64(thisSector/29)-1)*1024, 0)191 } else {192 _, err = f.Seek(PADOFFSET+((int64(thisSector/29))*1024)-1, 0)193 }194 if err == nil {195 err = binary.Write(f, binary.LittleEndian, hdrPage)196 }197 } else {198 if FHPp.Mark == 0 {199 FHPp.Mark = oxfsgo.OXFS_HeaderMark200 FHPp.Next = 0201 FHPp.Bmap = 0202 for i := 0; i < oxfsgo.OXFS_HdrPgSize; i++ {203 FHPp.Headers[i].Type = 4294967295 // empty slot204 }205 } else {206 FHPp.Bmap = FHPp.Bmap + 1207 if FHPp.Bmap == 63 {208 FHPp.Bmap = 0xFFFFFFFFFFFFFFFF209 if outfmt == EXTENDED {210 _, err = f.Seek((int64(cFHP/29)-1)*4096, 0)211 } else {212 _, err = f.Seek(PADOFFSET+((int64(cFHP/29))*4096)-1, 0)213 }214 if err == nil {215 err = binary.Write(f, binary.LittleEndian, *FHPp)216 }217 cFHP = nextFree218 nextFree = thisSector + 29219 FHPp.Bmap = 0220 for i := 0; i < oxfsgo.OXFS_HdrPgSize; i++ {221 FHPp.Headers[i].Type = 4294967295 // empty slot222 }223 }224 }225 FHPp.Headers[FHPp.Bmap].Type = 0 // regular file226 FHPp.Headers[FHPp.Bmap].Perm = 0227 FHPp.Headers[FHPp.Bmap].Date = 0228 FHPp.Headers[FHPp.Bmap].Length = uint64(len(e.Data))229 fmt.Println(" size ", FHPp.Headers[FHPp.Bmap].Length)230 FHPp.Headers[FHPp.Bmap].Owner = 0231 FHPp.Headers[FHPp.Bmap].Group = 0232 var xb xblock233 indirectUsed := false234 for n := 0; n <= len(e.Data)/4096; n++ {235 var dAdr int236 thisstart := n * 4096237 thisend := thisstart + 4096238 if thisend > len(e.Data) {239 thisend = len(e.Data)240 }241 dAdr, nextFree, err = produceFileData(f, outfmt, nextFree, e.Data[thisstart:thisend])242 if n < 3 {243 FHPp.Headers[FHPp.Bmap].Tab[n] = oxfsgo.OXFS_DiskAdr(dAdr)244 } else if ((n - 3) / 512) < 511 {245 ni := (n - 3) / 512246 if ni%512 == 0 {247 if indirectUsed {248 _ = produceXIndirectBlock(f, &xb, outfmt)249 }250 indirectUsed = true251 FHPp.Headers[FHPp.Bmap].Tab[3] = oxfsgo.OXFS_DiskAdr(nextFree)252 xb.A = int64(nextFree)253 nextFree = nextFree + 29254 }255 xb.E[ni%512] = uint64(dAdr)256 } else {257 // silently truncate file that is too large258 }259 }260 if indirectUsed {261 _ = produceXIndirectBlock(f, &xb, outfmt)262 }263 if outfmt == EXTENDED {264 _, err = f.Seek((int64(cFHP/29)-1)*4096, 0)265 } else {266 _, err = f.Seek(PADOFFSET+((int64(cFHP/29))*4096)-1, 0)267 }268 if err == nil {269 err = binary.Write(f, binary.LittleEndian, *FHPp)270 }271 FHPpBmap = int(FHPp.Bmap)272 }273 fmt.Println("producing file ", name)274 return thisSector, FHPpBmap, nextFree, cFHP, err275}276func produceDir(f *os.File, dT *dirTree, files map[string]ofile, outfmt int, thisSector int, iFHP int, FHPp *oxfsgo.OXFS_HeaderPage) (_ int, _ int, _ int, err error) {277 var storedAt, storedIdx int278 nextFree := thisSector + 29279 if nextFree < 65*29 {280 nextFree = 65 * 29281 }282 cFHP := iFHP283 if cFHP == 0 {284 cFHP = nextFree285 nextFree = nextFree + 29286 }287 if outfmt == ORIGINAL || outfmt == PADDEDORIGINAL {288 var dirPage oxfsgo.OBFS_DirPage289 dirPage.Mark = oxfsgo.OBFS_DirMark290 dirPage.M = int32(len(dT.Name))291 if dT.P0 != nil {292 storedAt, nextFree, _, err = produceDir(f, dT.P0, files, outfmt, nextFree, -1, FHPp)293 dirPage.P0 = oxfsgo.OBFS_DiskAdr(storedAt)294 }295 for i, _ := range dT.P {296 for x, ch := range []byte(dT.Name[i]) {297 dirPage.E[i].Name[x] = ch298 }299 storedAt, _, nextFree, _, err = produceFile(f, files[dT.Name[i]], dT.Name[i], outfmt, nextFree, -1, FHPp)300 dirPage.E[i].Adr = oxfsgo.OBFS_DiskAdr(storedAt)301 if dT.P[i] != nil {302 storedAt, nextFree, _, err = produceDir(f, dT.P[i], files, outfmt, nextFree, -1, FHPp)303 dirPage.E[i].P = oxfsgo.OBFS_DiskAdr(storedAt)304 }305 }306 if outfmt == ORIGINAL {307 _, err = f.Seek((int64(thisSector/29)-1)*1024, 0)308 } else {309 _, err = f.Seek(PADOFFSET+((int64(thisSector/29))*1024)-1, 0)310 }311 if err == nil {312 err = binary.Write(f, binary.LittleEndian, dirPage)313 }314 } else {315 var dirPage oxfsgo.OXFS_DirPage316 dirPage.Mark = oxfsgo.OXFS_DirMark317 dirPage.M = int64(len(dT.Name))318 if dT.P0 != nil {319 storedAt, nextFree, cFHP, err = produceDir(f, dT.P0, files, outfmt, nextFree, cFHP, FHPp)320 dirPage.P0 = oxfsgo.OXFS_DiskAdr(storedAt)321 }322 for i, _ := range dT.P {323 for x, ch := range []byte(dT.Name[i]) {324 dirPage.E[i].Name[x] = ch325 }326 fmt.Print(" producing ", dT.Name[i])327 _, storedIdx, nextFree, cFHP, err = produceFile(f, files[dT.Name[i]], dT.Name[i], outfmt, nextFree, cFHP, FHPp)328 dirPage.E[i].Adr = oxfsgo.OXFS_DiskAdr(cFHP)329 dirPage.E[i].I = byte(storedIdx)330 if dT.P[i] != nil {331 storedAt, nextFree, cFHP, err = produceDir(f, dT.P[i], files, outfmt, nextFree, cFHP, FHPp)332 dirPage.E[i].P = oxfsgo.OXFS_DiskAdr(storedAt)333 }334 }335 if outfmt == EXTENDED {336 _, err = f.Seek((int64(thisSector/29)-1)*4096, 0)337 } else {338 _, err = f.Seek(PADOFFSET+((int64(thisSector/29))*4096)-1, 0)339 }340 if err == nil {341 err = binary.Write(f, binary.LittleEndian, dirPage)342 fmt.Println("dirpage")343 for i := 0; i < int(dirPage.M); i++ {344 fmt.Println(" ", dirPage.E[i].Name, dirPage.E[i].Adr, dirPage.E[i].I, dirPage.E[i].P)345 }346 }347 }348 return thisSector, nextFree, cFHP, err349}350func installBootImage(f *os.File, bootImage []byte, outfmt int) (err error) {351 var i int352 var ssz int64353 if outfmt == EXTENDED || outfmt == PADDEDEXTENDED {354 ssz = 4096355 } else {356 ssz = 1024357 }358 if outfmt == ORIGINAL || outfmt == EXTENDED {359 _, err = f.Seek(ssz, 0)360 } else {361 _, err = f.Seek(PADOFFSET+ssz, 0)362 }363 if err == nil {364 i, err = f.Write(bootImage)365 fmt.Println("boot image bytes written:", i)366 }367 return err368}369func produceDirTree(files map[string]ofile, outfmt int, fw *os.File) (err error) {370 var nA []string371 var FHP oxfsgo.OXFS_HeaderPage372 var FHPp *oxfsgo.OXFS_HeaderPage373 nE := len(files)374 if _, ok := files["_BOOTIMAGE_"]; ok {375 nE = len(files) - 1376 _ = installBootImage(fw, files["_BOOTIMAGE_"].Data, outfmt)377 }378 if err == nil {379 nA = make([]string, nE)380 i := 0381 for fn, _ := range files {382 if fn != "_BOOTIMAGE_" {383 nA[i] = fn384 i++385 }386 }387 rnA := nA[:]388 sort.Strings(rnA)389 dsz := oxfsgo.OBFS_N + (oxfsgo.OBFS_N / 2)390 cFHP := -1391 if outfmt == EXTENDED || outfmt == PADDEDEXTENDED {392 dsz = oxfsgo.OXFS_N + (oxfsgo.OXFS_N / 2)393 cFHP = 0394 FHPp = &FHP395 FHPp.Mark = 0396 FHPp.Next = 0397 }398 dT := populateDir(rnA[:], files, dsz)399 _, _, _, err = produceDir(fw, dT, files, outfmt, 29, cFHP, FHPp)400 }401 return err402}403func producefs(name string, files map[string]ofile, outfmt int, force bool, osize int64, size string) (err error) {404 var fi *os.File405 keys := make([]string, 0, len(files))406 for k := range files {407 keys = append(keys, k)408 }409 sort.Strings(keys)410 if outfmt != LOCALFILES {411 if size == "same" && osize == 0 {412 err = fmt.Errorf("cannot use destination disk image size 'same' if source is files")...

Full Screen

Full Screen

cmd_auto_import_test.go

Source:cmd_auto_import_test.go Github

copy

Full Screen

1// -*- Mode: Go; indent-tabs-mode: t -*-2/*3 * Copyright (C) 2016 Canonical Ltd4 *5 * This program is free software: you can redistribute it and/or modify6 * it under the terms of the GNU General Public License version 3 as7 * published by the Free Software Foundation.8 *9 * This program is distributed in the hope that it will be useful,10 * but WITHOUT ANY WARRANTY; without even the implied warranty of11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12 * GNU General Public License for more details.13 *14 * You should have received a copy of the GNU General Public License15 * along with this program. If not, see <http://www.gnu.org/licenses/>.16 *17 */18package main_test19import (20 "fmt"21 "io/ioutil"22 "net/http"23 "os"24 "path/filepath"25 . "gopkg.in/check.v1"26 "github.com/snapcore/snapd/boot"27 snap "github.com/snapcore/snapd/cmd/snap"28 "github.com/snapcore/snapd/dirs"29 "github.com/snapcore/snapd/logger"30 "github.com/snapcore/snapd/osutil"31 "github.com/snapcore/snapd/release"32 "github.com/snapcore/snapd/snap/snaptest"33 "github.com/snapcore/snapd/testutil"34)35func makeMockMountInfo(c *C, content string) string {36 fn := filepath.Join(c.MkDir(), "mountinfo")37 err := ioutil.WriteFile(fn, []byte(content), 0644)38 c.Assert(err, IsNil)39 return fn40}41func (s *SnapSuite) TestAutoImportAssertsHappy(c *C) {42 restore := release.MockOnClassic(false)43 defer restore()44 fakeAssertData := []byte("my-assertion")45 n := 046 total := 247 s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {48 switch n {49 case 0:50 c.Check(r.Method, Equals, "POST")51 c.Check(r.URL.Path, Equals, "/v2/assertions")52 postData, err := ioutil.ReadAll(r.Body)53 c.Assert(err, IsNil)54 c.Check(postData, DeepEquals, fakeAssertData)55 fmt.Fprintln(w, `{"type": "sync", "result": {"ready": true, "status": "Done"}}`)56 n++57 case 1:58 c.Check(r.Method, Equals, "POST")59 c.Check(r.URL.Path, Equals, "/v2/users")60 postData, err := ioutil.ReadAll(r.Body)61 c.Assert(err, IsNil)62 c.Check(string(postData), Equals, `{"action":"create","sudoer":true,"known":true}`)63 fmt.Fprintln(w, `{"type": "sync", "result": [{"username": "foo"}]}`)64 n++65 default:66 c.Fatalf("unexpected request: %v (expected %d got %d)", r, total, n)67 }68 })69 fakeAssertsFn := filepath.Join(c.MkDir(), "auto-import.assert")70 err := ioutil.WriteFile(fakeAssertsFn, fakeAssertData, 0644)71 c.Assert(err, IsNil)72 mockMountInfoFmt := `7324 0 8:18 / %s rw,relatime shared:1 - ext4 /dev/sdb2 rw,errors=remount-ro,data=ordered`74 content := fmt.Sprintf(mockMountInfoFmt, filepath.Dir(fakeAssertsFn))75 restore = snap.MockMountInfoPath(makeMockMountInfo(c, content))76 defer restore()77 logbuf, restore := logger.MockLogger()78 defer restore()79 rest, err := snap.Parser(snap.Client()).ParseArgs([]string{"auto-import"})80 c.Assert(err, IsNil)81 c.Assert(rest, DeepEquals, []string{})82 c.Check(s.Stdout(), Equals, `created user "foo"`+"\n")83 // matches because we may get a:84 // "WARNING: cannot create syslog logger\n"85 // in the output86 c.Check(logbuf.String(), Matches, fmt.Sprintf("(?ms).*imported %s\n", fakeAssertsFn))87 c.Check(n, Equals, total)88}89func (s *SnapSuite) TestAutoImportAssertsNotImportedFromLoop(c *C) {90 restore := release.MockOnClassic(false)91 defer restore()92 fakeAssertData := []byte("bad-assertion")93 s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {94 // assertion is ignored, nothing is posted to this endpoint95 panic("not reached")96 })97 fakeAssertsFn := filepath.Join(c.MkDir(), "auto-import.assert")98 err := ioutil.WriteFile(fakeAssertsFn, fakeAssertData, 0644)99 c.Assert(err, IsNil)100 mockMountInfoFmtWithLoop := `10124 0 8:18 / %s rw,relatime shared:1 - squashfs /dev/loop1 rw,errors=remount-ro,data=ordered`102 content := fmt.Sprintf(mockMountInfoFmtWithLoop, filepath.Dir(fakeAssertsFn))103 restore = snap.MockMountInfoPath(makeMockMountInfo(c, content))104 defer restore()105 rest, err := snap.Parser(snap.Client()).ParseArgs([]string{"auto-import"})106 c.Assert(err, IsNil)107 c.Assert(rest, DeepEquals, []string{})108 c.Check(s.Stdout(), Equals, "")109 c.Check(s.Stderr(), Equals, "")110}111func (s *SnapSuite) TestAutoImportCandidatesHappy(c *C) {112 dirs := make([]string, 4)113 args := make([]interface{}, len(dirs))114 files := make([]string, len(dirs))115 for i := range dirs {116 dirs[i] = c.MkDir()117 args[i] = dirs[i]118 files[i] = filepath.Join(dirs[i], "auto-import.assert")119 err := ioutil.WriteFile(files[i], nil, 0644)120 c.Assert(err, IsNil)121 }122 mockMountInfoFmtWithLoop := `123too short12424 0 8:18 / %[1]s rw,relatime foo ext3 /dev/meep2 no,separator12524 0 8:18 / %[2]s rw,relatime - ext3 /dev/meep2 rw,errors=remount-ro,data=ordered12624 0 8:18 / %[3]s rw,relatime opt:1 - ext4 /dev/meep3 rw,errors=remount-ro,data=ordered12724 0 8:18 / %[4]s rw,relatime opt:1 opt:2 - ext2 /dev/meep1 rw,errors=remount-ro,data=ordered128`129 content := fmt.Sprintf(mockMountInfoFmtWithLoop, args...)130 restore := snap.MockMountInfoPath(makeMockMountInfo(c, content))131 defer restore()132 l, err := snap.AutoImportCandidates()133 c.Check(err, IsNil)134 c.Check(l, DeepEquals, files[1:])135}136func (s *SnapSuite) TestAutoImportAssertsHappyNotOnClassic(c *C) {137 restore := release.MockOnClassic(true)138 defer restore()139 fakeAssertData := []byte("my-assertion")140 s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {141 c.Errorf("auto-import on classic is disabled, but something tried to do a %q with %s", r.Method, r.URL.Path)142 })143 fakeAssertsFn := filepath.Join(c.MkDir(), "auto-import.assert")144 err := ioutil.WriteFile(fakeAssertsFn, fakeAssertData, 0644)145 c.Assert(err, IsNil)146 mockMountInfoFmt := `14724 0 8:18 / %s rw,relatime shared:1 - ext4 /dev/sdb2 rw,errors=remount-ro,data=ordered`148 content := fmt.Sprintf(mockMountInfoFmt, filepath.Dir(fakeAssertsFn))149 restore = snap.MockMountInfoPath(makeMockMountInfo(c, content))150 defer restore()151 rest, err := snap.Parser(snap.Client()).ParseArgs([]string{"auto-import"})152 c.Assert(err, IsNil)153 c.Assert(rest, DeepEquals, []string{})154 c.Check(s.Stdout(), Equals, "")155 c.Check(s.Stderr(), Equals, "auto-import is disabled on classic\n")156}157func (s *SnapSuite) TestAutoImportIntoSpool(c *C) {158 restore := release.MockOnClassic(false)159 defer restore()160 logbuf, restore := logger.MockLogger()161 defer restore()162 fakeAssertData := []byte("good-assertion")163 // ensure we can not connect164 snap.ClientConfig.BaseURL = "can-not-connect-to-this-url"165 fakeAssertsFn := filepath.Join(c.MkDir(), "auto-import.assert")166 err := ioutil.WriteFile(fakeAssertsFn, fakeAssertData, 0644)167 c.Assert(err, IsNil)168 mockMountInfoFmt := `16924 0 8:18 / %s rw,relatime shared:1 - squashfs /dev/sc1 rw,errors=remount-ro,data=ordered`170 content := fmt.Sprintf(mockMountInfoFmt, filepath.Dir(fakeAssertsFn))171 restore = snap.MockMountInfoPath(makeMockMountInfo(c, content))172 defer restore()173 rest, err := snap.Parser(snap.Client()).ParseArgs([]string{"auto-import"})174 c.Assert(err, IsNil)175 c.Assert(rest, DeepEquals, []string{})176 c.Check(s.Stdout(), Equals, "")177 // matches because we may get a:178 // "WARNING: cannot create syslog logger\n"179 // in the output180 c.Check(logbuf.String(), Matches, "(?ms).*queuing for later.*\n")181 files, err := ioutil.ReadDir(dirs.SnapAssertsSpoolDir)182 c.Assert(err, IsNil)183 c.Check(files, HasLen, 1)184 c.Check(files[0].Name(), Equals, "iOkaeet50rajLvL-0Qsf2ELrTdn3XIXRIBlDewcK02zwRi3_TJlUOTl9AaiDXmDn.assert")185}186func (s *SnapSuite) TestAutoImportFromSpoolHappy(c *C) {187 restore := release.MockOnClassic(false)188 defer restore()189 fakeAssertData := []byte("my-assertion")190 n := 0191 total := 2192 s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {193 switch n {194 case 0:195 c.Check(r.Method, Equals, "POST")196 c.Check(r.URL.Path, Equals, "/v2/assertions")197 postData, err := ioutil.ReadAll(r.Body)198 c.Assert(err, IsNil)199 c.Check(postData, DeepEquals, fakeAssertData)200 fmt.Fprintln(w, `{"type": "sync", "result": {"ready": true, "status": "Done"}}`)201 n++202 case 1:203 c.Check(r.Method, Equals, "POST")204 c.Check(r.URL.Path, Equals, "/v2/users")205 postData, err := ioutil.ReadAll(r.Body)206 c.Assert(err, IsNil)207 c.Check(string(postData), Equals, `{"action":"create","sudoer":true,"known":true}`)208 fmt.Fprintln(w, `{"type": "sync", "result": [{"username": "foo"}]}`)209 n++210 default:211 c.Fatalf("unexpected request: %v (expected %d got %d)", r, total, n)212 }213 })214 fakeAssertsFn := filepath.Join(dirs.SnapAssertsSpoolDir, "1234343")215 err := os.MkdirAll(filepath.Dir(fakeAssertsFn), 0755)216 c.Assert(err, IsNil)217 err = ioutil.WriteFile(fakeAssertsFn, fakeAssertData, 0644)218 c.Assert(err, IsNil)219 logbuf, restore := logger.MockLogger()220 defer restore()221 rest, err := snap.Parser(snap.Client()).ParseArgs([]string{"auto-import"})222 c.Assert(err, IsNil)223 c.Assert(rest, DeepEquals, []string{})224 c.Check(s.Stdout(), Equals, `created user "foo"`+"\n")225 // matches because we may get a:226 // "WARNING: cannot create syslog logger\n"227 // in the output228 c.Check(logbuf.String(), Matches, fmt.Sprintf("(?ms).*imported %s\n", fakeAssertsFn))229 c.Check(n, Equals, total)230 c.Check(osutil.FileExists(fakeAssertsFn), Equals, false)231}232func (s *SnapSuite) TestAutoImportIntoSpoolUnhappyTooBig(c *C) {233 restore := release.MockOnClassic(false)234 defer restore()235 _, restoreLogger := logger.MockLogger()236 defer restoreLogger()237 // fake data is bigger than the default assertion limit238 fakeAssertData := make([]byte, 641*1024)239 // ensure we can not connect240 snap.ClientConfig.BaseURL = "can-not-connect-to-this-url"241 fakeAssertsFn := filepath.Join(c.MkDir(), "auto-import.assert")242 err := ioutil.WriteFile(fakeAssertsFn, fakeAssertData, 0644)243 c.Assert(err, IsNil)244 mockMountInfoFmt := `24524 0 8:18 / %s rw,relatime shared:1 - squashfs /dev/sc1 rw,errors=remount-ro,data=ordered`246 content := fmt.Sprintf(mockMountInfoFmt, filepath.Dir(fakeAssertsFn))247 restore = snap.MockMountInfoPath(makeMockMountInfo(c, content))248 defer restore()249 _, err = snap.Parser(snap.Client()).ParseArgs([]string{"auto-import"})250 c.Assert(err, ErrorMatches, "cannot queue .*, file size too big: 656384")251}252func (s *SnapSuite) TestAutoImportUnhappyInInstallMode(c *C) {253 restore := release.MockOnClassic(false)254 defer restore()255 _, restoreLogger := logger.MockLogger()256 defer restoreLogger()257 mockProcCmdlinePath := filepath.Join(c.MkDir(), "cmdline")258 err := ioutil.WriteFile(mockProcCmdlinePath, []byte("foo=bar snapd_recovery_mode=install snapd_recovery_system=20191118"), 0644)259 c.Assert(err, IsNil)260 restore = boot.MockProcCmdline(mockProcCmdlinePath)261 defer restore()262 _, err = snap.Parser(snap.Client()).ParseArgs([]string{"auto-import"})263 c.Assert(err, IsNil)264 c.Check(s.Stdout(), Equals, "")265 c.Check(s.Stderr(), Equals, "auto-import is disabled in install-mode\n")266}267var mountStatic = []string{"mount", "-t", "ext4,vfat", "-o", "ro", "--make-private"}268func (s *SnapSuite) TestAutoImportFromRemovable(c *C) {269 restore := release.MockOnClassic(false)270 defer restore()271 _, restoreLogger := logger.MockLogger()272 defer restoreLogger()273 rootdir := c.MkDir()274 dirs.SetRootDir(rootdir)275 var umounts []string276 restore = snap.MockSyscallUmount(func(p string, _ int) error {277 umounts = append(umounts, p)278 return nil279 })280 defer restore()281 var tmpdirIdx int282 restore = snap.MockIoutilTempDir(func(where string, p string) (string, error) {283 c.Check(where, Equals, "")284 tmpdirIdx++285 return filepath.Join(rootdir, fmt.Sprintf("/tmp/%s%d", p, tmpdirIdx)), nil286 })287 defer restore()288 mountCmd := testutil.MockCommand(c, "mount", "")289 defer mountCmd.Restore()290 snaptest.PopulateDir(rootdir, [][]string{291 // removable without partitions292 {"sys/block/sdremovable/removable", "1\n"},293 // fixed disk294 {"sys/block/sdfixed/removable", "0\n"},295 // removable with partitions296 {"sys/block/sdpart/removable", "1\n"},297 {"sys/block/sdpart/sdpart1/partition", "1\n"},298 {"sys/block/sdpart/sdpart2/partition", "0\n"},299 {"sys/block/sdpart/sdpart3/partition", "1\n"},300 // removable but subdevices are not partitions?301 {"sys/block/sdother/removable", "1\n"},302 {"sys/block/sdother/sdother1/partition", "0\n"},303 })304 // do not mock mountinfo contents, we just want to observe whether we305 // try to mount and umount the right stuff306 _, err := snap.Parser(snap.Client()).ParseArgs([]string{"auto-import"})307 c.Assert(err, IsNil)308 c.Check(s.Stdout(), Equals, "")309 c.Check(s.Stderr(), Equals, "")310 c.Check(mountCmd.Calls(), DeepEquals, [][]string{311 append(mountStatic, "/dev/sdpart1", filepath.Join(rootdir, "/tmp/snapd-auto-import-mount-1")),312 append(mountStatic, "/dev/sdpart3", filepath.Join(rootdir, "/tmp/snapd-auto-import-mount-2")),313 append(mountStatic, "/dev/sdremovable", filepath.Join(rootdir, "/tmp/snapd-auto-import-mount-3")),314 })315 c.Check(umounts, DeepEquals, []string{316 filepath.Join(rootdir, "/tmp/snapd-auto-import-mount-3"),317 filepath.Join(rootdir, "/tmp/snapd-auto-import-mount-2"),318 filepath.Join(rootdir, "/tmp/snapd-auto-import-mount-1"),319 })320}321func (s *SnapSuite) TestAutoImportNoRemovable(c *C) {322 restore := release.MockOnClassic(false)323 defer restore()324 rootdir := c.MkDir()325 dirs.SetRootDir(rootdir)326 var umounts []string327 restore = snap.MockSyscallUmount(func(p string, _ int) error {328 return fmt.Errorf("unexpected call")329 })330 defer restore()331 mountCmd := testutil.MockCommand(c, "mount", "exit 1")332 defer mountCmd.Restore()333 snaptest.PopulateDir(rootdir, [][]string{334 // fixed disk335 {"sys/block/sdfixed/removable", "0\n"},336 // removable but subdevices are not partitions?337 {"sys/block/sdother/removable", "1\n"},338 {"sys/block/sdother/sdother1/partition", "0\n"},339 })340 _, err := snap.Parser(snap.Client()).ParseArgs([]string{"auto-import"})341 c.Assert(err, IsNil)342 c.Check(s.Stdout(), Equals, "")343 c.Check(s.Stderr(), Equals, "")344 c.Check(mountCmd.Calls(), HasLen, 0)345 c.Check(umounts, HasLen, 0)346}347func (s *SnapSuite) TestAutoImportFromMount(c *C) {348 restore := release.MockOnClassic(false)349 defer restore()350 _, restoreLogger := logger.MockLogger()351 defer restoreLogger()352 mountCmd := testutil.MockCommand(c, "mount", "")353 rootdir := c.MkDir()354 dirs.SetRootDir(rootdir)355 var umounts []string356 restore = snap.MockSyscallUmount(func(p string, _ int) error {357 c.Assert(umounts, HasLen, 0)358 umounts = append(umounts, p)359 return nil360 })361 defer restore()362 var tmpdircalls int363 restore = snap.MockIoutilTempDir(func(where string, p string) (string, error) {364 c.Check(where, Equals, "")365 c.Assert(tmpdircalls, Equals, 0)366 tmpdircalls++367 return filepath.Join(rootdir, fmt.Sprintf("/tmp/%s1", p)), nil368 })369 defer restore()370 // do not mock mountinfo contents, we just want to observe whether we371 // try to mount and umount the right stuff372 _, err := snap.Parser(snap.Client()).ParseArgs([]string{"auto-import", "--mount", "/dev/foobar"})373 c.Assert(err, IsNil)374 c.Check(s.Stdout(), Equals, "")375 c.Check(s.Stderr(), Equals, "")376 c.Check(mountCmd.Calls(), DeepEquals, [][]string{377 append(mountStatic, "/dev/foobar", filepath.Join(rootdir, "/tmp/snapd-auto-import-mount-1")),378 })379 c.Check(umounts, DeepEquals, []string{380 filepath.Join(rootdir, "/tmp/snapd-auto-import-mount-1"),381 })382}...

Full Screen

Full Screen

populateDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if len(os.Args) != 2 {4 fmt.Println("Usage: go run 2.go <directory>")5 os.Exit(1)6 }7 populateDir(dir)8}9func populateDir(dir string) {10 files, err := filepath.Glob(filepath.Join(dir, "*"))11 if err != nil {12 fmt.Println("Error getting file list")13 os.Exit(1)14 }15 for _, file := range files {16 fmt.Println(file)17 }18}

Full Screen

Full Screen

populateDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 newFile, err := os.Create("test.txt")4 if err != nil {5 log.Fatal(err)6 }7 defer newFile.Close()8 filePath := filepath.Dir("test.txt")9 populateDir(filePath)10}11func populateDir(path string) {12 newFile, err := os.Create("test1.txt")13 if err != nil {14 log.Fatal(err)15 }16 defer newFile.Close()17 filePath := filepath.Dir("test1.txt")18 newFile1, err := os.Create("test2.txt")19 if err != nil {20 log.Fatal(err)21 }22 defer newFile1.Close()23 filePath1 := filepath.Dir("test2.txt")24 newFile2, err := os.Create("test3.txt")25 if err != nil {26 log.Fatal(err)27 }28 defer newFile2.Close()29 filePath2 := filepath.Dir("test3.txt")30 newFile3, err := os.Create("test4.txt")31 if err != nil {32 log.Fatal(err)33 }34 defer newFile3.Close()35 filePath3 := filepath.Dir("test4.txt")36 newFile4, err := os.Create("test5.txt")37 if err != nil {38 log.Fatal(err)39 }40 defer newFile4.Close()41 filePath4 := filepath.Dir("test5.txt")42 newFile5, err := os.Create("test6.txt")43 if err != nil {44 log.Fatal(err)45 }46 defer newFile5.Close()

Full Screen

Full Screen

populateDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Enter the path to be populated: ")4 fmt.Scanln(&path)5 os.Chdir(path)6 fmt.Println("Enter the number of files to be created: ")7 fmt.Scanln(&n)8 for i := 0; i < n; i++ {9 fmt.Println("Enter the name of the file: ")10 fmt.Scanln(&name)11 f, err := os.Create(name)12 if err != nil {13 fmt.Println("Error creating file")14 }15 f.Close()16 }17}

Full Screen

Full Screen

populateDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 obj.populateDir()4 fmt.Println(obj.dir)5}6import (7func main() {8 obj.populateDir()9 fmt.Println(obj.dir)10}11import (12func main() {13 obj.populateDir()14 fmt.Println(obj.dir)15}16import (17func main() {18 obj.populateDir()19 fmt.Println(obj.dir)20}21import (22func main() {23 obj.populateDir()24 fmt.Println(obj.dir)25}26import (27func main() {28 obj.populateDir()29 fmt.Println(obj.dir)30}31import (32func main() {33 obj.populateDir()34 fmt.Println(obj.dir)35}36import (37func main() {

Full Screen

Full Screen

populateDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Enter the directory name")4 fmt.Scanln(&dirName)5 fmt.Println("Enter the number of sub-directories")6 fmt.Scanln(&numSubDir)7 fmt.Println("Enter the number of files")8 fmt.Scanln(&numFiles)9 err := os.Mkdir(dirPath, 0777)10 if err != nil {11 fmt.Println("Error creating directory")12 }13 for i := 0; i < numSubDir; i++ {14 fmt.Println("Enter the sub-directory name")15 fmt.Scanln(&subDirName)16 err := os.Mkdir(subDirPath, 0777)17 if err != nil {18 fmt.Println("Error creating sub-directory")19 }20 for j := 0; j < numFiles; j++ {21 fmt.Println("Enter the file name")22 fmt.Scanln(&fileName)23 f, err := os.Create(filePath)24 if err != nil {25 fmt.Println("Error creating file")26 }27 fmt.Println("Enter the file content")28 fmt.Scanln(&fileContent)29 _, err = f.WriteString(fileContent)30 if err != nil {31 fmt.Println("Error writing to file")32 }33 f.Close()34 }35 }36}37import (38func main() {39 fmt.Println("Enter the directory name")40 fmt.Scanln(&dirName)41 err := os.RemoveAll(dirPath)42 if err != nil {43 fmt.Println("Error deleting directory")44 }45}

Full Screen

Full Screen

populateDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 m := new(mainClass)4 m.populateDir()5 fmt.Println(m.dir)6 fmt.Println(len(m.dir))7}8import (9func main() {10 m := new(mainClass)11 m.populateDir()12 fmt.Println(m.dir)13 fmt.Println(len(m.dir))14}15import (16type mainClass struct {17}18func (m *mainClass) populateDir() {19 files, err := ioutil.ReadDir("./")20 if err != nil {21 fmt.Println(err)22 }23 m.dir = make(map[string]os.FileInfo)24 for _, f := range files {25 m.dir[f.Name()] = f26 }27 m.sortDir()28}29func (m *mainClass) sortDir() {30 sorted := make([]string, len(m.dir))31 for k := range m.dir {32 }33 sort.Strings(sorted)34 newDir := make(map[string]os.FileInfo)

Full Screen

Full Screen

populateDir

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 dir = new(DirectoryImpl)4 dir.populateDir("C:\\Users\\sudha\\Desktop\\GoLang")5 fmt.Println(dir)6}

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