Exemplo n.º 1
0
// extract extracts the original sound from the input video.
func extract(in string) error {
	// Probe to determine the audio codec.
	cmd := exec.Command("ffprobe", "-show_streams", "-select_streams", "a", in)
	buf, err := cmd.Output()
	if err != nil {
		return fmt.Errorf("audio codec probe failed; %v", err)
	}
	re := regexp.MustCompile("codec_name=(.*)")
	matches := re.FindSubmatch(buf)
	if len(matches) < 2 {
		return fmt.Errorf("unable to locate codec_name")
	}
	codec := string(matches[1])

	// Copy the original sound from the input video.
	stderr := new(bytes.Buffer)
	out := fmt.Sprintf("%s.%s", pathutil.TrimExt(in), codec)
	cmd = exec.Command("ffmpeg", "-i", in, "-vn", "-y", "-acodec", "copy", out)
	cmd.Stderr = stderr
	err = cmd.Run()
	if err != nil {
		log.Println(stderr.String())
		return err
	}
	fmt.Printf("Created %q.\n", out)

	return nil
}
Exemplo n.º 2
0
// dump stores the graph as a DOT file and an image representation of the graph
// as a PNG file with filenames based on "-o" flag.
func dump(graph *dot.Graph) error {
	// Store graph to DOT file.
	dotPath := flagOut
	if !flagQuiet {
		log.Printf("Creating: %q\n", dotPath)
	}
	err := ioutil.WriteFile(dotPath, []byte(graph.String()), 0644)
	if err != nil {
		return errutil.Err(err)
	}

	// Generate an image representation of the graph.
	if flagImage {
		pngPath := pathutil.TrimExt(dotPath) + ".png"
		if !flagQuiet {
			log.Printf("Creating: %q\n", pngPath)
		}
		cmd := exec.Command("dot", "-Tpng", "-o", pngPath, dotPath)
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		err = cmd.Run()
		if err != nil {
			return errutil.Err(err)
		}
	}

	return nil
}
Exemplo n.º 3
0
// flac2wav converts the provided FLAC file to a WAV file.
func flac2wav(path string) error {
	// Open FLAC file.
	stream, err := flac.Open(path)
	if err != nil {
		return err
	}
	defer stream.Close()

	// Create WAV file.
	wavPath := pathutil.TrimExt(path) + ".wav"
	if !flagForce {
		exists, err := osutil.Exists(wavPath)
		if err != nil {
			return err
		}
		if exists {
			return fmt.Errorf("the file %q exists already", wavPath)
		}
	}
	fw, err := os.Create(wavPath)
	if err != nil {
		return err
	}
	defer fw.Close()

	// Create WAV encoder.
	conf := audio.Config{
		Channels:   int(stream.Info.NChannels),
		SampleRate: int(stream.Info.SampleRate),
	}
	enc, err := wav.NewEncoder(fw, conf)
	if err != nil {
		return err
	}
	defer enc.Close()

	for {
		// Decode FLAC audio samples.
		frame, err := stream.ParseNext()
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}

		// Encode WAV audio samples.
		samples := make(audio.Int16, 1)
		for i := 0; i < int(frame.BlockSize); i++ {
			for _, subframe := range frame.Subframes {
				samples[0] = int16(subframe.Samples[i])
				_, err = enc.Write(samples)
				if err != nil {
					return err
				}
			}
		}
	}

	return nil
}
Exemplo n.º 4
0
// ll2go parses the provided LLVM IR assembly file and decompiles it to Go
// source code.
func ll2go(llPath string) error {
	// File name and file path without extension.
	baseName := pathutil.FileName(llPath)
	basePath := pathutil.TrimExt(llPath)

	// TODO: Create graphs in /tmp/xxx_graphs/*.dot

	// Create temporary foo.dot file, e.g.
	//
	//    foo.ll -> foo_graphs/*.dot
	dotDir := basePath + "_graphs"
	if ok, _ := osutil.Exists(dotDir); !ok {
		if !flagQuiet {
			log.Printf("Creating control flow graphs for %q.\n", filepath.Base(llPath))
		}
		cmd := exec.Command("ll2dot", "-q", "-funcs", flagFuncs, "-f", llPath)
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		err := cmd.Run()
		if err != nil {
			return errutil.Err(err)
		}
	}

	// Create temporary foo.bc file, e.g.
	//
	//    foo.ll -> foo.bc
	bcPath := fmt.Sprintf("/tmp/%s.bc", baseName)
	cmd := exec.Command("llvm-as", "-o", bcPath, llPath)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		return errutil.Err(err)
	}

	// Remove temporary foo.bc file.
	defer func() {
		err = os.Remove(bcPath)
		if err != nil {
			log.Fatalln(errutil.Err(err))
		}
	}()

	// Parse foo.bc
	module, err := llvm.ParseBitcodeFile(bcPath)
	if err != nil {
		return errutil.Err(err)
	}
	defer module.Dispose()

	// Get function names.
	var funcNames []string
	if len(flagFuncs) > 0 {
		// Get function names from command line flag:
		//
		//    -funcs="foo,bar"
		funcNames = strings.Split(flagFuncs, ",")
	} else {
		// Get all function names.
		for llFunc := module.FirstFunction(); !llFunc.IsNil(); llFunc = llvm.NextFunction(llFunc) {
			if llFunc.IsDeclaration() {
				// Ignore function declarations (e.g. functions without bodies).
				continue
			}
			funcNames = append(funcNames, llFunc.Name())
		}
	}

	// Locate package name.
	pkgName := flagPkgName
	if len(flagPkgName) == 0 {
		pkgName = baseName
		for _, funcName := range funcNames {
			if funcName == "main" {
				pkgName = "main"
				break
			}
		}
	}

	// Create foo.go.
	file := &ast.File{
		Name: newIdent(pkgName),
	}

	// TODO: Implement support for global variables.

	// Parse each function.
	for _, funcName := range funcNames {
		if !flagQuiet {
			log.Printf("Parsing function: %q\n", funcName)
		}
		graph, err := parseCFG(basePath, funcName)
		if err != nil {
			return errutil.Err(err)
		}

		// Structure the CFG.
		dotDir := basePath + "_graphs"
		dotName := funcName + ".dot"
		dotPath := path.Join(dotDir, dotName)
		jsonName := funcName + ".json"
		jsonPath := path.Join(dotDir, jsonName)
		if ok, _ := osutil.Exists(jsonPath); !ok {
			cmd := exec.Command("restructure", "-o", jsonPath, dotPath)
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			if !flagQuiet {
				log.Printf("Structuring function: %q\n", funcName)
			}
			err = cmd.Run()
			if err != nil {
				return errutil.Err(err)
			}
		}
		var hprims []*xprimitive.Primitive
		fr, err := os.Open(jsonPath)
		if err != nil {
			return errutil.Err(err)
		}
		defer fr.Close()
		dec := json.NewDecoder(fr)
		err = dec.Decode(&hprims)
		if err != nil {
			return errutil.Err(err)
		}

		f, err := parseFunc(graph, module, funcName, hprims)
		if err != nil {
			return errutil.Err(err)
		}
		file.Decls = append(file.Decls, f)
		if flagVerbose && !flagQuiet {
			printFunc(f)
		}
	}

	// Store Go source code to file.
	goPath := basePath + ".go"
	if !flagQuiet {
		log.Printf("Creating: %q\n", goPath)
	}
	return storeFile(goPath, file)
}
Exemplo n.º 5
0
// ll2dot parses the provided LLVM IR assembly file and generates a control flow
// graph for each of its defined functions using one node per basic block.
func ll2dot(llPath string) error {
	// File name and file path without extension.
	baseName := pathutil.FileName(llPath)
	basePath := pathutil.TrimExt(llPath)

	// Create temporary foo.bc file, e.g.
	//
	//    foo.ll -> foo.bc
	bcPath := fmt.Sprintf("/tmp/%s.bc", baseName)
	cmd := exec.Command("llvm-as", "-o", bcPath, llPath)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		return errutil.Err(err)
	}

	// Remove temporary foo.bc file.
	defer func() {
		err = os.Remove(bcPath)
		if err != nil {
			log.Fatalln(errutil.Err(err))
		}
	}()

	// Create output directory for the control flow graphs.
	dotDir := basePath + "_graphs"
	if flagForce {
		// Force remove existing graph directory.
		err = os.RemoveAll(dotDir)
		if err != nil {
			return errutil.Err(err)
		}
	}
	err = os.Mkdir(dotDir, 0755)
	if err != nil {
		return errutil.Err(err)
	}

	// Parse foo.bc
	module, err := llvm.ParseBitcodeFile(bcPath)
	if err != nil {
		return errutil.Err(err)
	}
	defer module.Dispose()

	// Get function names.
	var funcNames []string
	if len(flagFuncs) > 0 {
		// Get function names from command line flag:
		//
		//    -funcs="foo,bar"
		funcNames = strings.Split(flagFuncs, ",")
	} else {
		// Get all function names.
		for f := module.FirstFunction(); !f.IsNil(); f = llvm.NextFunction(f) {
			if f.IsDeclaration() {
				// Ignore function declarations (e.g. functions without bodies).
				continue
			}
			funcNames = append(funcNames, f.Name())
		}
	}

	// Generate a control flow graph for each function.
	for _, funcName := range funcNames {
		// Generate control flow graph.
		if !flagQuiet {
			log.Printf("Parsing function: %q\n", funcName)
		}
		graph, err := createCFG(module, funcName)
		if err != nil {
			return errutil.Err(err)
		}

		// Store the control flow graph.
		//
		// For a source file "foo.ll" containing the functions "bar" and "baz" the
		// following DOT files will be created:
		//
		//    foo_graphs/bar.dot
		//    foo_graphs/baz.dot
		dotName := funcName + ".dot"
		dotPath := filepath.Join(dotDir, dotName)
		if !flagQuiet {
			log.Printf("Creating: %q\n", dotPath)
		}
		buf := []byte(graph.String())
		err = ioutil.WriteFile(dotPath, buf, 0644)
		if err != nil {
			return errutil.Err(err)
		}

		// Generate an image representation of the control flow graph.
		if flagImage {
			pngName := funcName + ".png"
			pngPath := filepath.Join(dotDir, pngName)
			if !flagQuiet {
				log.Printf("Creating: %q\n", pngPath)
			}
			cmd := exec.Command("dot", "-Tpng", "-o", pngPath, dotPath)
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			err = cmd.Run()
			if err != nil {
				return errutil.Err(err)
			}
		}
	}

	return nil
}
Exemplo n.º 6
0
// flac2wav converts the provided FLAC file to a WAV file.
func flac2wav(path string) error {
	// Open FLAC file.
	fr, err := os.Open(path)
	if err != nil {
		return err
	}
	defer fr.Close()

	// Create FLAC decoder.
	dec, magic, err := audio.NewDecoder(fr)
	if err != nil {
		return err
	}
	fmt.Println("magic:", magic)
	conf := dec.Config()
	fmt.Println("conf:", conf)

	// Create WAV file.
	wavPath := pathutil.TrimExt(path) + ".wav"
	if !flagForce {
		exists, err := osutil.Exists(wavPath)
		if err != nil {
			return err
		}
		if exists {
			return fmt.Errorf("the file %q exists already", wavPath)
		}
	}
	fw, err := os.Create(wavPath)
	if err != nil {
		return err
	}
	defer fw.Close()

	// Create WAV encoder.
	enc, err := wav.NewEncoder(fw, conf)
	if err != nil {
		return err
	}
	defer enc.Close()

	// Encode WAV audio samples copied from the FLAC decoder.
	// TODO(u): Replace with audio.Copy as soon as that doesn't cause audio
	// sample conversions.
	buf := make(audio.PCM16Samples, (32*1024)/8)
	for {
		nr, er := dec.Read(buf)
		if nr > 0 {
			nw, ew := enc.Write(buf[0:nr])
			if ew != nil {
				return ew
			}
			if nr != nw {
				return audio.ErrShortWrite
			}
		}
		if er == audio.EOS {
			return nil
		}
		if er != nil {
			return er
		}
	}
}