summaryrefslogtreecommitdiffstats
path: root/native_client_sdk/src/tools/tests/create_nmf_test.py
blob: c0855ad16c11e949fddc99deef6499aa2b300766 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import shutil
import subprocess
import sys
import tempfile
import unittest

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PARENT_DIR = os.path.dirname(SCRIPT_DIR)
DATA_DIR = os.path.join(SCRIPT_DIR, 'data')
CHROME_SRC = os.path.dirname(os.path.dirname(os.path.dirname(PARENT_DIR)))
MOCK_DIR = os.path.join(CHROME_SRC, "third_party", "pymock")

# For the mock library
sys.path.append(MOCK_DIR)
sys.path.append(PARENT_DIR)

import create_nmf
import getos
import mock


class TestIsDynamicElf(unittest.TestCase):
  def test_arm(self):
    static_nexe = os.path.join(DATA_DIR, 'test_static_arm.nexe')
    self.assertFalse(create_nmf.IsDynamicElf(static_nexe, False))

  def test_x86_32(self):
    dyn_nexe = os.path.join(DATA_DIR, 'test_dynamic_x86_32.nexe')
    static_nexe = os.path.join(DATA_DIR, 'test_static_x86_32.nexe')
    self.assertTrue(create_nmf.IsDynamicElf(dyn_nexe, False))
    self.assertFalse(create_nmf.IsDynamicElf(static_nexe, False))

  def test_x86_64(self):
    dyn_nexe = os.path.join(DATA_DIR, 'test_dynamic_x86_64.nexe')
    static_nexe = os.path.join(DATA_DIR, 'test_static_x86_64.nexe')
    self.assertTrue(create_nmf.IsDynamicElf(dyn_nexe, True))
    self.assertFalse(create_nmf.IsDynamicElf(static_nexe, True))


class TestParseElfHeader(unittest.TestCase):
  def test_invalid_elf(self):
    self.assertRaises(create_nmf.Error, create_nmf.ParseElfHeader, __file__)

  def test_arm_elf_parse(self):
    """Test parsing of ARM elf header."""
    static_nexe = os.path.join(DATA_DIR, 'test_static_arm.nexe')
    arch, dynamic = create_nmf.ParseElfHeader(static_nexe)
    self.assertEqual(arch, 'arm')
    self.assertFalse(dynamic)

  def test_x86_32_elf_parse(self):
    """Test parsing of x86-32 elf header."""
    dyn_nexe = os.path.join(DATA_DIR, 'test_dynamic_x86_32.nexe')
    static_nexe = os.path.join(DATA_DIR, 'test_static_x86_32.nexe')

    arch, dynamic = create_nmf.ParseElfHeader(dyn_nexe)
    self.assertEqual(arch, 'x86-32')
    self.assertTrue(dynamic)

    arch, dynamic = create_nmf.ParseElfHeader(static_nexe)
    self.assertEqual(arch, 'x86-32')
    self.assertFalse(dynamic)

  def test_x86_64_elf_parse(self):
    """Test parsing of x86-64 elf header."""
    dyn_nexe = os.path.join(DATA_DIR, 'test_dynamic_x86_64.nexe')
    static_nexe = os.path.join(DATA_DIR, 'test_static_x86_64.nexe')

    arch, dynamic = create_nmf.ParseElfHeader(dyn_nexe)
    self.assertEqual(arch, 'x86-64')
    self.assertTrue(dynamic)

    arch, dynamic = create_nmf.ParseElfHeader(static_nexe)
    self.assertEqual(arch, 'x86-64')
    self.assertFalse(dynamic)


class TestDefaultLibpath(unittest.TestCase):
  def testWithoutNaClSDKRoot(self):
    """GetDefaultLibPath wihtout NACL_SDK_ROOT set

    In the absence of NACL_SDK_ROOT GetDefaultLibPath should
    return the empty list."""
    with mock.patch.dict('os.environ', clear=True):
      paths = create_nmf.GetDefaultLibPath('Debug')
    self.assertEqual(paths, [])

  def testHonorNaClSDKRoot(self):
    with mock.patch.dict('os.environ', {'NACL_SDK_ROOT': '/dummy/path'}):
      paths = create_nmf.GetDefaultLibPath('Debug')
    for path in paths:
      self.assertTrue(path.startswith('/dummy/path'))

  def testIncludesNaClPorts(self):
    with mock.patch.dict('os.environ', {'NACL_SDK_ROOT': '/dummy/path'}):
      paths = create_nmf.GetDefaultLibPath('Debug')
    self.assertTrue(any(os.path.join('ports', 'lib') in p for p in paths),
                    "naclports libpath missing: %s" % str(paths))


