aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/relocate_sdk.py
blob: 992db5c47d1531478e00d19c721a5b476970315c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

@media only all and (prefers-color-scheme: dark) {
.highlight .hll { background-color: #49483e }
.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #66d9ef } /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #f8f8f2 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #f8f8f2 } /* Punctuation */
.highlight .ch { color: #75715e } /* Comment.Hashbang */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .cpf { color: #75715e } /* Comment.PreprocFile */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .gd { color: #f92672 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gi { color: #a6e22e } /* Generic.Inserted */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #75715e } /* Generic.Subheading */
.highlight .kc { color: #66d9ef } /* Keyword.Constant */
.highlight .kd { color: #66d9ef } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
.highlight .kr { color: #66d9ef } /* Keyword.Reserved */
.highlight .kt { color: #66d9ef } /* Keyword.Type */
.highlight .ld { color: #e6db74 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #e6db74 } /* Literal.String */
.highlight .na { color: #a6e22e } /* Name.Attribute */
.highlight .nb { color: #f8f8f2 } /* Name.Builtin */
.highlight .nc { color: #a6e22e } /* Name.Class */
.highlight .no { color: #66d9ef } /* Name.Constant */
.highlight .nd { color: #a6e22e } /* Name.Decorator */
.highlight .ni { color: #f8f8f2 } /* Name.Entity */
.highlight .ne { color: #a6e22e } /* Name.Exception */
.highlight .nf { color: #a6e22e } /* Name.Function */
.highlight .nl { color: #f8f8f2 } /* Name.Label */
.highlight .nn { color: #f8f8f2 } /* Name.Namespace */
.highlight .nx { color: #a6e22e } /* Name.Other */
.highlight .py { color: #f8f8f2 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #f8f8f2 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #f8f8f2 } /* Text.Whitespace */
.highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sa { color: #e6db74 } /* Literal.String.Affix */
.highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
.highlight .sc { color: #e6db74 } /* Literal.String.Char */
.highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
.highlight .sd { color: #e6db74 } /* Literal.String.Doc */
.highlight .s2 { color: #e6db74 } /* Literal.String.Double */
.highlight .se { color: #ae81ff } /* Literal.String.Escape */
.highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
.highlight .si { color: #e6db74 } /* Literal.String.Interpol */
.highlight .sx { color: #e6db74 } /* Literal.String.Other */
.highlight .sr { color: #e6db74 } /* Literal.String.Regex */
.highlight .s1 { color: #e6db74 } /* Literal.String.Single */
.highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
.highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #a6e22e } /* Name.Function.Magic */
.highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
.highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */
.highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */
.highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */
.highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */
}
@media (prefers-color-scheme: light) {
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { co
#!/usr/bin/env python
#
# Copyright (c) 2012 Intel Corporation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# DESCRIPTION
# This script is called by the SDK installer script. It replaces the dynamic
# loader path in all binaries and also fixes the SYSDIR paths/lengths and the
# location of ld.so.cache in the dynamic loader binary
#
# AUTHORS
# Laurentiu Palcu <laurentiu.palcu@intel.com>
#

import struct
import sys
import stat
import os
import re
import errno

if sys.version < '3':
    def b(x):
        return x
else:
    def b(x):
        return x.encode(sys.getfilesystemencoding())

old_prefix = re.compile(b("##DEFAULT_INSTALL_DIR##"))

def get_arch():
    f.seek(0)
    e_ident =f.read(16)
    ei_mag0,ei_mag1_3,ei_class = struct.unpack("<B3sB11x", e_ident)

    if (ei_mag0 != 0x7f and ei_mag1_3 != "ELF") or ei_class == 0:
        return 0

    if ei_class == 1:
        return 32
    elif ei_class == 2:
        return 64

def parse_elf_header():
    global e_type, e_machine, e_version, e_entry, e_phoff, e_shoff, e_flags,\
           e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx

    f.seek(0)
    elf_header = f.read(64)

    if arch == 32:
        # 32bit
        hdr_fmt = "<HHILLLIHHHHHH"
        hdr_size = 52
    else:
        # 64bit
        hdr_fmt = "<HHIQQQIHHHHHH"
        hdr_size = 64

    e_type, e_machine, e_version, e_entry, e_phoff, e_shoff, e_flags,\
    e_ehsize, e_phentsize, e_phnum, e_shentsize, e_shnum, e_shstrndx =\
        struct.unpack(hdr_fmt, elf_header[16:hdr_size])

def change_interpreter(elf_file_name):
    if arch == 32:
        ph_fmt = "<IIIIIIII"
    else:
        ph_fmt = "<IIQQQQQQ"

    """ look for PT_INTERP section """
    for i in range(0,e_phnum):
        f.seek(e_phoff + i * e_phentsize)
        ph_hdr = f.read(e_phentsize)
        if arch == 32:
            # 32bit
            p_type, p_offset, p_vaddr, p_paddr, p_filesz,\
                p_memsz, p_flags, p_align = struct.unpack(ph_fmt, ph_hdr)
        else:
            # 64bit
            p_type, p_flags, p_offset, p_vaddr, p_paddr, \
            p_filesz, p_memsz, p_align = struct.unpack(ph_fmt, ph_hdr)

        """ change interpreter """
        if p_type == 3:
            # PT_INTERP section
            f.seek(p_offset)
            # External SDKs with mixed pre-compiled binaries should not get
            # relocated so look for some variant of /lib
            fname = f.read(11)
            if fname.startswith(b("/lib/")) or fname.startswith(b("/lib64/")) or \
               fname.startswith(b("/lib32/")) or fname.startswith(b("/usr/lib32/")) or \
               fname.startswith(b("/usr/lib32/")) or fname.startswith(b("/usr/lib64/")):
                break
            if (len(new_dl_path) >= p_filesz):
                print("ERROR: could not relocate %s, interp size = %i and %i is needed." \
                    % (elf_file_name, p_memsz, len(new_dl_path) + 1))
                break
            dl_path = new_dl_path + b("\0") * (p_filesz - len(new_dl_path))
            f.seek(p_offset)
            f.write(dl_path)
            break

def change_dl_sysdirs():
    if arch == 32:
        sh_fmt = "<IIIIIIIIII"
    else:
        sh_fmt = "<IIQQQQIIQQ"

    """ read section string table """
    f.seek(e_shoff + e_shstrndx * e_shentsize)
    sh_hdr = f.read(e_shentsize)
    if arch == 32:
        sh_offset, sh_size = struct.unpack("<16xII16x", sh_hdr)
    else:
        sh_offset, sh_size = struct.unpack("<24xQQ24x", sh_hdr)

    f.seek(sh_offset)
    sh_strtab = f.read(sh_size)

    sysdirs = sysdirs_len = ""

    """ change ld.so.cache path and default libs path for dynamic loader """
    for i in range(0,e_shnum):
        f.seek(e_shoff + i * e_shentsize)
        sh_hdr = f.read(e_shentsize)

        sh_name, sh_type, sh_flags, sh_addr, sh_offset, sh_size, sh_link,\
            sh_info, sh_addralign, sh_entsize = struct.unpack(sh_fmt, sh_hdr)

        name = sh_strtab[sh_name:sh_strtab.find(b("\0"), sh_name)]

        """ look only into SHT_PROGBITS sections """
        if sh_type == 1:
            f.seek(sh_offset)
            """ default library paths cannot be changed on the fly because  """
            """ the string lengths have to be changed too.                  """
            if name == b(".sysdirs"):
                sysdirs = f.read(sh_size)
                sysdirs_off = sh_offset
                sysdirs_sect_size = sh_size
            elif name == b(".sysdirslen"):
                sysdirslen = f.read(sh_size)
                sysdirslen_off = sh_offset
            elif name == b(".ldsocache"):
                ldsocache_path = f.read(sh_size)
                new_ldsocache_path = old_prefix.sub(new_prefix, ldsocache_path)
                # pad with zeros
                new_ldsocache_path += b("\0") * (sh_size - len(new_ldsocache_path))
                # write it back
                f.seek(sh_offset)
                f.write(new_ldsocache_path)
            elif name == b(".gccrelocprefix"):
                offset = 0
                while (offset + 4096) <= sh_size:
                    path = f.read(4096)
                    new_path = old_prefix.sub(new_prefix, path)
                    # pad with zeros
                    new_path += b("\0") * (4096 - len(new_path))
                    #print "Changing %s to %s at %s" % (str(path), str(new_path), str(offset))
                    # write it back
                    f.seek(sh_offset + offset)
                    f.write(new_path)
                    offset = offset + 4096
    if sysdirs != "" and sysdirslen != "":
        paths = sysdirs.split(b("\0"))
        sysdirs = b("")
        sysdirslen = b("")
        for path in paths:
            """ exit the loop when we encounter first empty string """
            if path == b(""):
                break

            new_path = old_prefix.sub(new_prefix, path)
            sysdirs += new_path + b("\0")

            if arch == 32:
                sysdirslen += struct.pack("<L", len(new_path))
            else:
                sysdirslen += struct.pack("<Q", len(new_path))

        """ pad with zeros """
        sysdirs += b("\0") * (sysdirs_sect_size - len(sysdirs))

        """ write the sections back """
        f.seek(sysdirs_off)
        f.write(sysdirs)
        f.seek(sysdirslen_off)
        f.write(sysdirslen)

# MAIN
if len(sys.argv) < 4:
    sys.exit(-1)

# In python > 3, strings may also contain Unicode characters. So, convert
# them to bytes
if sys.version_info < (3,):
    new_prefix = sys.argv[1]
    new_dl_path = sys.argv[2]
else:
    new_prefix = sys.argv[1].encode()
    new_dl_path = sys.argv[2].encode()

executables_list = sys.argv[3:]

for e in executables_list:
    perms = os.stat(e)[stat.ST_MODE]
    if os.access(e, os.W_OK|os.R_OK):
        perms = None
    else:
        os.chmod(e, perms|stat.S_IRWXU)

    try:
        f = open(e, "r+b")
    except IOError:
        exctype, ioex = sys.exc_info()[:2]
        if ioex.errno == errno.ETXTBSY:
            print("Could not open %s. File used by another process.\nPlease "\
                  "make sure you exit all processes that might use any SDK "\
                  "binaries." % e)
        else:
            print("Could not open %s: %s(%d)" % (e, ioex.strerror, ioex.errno))
        sys.exit(-1)

    # Save old size and do a size check at the end. Just a safety measure.
    old_size = os.path.getsize(e)
    if old_size >= 64:
        arch = get_arch()
        if arch:
            parse_elf_header()
            change_interpreter(e)
            change_dl_sysdirs()

    """ change permissions back """
    if perms:
        os.chmod(e, perms)

    f.close()

    if old_size != os.path.getsize(e):
        print("New file size for %s is different. Looks like a relocation error!", e)
        sys.exit(-1)