Created
July 14, 2018 18:22
-
-
Save jpittis/414fb8ffc403f8ea0f889f5fabd6178c to your computer and use it in GitHub Desktop.
Playing around with mid write crashing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"math/rand" | |
"os" | |
"time" | |
) | |
func genNumbers(n int) []int { | |
words := make([]int, n) | |
for i := 0; i < n; i++ { | |
words[i] = rand.Intn(n) | |
} | |
return words | |
} | |
func writeFile(data []byte, filename string) error { | |
file, err := os.Create(filename) | |
if err != nil { | |
return err | |
} | |
defer file.Close() | |
fmt.Println("@@@ commencing file write @@@") | |
_, err = file.Write(data) | |
return err | |
} | |
var lastTime time.Time | |
func printTime(msg string) { | |
current := time.Now() | |
fmt.Println(msg, "took", current.Sub(lastTime)) | |
lastTime = current | |
} | |
func spawnRandomCrash(n int) { | |
timeUntilCrash := rand.Intn(n) | |
<-time.After(time.Duration(timeUntilCrash) * time.Millisecond) | |
os.Exit(1) | |
} | |
// Test for failures with the following: | |
// go build test.go && ./test; cat test.json | json_verify | |
// | |
// Which should produce somtthing like this: | |
// | |
// $ go build test.go && ./test; cat test.json | json_verify | |
// genNumbers took 341.819596ms | |
// marshal took 560.629396ms | |
// @@@ commencing file write @@@ | |
// lexical error: invalid char in json text. | |
// 931774,5077342,4984661,1921838 | |
// (right here) ------^ | |
// JSON is invalid | |
// | |
// If JSON is valid, you will likely want to tweak the param to spawnRandomCrash to be | |
// close to the time to took to run writeFile. | |
func main() { | |
lastTime = time.Now() | |
words := genNumbers(10000000) | |
printTime("genNumbers") | |
data, err := json.Marshal(words) | |
if err != nil { | |
log.Fatal(err) | |
} | |
printTime("marshal") | |
go spawnRandomCrash(30) | |
err = writeFile(data, "test.json") | |
if err != nil { | |
log.Fatal(err) | |
} | |
printTime("writeFile") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment