github.com/coreos/mantle@v0.13.0/system/targen/ldd.go (about)

     1  // Copyright 2016 CoreOS, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package targen
    16  
    17  import (
    18  	"bufio"
    19  	"bytes"
    20  	"path/filepath"
    21  	"strings"
    22  
    23  	"github.com/coreos/mantle/system/exec"
    24  )
    25  
    26  // return a slice of strings that are the library dependencies of binary.
    27  // returns a nil slice if the binary is static
    28  func ldd(binary string) ([]string, error) {
    29  	c := exec.Command("ldd", binary)
    30  
    31  	// let's not get LD_PRELOAD invovled.
    32  	c.Env = []string{}
    33  
    34  	out, err := c.CombinedOutput()
    35  	if err != nil {
    36  		// static binaries have no libs (barring dlopened ones, which we can't find)
    37  		if strings.Contains(string(out), "not a dynamic executable") {
    38  			return nil, nil
    39  		}
    40  
    41  		return nil, err
    42  	}
    43  
    44  	buf := bytes.NewBuffer(out)
    45  	sc := bufio.NewScanner(buf)
    46  	sc.Split(bufio.ScanWords)
    47  
    48  	var libs []string
    49  	for sc.Scan() {
    50  		w := sc.Text()
    51  		if filepath.IsAbs(w) {
    52  			libs = append(libs, w)
    53  		}
    54  	}
    55  
    56  	return libs, nil
    57  }