aboutsummaryrefslogtreecommitdiff
blob: dda90251e914debd00e13ad16fbb71c12719aa9b (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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
#!/usr/bin/env python
#
#    alt-revdep-pax: this file is part of the elfix package
#    Copyright (C) 2011  Anthony G. Basile
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    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, see <http://www.gnu.org/licenses/>.
#

#
# Note: This alternative way of doing revdep-pax only
# works on Gentoo systems where NEEDED.ELF.2 all the
# information we need generated by scanelf during emerge.
#
# See /usr/lib/portage/bin/misc-functions.sh ~line 520
# echo "${arch:3};${obj};${soname};${rpath};${needed}" >> "${PORTAGE_BUILDDIR}"/build-info/NEEDED.ELF.2
#

import getopt
import os
import sys
import pax

from link_map import LinkMap

def get_input(prompt):
    """ python2/3 compat input """
    if sys.hexversion > 0x03000000:
        return input(prompt)
    else:
        return raw_input(prompt)


def print_problems(sonames_missing_library):
    sonames_missing_library = set(sonames_missing_library)
    print('\n**** SONAMES without any library files ****')
    for m in sonames_missing_library:
        print('\t%s' % m)


def run_forward(verbose):
    (object_linkings, object_reverse_linkings, library2soname, soname2library) = LinkMap().get_maps()

    sonames_missing_library = []

    for abi in object_linkings:
        for elf in object_linkings[abi]:
            try:
                (elf_str_flags, elf_bin_flags) = pax.getflags(elf)
                sv = '%s :%s ( %s )' % (elf, abi, elf_str_flags)
                s = sv
            except pax.PaxError:
                sv = '%s :%s ( %s )' % (elf, abi, '****')
                s = sv
                continue

            count = 0
            for soname in object_linkings[abi][elf]:
                try:
                    library = soname2library[(soname, abi)]
                    try:
                        (library_str_flags, library_bin_flags) = pax.getflags(library)
                    except pax.PaxError:
                        library_str_flags = '****'
                    sv = '%s\n\t%s\t%s ( %s )' % (sv, soname, library, library_str_flags)
                    if elf_str_flags != library_str_flags:
                        s = '%s\n\t%s\t%s ( %s )' % (s, soname, library, library_str_flags)
                        count = count + 1
                except KeyError:
                    sonames_missing_library.append(soname)

            if verbose:
                print('%s\n' % sv)
                if count == 0:
                    print('\tNo mismatches\n\n')
                else:
                    print('\tMismatches\n\n')
            else:
                if count != 0:
                    print('%s\n\n' % s)

    if verbose:
        print_problems(sonames_missing_library)


def run_reverse(verbose, executable_only):
    (object_linkings, object_reverse_linkings, library2soname, soname2library) = LinkMap().get_maps()

    shell_path = path = os.getenv('PATH').split(':')

    sonames_missing_library = []

    for abi in object_reverse_linkings:
        for soname in object_reverse_linkings[abi]:
            try:
                library = soname2library[(soname, abi)]
                try:
                    (library_str_flags, library_bin_flags) = pax.getflags(library)
                except pax.PaxError:
                    library_str_flags = '****'
                sv = '%s\t%s :%s ( %s )' % (soname, library, abi, library_str_flags)
                s = sv
            except KeyError:
                sonames_missing_library.append(soname)

            count = 0
            for elf in object_reverse_linkings[abi][soname]:
                try:
                    (elf_str_flags, elf_bin_flags) = pax.getflags(elf)
                except pax.PaxError:
                    elf_str_flags = '****'
                if executable_only:
                    if os.path.dirname(elf) in shell_path:
                        sv = '%s\n\t%s ( %s )' % (sv, elf, elf_str_flags)
                        if library_str_flags != elf_str_flags:
                            s = '%s\n\t%s ( %s )' % (s, elf, elf_str_flags)
                            count = count + 1
                else:
                    sv = '%s\n\t%s ( %s )' % (sv, elf, elf_str_flags)
                    if library_str_flags != elf_str_flags:
                        s = '%s\n\t%s ( %s )' % (s, elf, elf_str_flags)
                        count = count + 1

            if verbose:
                print('%s\n' % sv)
                if count == 0:
                    print('\tNo mismatches\n\n')
                else:
                    print('\tMismatches\n\n')
            else:
                if count != 0:
                    print('%s\n\n' % s)

    if verbose:
        print_problems(sonames_missing_library)


def migrate_flags(importer, exporter_str_flags, exporter_bin_flags):
    # We implement the following logic for setting the pax flags
    # on the target elf object, the IMPORTER, given that the flags
    # from the elf object we want it to match to, the EXPORTER.
    #
    #    EXPORTER    IMPORTER    RESULT
    #       On          On         On
    #       On          Off        On + Warn
    #       On          -          On
    #       Off         On         On + Warn
    #       Off         Off        Off
    #       Off         -          Off
    #       -           On         On
    #       -           Off        Off
    #       -           -          -

    #See /usr/include/elf.h for these values
    pf_flags = {
        'P':1<<4, 'p':1<<5,
        'S':1<<6, 's':1<<7,
        'M':1<<8, 'm':1<<9,
        'X':1<<10, 'x':1<<11,
        'E':1<<12, 'e':1<<13,
        'R':1<<14, 'r':1<<15
    }

    try:
        (importer_str_flags, importer_bin_flags) = pax.getflags(importer)
    except pax.PaxError:
        # The importer has no flags, so just set them
        pax.setbinflags(importer, exporter_bin_flags)
        return

    # Start with the exporter's flags
    result_bin_flags = exporter_bin_flags

    for i in range(len(importer_str_flags)):

        # The exporter's flag contradicts the importer's flag, so do nothing
        if (exporter_str_flags[i].isupper() and importer_str_flags[i].islower()) or \
           (exporter_str_flags[i].islower() and importer_str_flags[i].isupper()):

            # Revert the exporter's flag, use the importer's flag and warn
            result_bin_flags = result_bin_flags ^ pf_flags[exporter_str_flags[i]]
            result_bin_flags = result_bin_flags | pf_flags[importer_str_flags[i]]
            print('\t\tWarning: %s has %s, refusing to set to %s' % (
                importer, importer_str_flags[i], exporter_str_flags[i] )),

        # The exporter's flags is off, so use the importer's flag
        if (exporter_str_flags[i] == '-' and importer_str_flags[i] != '-'):
            result_bin_flags = result_bin_flags | pf_flags[importer_str_flags[i]]

    pax.setbinflags(importer, result_bin_flags)


def run_elf(elf, verbose, mark, allyes):
    if not os.path.exists(elf):
        print('%s\tNo such OBJECT' % elf)
        return

    try:
        (elf_str_flags, elf_bin_flags) = pax.getflags(elf)
        print('%s (%s)\n' % (elf, elf_str_flags))
    except pax.PaxError:
        print('%s: No PAX flags found\n' % elf)
        return

    (object_linkings, object_reverse_linkings, library2soname, soname2library) = LinkMap().get_maps()

    mismatched_libraries = []

    for abi in object_linkings:
        if not elf in object_linkings[abi]: # There may be no elf for that abi
            continue
        for soname in object_linkings[abi][elf]:
            try:
                library = soname2library[(soname,abi)]
                try:
                    (library_str_flags, library_bin_flags) = pax.getflags(library)
                except pax.PaxError:
                    library_str_flags = '****'
                if verbose:
                    print('\t%s\t%s :%s ( %s )' % (soname, library, abi, library_str_flags))
                if elf_str_flags != library_str_flags:
                    mismatched_libraries.append(library)
                    if not verbose:
                        print('\t%s\t%s :%s ( %s )' % (soname, library, abi, library_str_flags))
            except KeyError:
                print('%s :%s: file for soname not found' % (soname, abi))

        if len(mismatched_libraries) == 0:
            if not verbose:
                print('\tNo mismatches\n')
        else:
            print('')
            if mark:
                print('\tWill mark libraries with %s\n' % elf_str_flags)
                for library in mismatched_libraries:
                    do_marking = False
                    while True:
                        if allyes:
                            ans = 'y'
                        else:
                            ans = get_input('\tSet flags for %s :%s (y/n): ' % (library, abi))
                        if ans == 'y':
                            do_marking = True
                            break
                        elif ans == 'n':
                            do_marking = False
                            break
                        else:
                            print('\t\tPlease enter y or n')

                    if do_marking:
                        try:
                            migrate_flags(library, elf_str_flags, elf_bin_flags)
                        except pax.PaxError:
                            print('\n\tCould not set PAX flags on %s, text maybe busy' % (library, abi))

                        try:
                            (library_str_flags, library_bin_flags) = pax.getflags(library)
                            print('\n\t\t%s ( %s )\n' % (library, library_str_flags))
                        except pax.PaxError:
                            print('\n\t\t%s: Could not read PAX flags')


def run_soname(name, verbose, use_soname, mark, allyes, executable_only):
    shell_path = path = os.getenv('PATH').split(':')

    (object_linkings, object_reverse_linkings, library2soname, soname2library) = LinkMap().get_maps()

    if use_soname:
        soname = name
        abi_list = object_reverse_linkings.keys()
        for abi in abi_list:
            # There must be at least on abi with that soname
            if soname in object_reverse_linkings[abi]:
                break
        else:
            print('%s\tNo such SONAME' % soname)
            return
    else:
        try:
            (soname, abi) = library2soname[name]
            abi_list = [abi]
        except KeyError:
            print('%s\tNo such LIBRARY' % name)
            return


    mismatched_elfs = []

    for abi in abi_list:
        # An soname can belong to one or more abis
        if not soname in object_reverse_linkings[abi]:
            continue

        library = soname2library[(soname, abi)]

        try:
           (library_str_flags, library_bin_flags) = pax.getflags(library)
           print('%s\t%s :%s (%s)\n' % (soname, library, abi, library_str_flags))
        except pax.PaxError:
           print('%s :%s : No PAX flags found\n' % (library, abi))
           continue

        for elf in object_reverse_linkings[abi][soname]:
            try:
                (elf_str_flags, elf_bin_flags ) = pax.getflags(elf)
            except pax.PaxError:
                elf_str_flags = '****'
            if verbose:
                if executable_only:
                    if os.path.dirname(elf) in shell_path:
                        print('\t%s ( %s )' % (elf, elf_str_flags))
                else:
                    print('\t%s ( %s )' % (elf, elf_str_flags))
            if library_str_flags != elf_str_flags:
                if executable_only:
                    if os.path.dirname(elf) in shell_path:
                        mismatched_elfs.append(elf)
                        if not verbose:
                            print('\t%s ( %s )' % (elf, elf_str_flags))
                else:
                    mismatched_elfs.append(elf)
                    if not verbose:
                        print('\t%s ( %s )' % (elf, elf_str_flags))

        if len(mismatched_elfs) == 0:
            if not verbose:
                print('\tNo mismatches\n')
        else:
            print('')
            if mark:
                print('\tWill mark elf with %s\n' % library_str_flags)
                for elf in mismatched_elfs:
                    if executable_only:
                        if not os.path.dirname(elf) in shell_path:
                            continue
                    do_marking = False
                    while True:
                        if allyes:
                            ans = 'y'
                        else:
                            ans = get_input('\tSet flags for %s (y/n): ' % elf)
                        if ans == 'y':
                            do_marking = True
                            break
                        elif ans == 'n':
                            do_marking = False
                            break
                        else:
                            print('\t\tPlease enter y or n')
                    if do_marking:
                        try:
                            migrate_flags(elf, library_str_flags, library_bin_flags)
                        except pax.PaxError:
                            print('\n\tCould not set pax flags on %s, file is probably busy' % elf)
                            print('\tShut down all processes that use it and try again')
                        (elf_str_flags, elf_bin_flags) = pax.getflags(elf)
                        print('\n\t\t%s ( %s )\n' % (elf, elf_str_flags))


def run_usage():
    print('Package Name : elfix')
    print('Bug Reports  : http://bugs.gentoo.org/')
    print('Program Name : revdep-pax')
    print('Description  : Get or set pax flags on an ELF object')
    print('')
    print('Usage        : revdep-pax -f [-v]             print out all forward mappings for all system ELF objects')
    print('             : revdep-pax -r [-ve]            print out all reverse mappings for all system sonames')
    print('             : revdep-pax -b OBJECT  [-myv]   print all forward mappings only for OBJECT')
    print('             : revdep-pax -s SONAME  [-myve]  print all reverse mappings only for SONAME')
    print('             : revdep-pax -l LIBRARY [-myve]  print all reverse mappings only for LIBRARY file')
    print('             : revdep-pax [-h]                print out this help')
    print('             : -v                             verbose, otherwise just print mismatching objects')
    print('             : -e                             only print out executables in shell $PATH')
    print('             : -m                             don\'t just report, but mark the mismatching objects')
    print('             : -y                             assume "yes" to all prompts for marking (USE CAREFULLY!)')
    print('')


def main():
    # Are we root?
    uid = os.getuid()
    if uid != 0:
        print('This program must be run as root')
        sys.exit(1)

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hfrb:s:l:vemy')
    except getopt.GetoptError as err:
        print(str(err)) # will print something like 'option -a not recognized'
        run_usage()
        sys.exit(1)

    if len(opts) == 0:
        run_usage()
        sys.exit(1)

    do_usage   = False
    do_forward = False
    do_reverse = False

    elf     = None
    soname  = None
    library = None

    verbose = False
    executable_only = False
    mark = False
    allyes = False

    opt_count = 0

    for o, a in opts:
        if o == '-h':
            do_usage = True
            opt_count += 1
        elif o == '-f':
            do_forward = True
            opt_count += 1
        elif o == '-r':
            do_reverse = True
            opt_count += 1
        elif o == '-b':
            elf = a
            opt_count += 1
        elif o == '-s':
            soname = a
            opt_count += 1
        elif o == '-l':
            library = a
            opt_count += 1
        elif o == '-v':
            verbose = True
        elif o == '-e':
            executable_only = True
        elif o == '-m':
            mark = True
        elif o == '-y':
            allyes = True
        else:
            print('Option included in getopt but not handled here!')
            print('Please file a bug')
            sys.exit(1)

    # Only allow one of -h, -f -r -b -s
    if opt_count > 1 or do_usage:
        run_usage()
    elif do_forward:
        run_forward(verbose)
    elif do_reverse:
        run_reverse(verbose, executable_only)
    elif elf != None:
        run_elf(elf, verbose, mark, allyes)
    elif soname != None:
        run_soname(soname, verbose, True, mark, allyes, executable_only)
    elif library != None:
        library = os.path.realpath(library)
        run_soname(library, verbose, False, mark, allyes, executable_only)


if __name__ == '__main__':
    main()