class TestNmfUtils(unittest.TestCase):
  """Tests for the main NmfUtils class in create_nmf."""

  def setUp(self):
    self.tempdir = None
    toolchain = os.path.join(CHROME_SRC, 'native_client', 'toolchain')
    self.toolchain = os.path.join(toolchain, '%s_x86' % getos.GetPlatform())
    self.objdump = os.path.join(self.toolchain, 'bin', 'i686-nacl-objdump')
    if os.name == 'nt':
      self.objdump += '.exe'
    self.Mktemp()
    self.dyn_nexe = self.createTestNexe('test_dynamic_x86_32.nexe', True,
                                        'i686')
    self.dyn_deps = set(['libc.so', 'runnable-ld.so',
                         'libgcc_s.so', 'libpthread.so'])

  def createTestNexe(self, name, dynamic, arch):
    """Create an empty test .nexe file for use in create_nmf tests.

    This is used rather than checking in test binaries since the
    checked in binaries depend on .so files that only exist in the
    certain SDK that build them.
    """
    compiler = os.path.join(self.toolchain, 'bin', '%s-nacl-g++' % arch)
    if os.name == 'nt':
      compiler += '.exe'
      os.environ['CYGWIN'] = 'nodosfilewarning'
    program = 'int main() { return 0; }'
    name = os.path.join(self.tempdir, name)
    cmd = [compiler, '-pthread', '-x' , 'c', '-o', name, '-']
    p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
    p.communicate(input=program)
    self.assertEqual(p.returncode, 0)
    return name

  def tearDown(self):
    if self.tempdir:
      shutil.rmtree(self.tempdir)

  def Mktemp(self):
    self.tempdir = tempfile.mkdtemp()

  def CreateNmfUtils(self, libdir=None):
    if not libdir:
      libdir = os.path.join(self.toolchain, 'x86_64-nacl', 'lib32')
    return create_nmf.NmfUtils([self.dyn_nexe],
                               lib_path=[libdir],
                               objdump=self.objdump)

  def testGetNeededStatic(self):
    nexe = os.path.join(DATA_DIR, 'test_static_x86_32.nexe')
    nmf = create_nmf.NmfUtils([nexe])
    needed = nmf.GetNeeded()

    # static nexe should have exactly one needed file
    self.assertEqual(len(needed), 1)
    self.assertEqual(needed.keys()[0], nexe)

    # arch of needed file should be x86-32
    archfile = needed.values()[0]
    self.assertEqual(archfile.arch, 'x86-32')

  def StripDependencies(self, deps):
    """Strip the dirnames and version suffixes from
    a list of nexe dependencies.

    e.g:
    /path/to/libpthread.so.1a2d3fsa -> libpthread.so
    """
    names = []
    for name in deps:
      name = os.path.basename(name)
      if '.so.' in name:
        name = name.rsplit('.', 1)[0]
      names.append(name)
    return names

  def testGetNeededDynamic(self):
    nmf = self.CreateNmfUtils()
    needed = nmf.GetNeeded()
    names = needed.keys()

    # this nexe has 5 dependencies
    expected = set(self.dyn_deps)
    expected.add(os.path.basename(self.dyn_nexe))

    basenames = set(self.StripDependencies(names))
    self.assertEqual(expected, basenames)

  def testStageDependencies(self):
    self.Mktemp()
    nmf = self.CreateNmfUtils()
    #create_nmf.DebugPrint.debug_mode = True
    #create_nmf.Trace.verbose = True

    # Stage dependencies
    nmf.StageDependencies(self.tempdir)

    # Verify directory contents
    contents = set(os.listdir(self.tempdir))
    expectedContents = set((os.path.basename(self.dyn_nexe), 'lib32'))
    self.assertEqual(contents, expectedContents)

    contents = os.listdir(os.path.join(self.tempdir, 'lib32'))
    contents = self.StripDependencies(contents)
    contents = set(contents)
    expectedContents = self.dyn_deps
    self.assertEqual(contents, expectedContents)

  def testMissingArchLibrary(self):
    self.Mktemp()
    nmf = self.CreateNmfUtils()
    # CreateNmfUtils uses the 32-bit library path, but not the 64-bit one
    # so searching for a 32-bit library should succeed while searching for
    # a 64-bit one should fail.
    nmf.GleanFromObjdump(['libgcc_s.so.1'], 'x86-32')
    self.assertRaises(create_nmf.Error,
                      nmf.GleanFromObjdump, ['libgcc_s.so.1'], 'x86-64')


if __name__ == '__main__':
  unittest.main()