Merge branch 'org.openembedded.dev' of ssh+git://git@git.openembedded.net/openembedde...
[openembedded.git] / classes / insane.bbclass
1 # BB Class inspired by ebuild.sh
2 #
3 # This class will test files after installation for certain
4 # security issues and other kind of issues.
5 #
6 # Checks we do:
7 #  -Check the ownership and permissions
8 #  -Check the RUNTIME path for the $TMPDIR
9 #  -Check if .la files wrongly point to workdir
10 #  -Check if .pc files wrongly point to workdir
11 #  -Check if packages contains .debug directories or .so files
12 #   where they should be in -dev or -dbg
13 #  -Check if config.log contains traces to broken autoconf tests
14
15
16 #
17 # We need to have the scanelf utility as soon as
18 # possible and this is contained within the pax-utils-native.
19 # The package.bbclass can help us here.
20 #
21 inherit package
22 PACKAGE_DEPENDS += "pax-utils-native desktop-file-utils-native"
23 PACKAGEFUNCS += " do_package_qa "
24
25
26 #
27 # dictionary for elf headers
28 #
29 # feel free to add and correct.
30 #
31 #           TARGET_OS  TARGET_ARCH   MACHINE, OSABI, ABIVERSION, Little Endian, 32bit?
32 def package_qa_get_machine_dict():
33     return {
34             "darwin9" : { 
35                         "arm" :       (40,     0,    0,          True,          True),
36                       },
37             "linux" : { 
38                         "arm" :       (40,    97,    0,          True,          True),
39                         "armeb":      (40,    97,    0,          False,         True),
40                         "powerpc":    (20,     0,    0,          False,         True),
41                         "i386":       ( 3,     0,    0,          True,          True),
42                         "i486":       ( 3,     0,    0,          True,          True),
43                         "i586":       ( 3,     0,    0,          True,          True),
44                         "i686":       ( 3,     0,    0,          True,          True),
45                         "x86_64":     (62,     0,    0,          True,          False),
46                         "ia64":       (50,     0,    0,          True,          False),
47                         "alpha":      (36902,  0,    0,          True,          False),
48                         "hppa":       (15,     3,    0,          False,         True),
49                         "m68k":       ( 4,     0,    0,          False,         True),
50                         "mips":       ( 8,     0,    0,          False,         True),
51                         "mipsel":     ( 8,     0,    0,          True,          True),
52                         "s390":       (22,     0,    0,          False,         True),
53                         "sh4":        (42,     0,    0,          True,          True),
54                         "sparc":      ( 2,     0,    0,          False,         True),
55                       },
56             "linux-uclibc" : { 
57                         "arm" :       (  40,    97,    0,          True,          True),
58                         "armeb":      (  40,    97,    0,          False,         True),
59                         "powerpc":    (  20,     0,    0,          False,         True),
60                         "i386":       (   3,     0,    0,          True,          True),
61                         "i486":       (   3,     0,    0,          True,          True),
62                         "i586":       (   3,     0,    0,          True,          True),
63                         "i686":       (   3,     0,    0,          True,          True),
64                         "mips":       (   8,     0,    0,          False,         True),
65                         "mipsel":     (   8,     0,    0,          True,          True),
66                         "avr32":      (6317,     0,    0,          False,         True),
67                         "sh4":        (42,       0,    0,          True,          True),
68
69                       },
70             "uclinux-uclibc" : {
71                         "bfin":       ( 106,     0,    0,          True,         True),
72                       }, 
73             "linux-gnueabi" : {
74                         "arm" :       (40,     0,    0,          True,          True),
75                         "armeb" :     (40,     0,    0,          False,         True),
76                       },
77             "linux-uclibceabi" : {
78                         "arm" :       (40,     0,    0,          True,          True),
79                         "armeb" :     (40,     0,    0,          False,         True),
80                       },
81             "linux-gnuspe" : {
82                         "powerpc":    (20,     0,    0,          False,         True),
83                       },
84             "linux-uclibcspe" : {
85                         "powerpc":    (20,     0,    0,          False,         True),
86                       },
87
88        }
89
90 # factory for a class, embedded in a method
91 def package_qa_get_elf(path, bits32):
92     class ELFFile:
93         EI_NIDENT = 16
94
95         EI_CLASS      = 4
96         EI_DATA       = 5
97         EI_VERSION    = 6
98         EI_OSABI      = 7
99         EI_ABIVERSION = 8
100
101         # possible values for EI_CLASS
102         ELFCLASSNONE = 0
103         ELFCLASS32   = 1
104         ELFCLASS64   = 2
105
106         # possible value for EI_VERSION
107         EV_CURRENT   = 1
108
109         # possible values for EI_DATA
110         ELFDATANONE  = 0
111         ELFDATA2LSB  = 1
112         ELFDATA2MSB  = 2
113
114         def my_assert(self, expectation, result):
115             if not expectation == result:
116                 #print "'%x','%x' %s" % (ord(expectation), ord(result), self.name)
117                 raise Exception("This does not work as expected")
118
119         def __init__(self, name):
120             self.name = name
121
122         def open(self):
123             self.file = file(self.name, "r")
124             self.data = self.file.read(ELFFile.EI_NIDENT+4)
125
126             self.my_assert(len(self.data), ELFFile.EI_NIDENT+4)
127             self.my_assert(self.data[0], chr(0x7f) )
128             self.my_assert(self.data[1], 'E')
129             self.my_assert(self.data[2], 'L')
130             self.my_assert(self.data[3], 'F')
131             if bits32 :
132                 self.my_assert(self.data[ELFFile.EI_CLASS], chr(ELFFile.ELFCLASS32))
133             else:
134                 self.my_assert(self.data[ELFFile.EI_CLASS], chr(ELFFile.ELFCLASS64))
135             self.my_assert(self.data[ELFFile.EI_VERSION], chr(ELFFile.EV_CURRENT) )
136
137             self.sex = self.data[ELFFile.EI_DATA]
138             if self.sex == chr(ELFFile.ELFDATANONE):
139                 raise Exception("self.sex == ELFDATANONE")
140             elif self.sex == chr(ELFFile.ELFDATA2LSB):
141                 self.sex = "<"
142             elif self.sex == chr(ELFFile.ELFDATA2MSB):
143                 self.sex = ">"
144             else:
145                 raise Exception("Unknown self.sex")
146
147         def osAbi(self):
148             return ord(self.data[ELFFile.EI_OSABI])
149
150         def abiVersion(self):
151             return ord(self.data[ELFFile.EI_ABIVERSION])
152
153         def isLittleEndian(self):
154             return self.sex == "<"
155
156         def isBigEngian(self):
157             return self.sex == ">"
158
159         def machine(self):
160             """
161             We know the sex stored in self.sex and we
162             know the position
163             """
164             import struct
165             (a,) = struct.unpack(self.sex+"H", self.data[18:20])
166             return a
167
168     return ELFFile(path)
169
170
171 # Known Error classes
172 # 0 - non dev contains .so
173 # 1 - package contains a dangerous RPATH
174 # 2 - package depends on debug package
175 # 3 - non dbg contains .so
176 # 4 - wrong architecture
177 # 5 - .la contains installed=yes or reference to the workdir
178 # 6 - .pc contains reference to /usr/include or workdir
179 # 7 - the desktop file is not valid
180 # 8 - .la contains reference to the workdir
181 # 9 - LDFLAGS ignored
182
183 def package_qa_clean_path(path,d):
184     """ Remove the common prefix from the path. In this case it is the TMPDIR"""
185     return path.replace(bb.data.getVar('TMPDIR',d,True),"")
186
187 def package_qa_make_fatal_error(error_class, name, path,d):
188     """
189     decide if an error is fatal
190
191     TODO: Load a whitelist of known errors
192     """
193     return not error_class in [0, 5, 7]
194
195 def package_qa_write_error(error_class, name, path, d):
196     """
197     Log the error
198     """
199     if not bb.data.getVar('QA_LOG', d):
200         bb.note("a QA error occured but will not be logged because QA_LOG is not set")
201         return
202
203     ERROR_NAMES =[
204         "non dev contains .so",
205         "package contains RPATH",
206         "package depends on debug package",
207         "non dbg contains .debug",
208         "wrong architecture",
209         "evil hides inside the .la",
210         "evil hides inside the .pc",
211         "the desktop file is not valid",
212         ".la contains reference to the workdir",
213         "LDFLAGS ignored",
214     ]
215
216     log_path = os.path.join( bb.data.getVar('T', d, True), "log.qa_package" )
217     f = file( log_path, "a+")
218     print >> f, "%s, %s, %s" % \
219              (ERROR_NAMES[error_class], name, package_qa_clean_path(path,d))
220     f.close()
221
222 def package_qa_handle_error(error_class, error_msg, name, path, d):
223     bb.error("QA Issue with %s: %s" % (name, error_msg))
224     package_qa_write_error(error_class, name, path, d)
225     return not package_qa_make_fatal_error(error_class, name, path, d)
226
227 def package_qa_check_rpath(file,name,d, elf):
228     """
229     Check for dangerous RPATHs
230     """
231     if not elf:
232         return True
233
234     import bb, os
235     sane = True
236     scanelf = os.path.join(bb.data.getVar('STAGING_BINDIR_NATIVE',d,True),'scanelf')
237     bad_dir = bb.data.getVar('TMPDIR', d, True) + "/work"
238     bad_dir_test = bb.data.getVar('TMPDIR', d, True)
239     if not os.path.exists(scanelf):
240         bb.fatal("Can not check RPATH, scanelf (part of pax-utils-native) not found")
241
242     if not bad_dir in bb.data.getVar('WORKDIR', d, True):
243         bb.fatal("This class assumed that WORKDIR is ${TMPDIR}/work... Not doing any check")
244
245     output = os.popen("%s -B -F%%r#F '%s'" % (scanelf,file))
246     txt    = output.readline().split()
247     for line in txt:
248         if bad_dir in line:
249             error_msg = "package %s contains bad RPATH %s in file %s" % (name, line, file)
250             sane = package_qa_handle_error(1, error_msg, name, file, d)
251
252     return sane
253
254 def package_qa_check_dev(path, name,d, elf):
255     """
256     Check for ".so" library symlinks in non-dev packages
257     """
258
259     sane = True
260
261     # SDK packages are special.
262     for s in ['sdk', 'canadian-sdk']:
263         if bb.data.inherits_class(s, d):
264             return True
265
266     if not "-dev" in name:
267         if path[-3:] == ".so" and os.path.islink(path):
268             error_msg = "non -dev package contains symlink .so: %s path '%s'" % \
269                      (name, package_qa_clean_path(path,d))
270             sane = package_qa_handle_error(0, error_msg, name, path, d)
271
272     return sane
273
274 def package_qa_check_dbg(path, name,d, elf):
275     """
276     Check for ".debug" files or directories outside of the dbg package
277     """
278
279     sane = True
280
281     if not "-dbg" in name:
282         if '.debug' in path.split(os.path.sep):
283             error_msg = "non debug package contains .debug directory: %s path %s" % \
284                      (name, package_qa_clean_path(path,d))
285             sane = package_qa_handle_error(3, error_msg, name, path, d)
286
287     return sane
288
289 def package_qa_check_perm(path,name,d, elf):
290     """
291     Check the permission of files
292     """
293     sane = True
294     return sane
295
296 def package_qa_check_arch(path,name,d, elf):
297     """
298     Check if archs are compatible
299     """
300     if not elf:
301         return True
302
303     sane = True
304     target_os   = bb.data.getVar('TARGET_OS',   d, True)
305     target_arch = bb.data.getVar('TARGET_ARCH', d, True)
306
307     # FIXME: Cross package confuse this check, so just skip them
308     for s in ['cross', 'sdk', 'canadian-cross', 'canadian-sdk']:
309         if bb.data.inherits_class(s, d):
310             return True
311
312     # avoid following links to /usr/bin (e.g. on udev builds)
313     # we will check the files pointed to anyway...
314     if os.path.islink(path):
315         return True
316
317     #if this will throw an exception, then fix the dict above
318     (machine, osabi, abiversion, littleendian, bits32) \
319         = package_qa_get_machine_dict()[target_os][target_arch]
320
321     # Check the architecture and endiannes of the binary
322     if not machine == elf.machine():
323         error_msg = "Architecture did not match (%d to %d) on %s" % \
324                  (machine, elf.machine(), package_qa_clean_path(path,d))
325         sane = package_qa_handle_error(4, error_msg, name, path, d)
326     elif not littleendian == elf.isLittleEndian():
327         error_msg = "Endiannes did not match (%d to %d) on %s" % \
328                  (littleendian, elf.isLittleEndian(), package_qa_clean_path(path,d))
329         sane = package_qa_handle_error(4, error_msg, name, path, d)
330
331     return sane
332
333 def package_qa_check_desktop(path, name, d, elf):
334     """
335     Run all desktop files through desktop-file-validate.
336     """
337     sane = True
338     if path.endswith(".desktop"):
339         output = os.popen("desktop-file-validate %s" % path)
340         # This only produces output on errors
341         for l in output:
342             sane = package_qa_handle_error(7, l.strip(), name, path, d)
343
344     return sane
345
346 def package_qa_hash_style(path, name, d, elf):
347     """
348     Check if the binary has the right hash style...
349     """
350
351     if not elf:
352         return True
353
354     if os.path.islink(path):
355         return True
356
357     gnu_hash = "--hash-style=gnu" in bb.data.getVar('LDFLAGS', d, True)
358     if not gnu_hash:
359         gnu_hash = "--hash-style=both" in bb.data.getVar('LDFLAGS', d, True)
360     if not gnu_hash:
361         return True
362
363     objdump = bb.data.getVar('OBJDUMP', d, True)
364     env_path = bb.data.getVar('PATH', d, True)
365
366     sane = True
367     elf = False
368     # A bit hacky. We do not know if path is an elf binary or not
369     # we will search for 'NEEDED' or 'INIT' as this should be printed...
370     # and come before the HASH section (guess!!!) and works on split out
371     # debug symbols too
372     for line in os.popen("LC_ALL=C PATH=%s %s -p '%s' 2> /dev/null" % (env_path, objdump, path), "r"):
373         if "NEEDED" in line or "INIT" in line:
374             sane = False
375             elf = True
376         if "GNU_HASH" in line:
377             sane = True
378         if "[mips32]" in line or "[mips64]" in line:
379             sane = True
380
381     if elf and not sane:
382         error_msg = "No GNU_HASH in the elf binary: '%s'" % path
383         return package_qa_handle_error(9, error_msg, name, path, d)
384
385     return True
386
387 def package_qa_check_staged(path,d):
388     """
389     Check staged la and pc files for sanity
390       -e.g. installed being false
391
392         As this is run after every stage we should be able
393         to find the one responsible for the errors easily even
394         if we look at every .pc and .la file
395     """
396
397     sane = True
398     tmpdir = bb.data.getVar('TMPDIR', d, True)
399     workdir = os.path.join(tmpdir, "work")
400
401     installed = "installed=yes"
402     iscrossnative = False
403     pkgconfigcheck = tmpdir
404     for s in ['cross', 'native', 'canadian-cross', 'canadian-native']:
405         if bb.data.inherits_class(s, d):
406             pkgconfigcheck = workdir
407             iscrossnative = True
408
409     # find all .la and .pc files
410     # read the content
411     # and check for stuff that looks wrong
412     for root, dirs, files in os.walk(path):
413         for file in files:
414             path = os.path.join(root,file)
415             if file[-2:] == "la":
416                 file_content = open(path).read()
417                 # Don't check installed status for native/cross packages
418                 if not iscrossnative:
419                     if installed in file_content:
420                         error_msg = "%s failed sanity test (installed) in path %s" % (file,root)
421                         sane = package_qa_handle_error(5, error_msg, "staging", path, d)
422                 if workdir in file_content:
423                     error_msg = "%s failed sanity test (workdir) in path %s" % (file,root)
424                     sane = package_qa_handle_error(8, error_msg, "staging", path, d)
425             elif file[-2:] == "pc":
426                 file_content = open(path).read()
427                 if pkgconfigcheck in file_content:
428                     error_msg = "%s failed sanity test (tmpdir) in path %s" % (file,root)
429                     sane = package_qa_handle_error(6, error_msg, "staging", path, d)
430
431     return sane
432
433 # Walk over all files in a directory and call func
434 def package_qa_walk(path, funcs, package,d):
435     sane = True
436
437     #if this will throw an exception, then fix the dict above
438     target_os   = bb.data.getVar('TARGET_OS',   d, True)
439     target_arch = bb.data.getVar('TARGET_ARCH', d, True)
440     (machine, osabi, abiversion, littleendian, bits32) \
441         = package_qa_get_machine_dict()[target_os][target_arch]
442
443     for root, dirs, files in os.walk(path):
444         for file in files:
445             path = os.path.join(root,file)
446             elf = package_qa_get_elf(path, bits32)
447             try:
448                 elf.open()
449             except:
450                 elf = None
451             for func in funcs:
452                 if not func(path, package,d, elf):
453                     sane = False
454
455     return sane
456
457 def package_qa_check_rdepends(pkg, pkgdest, d):
458     sane = True
459     if not "-dbg" in pkg and not "task-" in pkg and not "-image" in pkg:
460         # Copied from package_ipk.bbclass
461         # boiler plate to update the data
462         localdata = bb.data.createCopy(d)
463         root = "%s/%s" % (pkgdest, pkg)
464
465         bb.data.setVar('ROOT', '', localdata) 
466         bb.data.setVar('ROOT_%s' % pkg, root, localdata)
467         pkgname = bb.data.getVar('PKG_%s' % pkg, localdata, True)
468         if not pkgname:
469             pkgname = pkg
470         bb.data.setVar('PKG', pkgname, localdata)
471
472         overrides = bb.data.getVar('OVERRIDES', localdata)
473         if not overrides:
474             raise bb.build.FuncFailed('OVERRIDES not defined')
475         overrides = bb.data.expand(overrides, localdata)
476         bb.data.setVar('OVERRIDES', overrides + ':' + pkg, localdata)
477
478         bb.data.update_data(localdata)
479
480         # Now check the RDEPENDS
481         rdepends = explode_deps(bb.data.getVar('RDEPENDS', localdata, True) or "")
482
483
484         # Now do the sanity check!!!
485         for rdepend in rdepends:
486             if "-dbg" in rdepend:
487                 error_msg = "%s rdepends on %s" % (pkgname,rdepend)
488                 sane = package_qa_handle_error(2, error_msg, pkgname, rdepend, d)
489
490     return sane
491
492 # The PACKAGE FUNC to scan each package
493 python do_package_qa () {
494     bb.debug(2, "DO PACKAGE QA")
495     pkgdest = bb.data.getVar('PKGDEST', d, True)
496     packages = bb.data.getVar('PACKAGES',d, True)
497
498     # no packages should be scanned
499     if not packages:
500         return
501
502     checks = [package_qa_check_rpath, package_qa_check_dev,
503               package_qa_check_perm, package_qa_check_arch,
504               package_qa_check_desktop, package_qa_hash_style,
505               package_qa_check_dbg]
506     walk_sane = True
507     rdepends_sane = True
508     for package in packages.split():
509         if bb.data.getVar('INSANE_SKIP_' + package, d, True):
510             bb.note("package %s skipped" % package)
511             continue
512
513         bb.debug(1, "Checking Package: %s" % package)
514         path = "%s/%s" % (pkgdest, package)
515         if not package_qa_walk(path, checks, package, d):
516             walk_sane  = False
517         if not package_qa_check_rdepends(package, pkgdest, d):
518             rdepends_sane = False
519
520     if not walk_sane or not rdepends_sane:
521         bb.fatal("QA run found fatal errors. Please consider fixing them.")
522     bb.debug(2, "DONE with PACKAGE QA")
523 }
524
525
526 # The Staging Func, to check all staging
527 addtask qa_staging after do_populate_staging before do_build
528 python do_qa_staging() {
529     bb.debug(2, "QA checking staging")
530
531     if not package_qa_check_staged(bb.data.getVar('STAGING_LIBDIR',d,True), d):
532         bb.fatal("QA staging was broken by the package built above")
533 }
534
535 # Check broken config.log files
536 addtask qa_configure after do_configure before do_compile
537 python do_qa_configure() {
538     bb.debug(1, "Checking sanity of the config.log file")
539     for root, dirs, files in os.walk(bb.data.getVar('WORKDIR', d, True)):
540         statement = "grep 'CROSS COMPILE Badness:' %s > /dev/null" % \
541                     os.path.join(root,"config.log")
542         if "config.log" in files:
543             if os.system(statement) == 0:
544                 bb.fatal("""This autoconf log indicates errors, it looked at host includes.
545 Rerun configure task after fixing this. The path was '%s'""" % root)
546 }