merge of '0b604857bbf871639fdb43ee8380222e8ef64bb7'
[vuplus_openembedded] / classes / base.bbclass
1 BB_DEFAULT_TASK ?= "build"
2
3 # like os.path.join but doesn't treat absolute RHS specially
4 def base_path_join(a, *p):
5     path = a
6     for b in p:
7         if path == '' or path.endswith('/'):
8             path +=  b
9         else:
10             path += '/' + b
11     return path
12
13 # for MD5/SHA handling
14 def base_chk_load_parser(config_path):
15     import ConfigParser, os, bb
16     parser = ConfigParser.ConfigParser()
17     if not len(parser.read(config_path)) == 1:
18         bb.note("Can not open the '%s' ini file" % config_path)
19         raise Exception("Can not open the '%s'" % config_path)
20
21     return parser
22
23 def base_chk_file(parser, pn, pv, src_uri, localpath, data):
24     import os, bb
25     no_checksum = False
26     # Try PN-PV-SRC_URI first and then try PN-SRC_URI
27     # we rely on the get method to create errors
28     pn_pv_src = "%s-%s-%s" % (pn,pv,src_uri)
29     pn_src    = "%s-%s" % (pn,src_uri)
30     if parser.has_section(pn_pv_src):
31         md5    = parser.get(pn_pv_src, "md5")
32         sha256 = parser.get(pn_pv_src, "sha256")
33     elif parser.has_section(pn_src):
34         md5    = parser.get(pn_src, "md5")
35         sha256 = parser.get(pn_src, "sha256")
36     elif parser.has_section(src_uri):
37         md5    = parser.get(src_uri, "md5")
38         sha256 = parser.get(src_uri, "sha256")
39     else:
40         no_checksum = True
41
42     # md5 and sha256 should be valid now
43     if not os.path.exists(localpath):
44         bb.note("The localpath does not exist '%s'" % localpath)
45         raise Exception("The path does not exist '%s'" % localpath)
46
47
48     # call md5(sum) and shasum
49     try:
50         md5pipe = os.popen('md5sum ' + localpath)
51         md5data = (md5pipe.readline().split() or [ "" ])[0]
52         md5pipe.close()
53     except OSError:
54         raise Exception("Executing md5sum failed")
55
56     try:
57         shapipe = os.popen('PATH=%s oe_sha256sum %s' % (bb.data.getVar('PATH', data, True), localpath))
58         shadata = (shapipe.readline().split() or [ "" ])[0]
59         shapipe.close()
60     except OSError:
61         raise Exception("Executing shasum failed")
62
63     if no_checksum == True:     # we do not have conf/checksums.ini entry
64         try:
65             file = open("%s/checksums.ini" % bb.data.getVar("TMPDIR", data, 1), "a")
66         except:
67             return False
68
69         if not file:
70             raise Exception("Creating checksums.ini failed")
71         
72         file.write("[%s]\nmd5=%s\nsha256=%s\n\n" % (src_uri, md5data, shadata))
73         file.close()
74         return False
75
76     if not md5 == md5data:
77         bb.note("The MD5Sums did not match. Wanted: '%s' and Got: '%s'" % (md5,md5data))
78         raise Exception("MD5 Sums do not match. Wanted: '%s' Got: '%s'" % (md5, md5data))
79
80     if not sha256 == shadata:
81         bb.note("The SHA256 Sums do not match. Wanted: '%s' Got: '%s'" % (sha256,shadata))
82         raise Exception("SHA256 Sums do not match. Wanted: '%s' Got: '%s'" % (sha256, shadata))
83
84     return True
85
86
87 def base_dep_prepend(d):
88         import bb
89         #
90         # Ideally this will check a flag so we will operate properly in
91         # the case where host == build == target, for now we don't work in
92         # that case though.
93         #
94         deps = "shasum-native "
95         if bb.data.getVar('PN', d, True) == "shasum-native":
96                 deps = ""
97
98         # INHIBIT_DEFAULT_DEPS doesn't apply to the patch command.  Whether or  not
99         # we need that built is the responsibility of the patch function / class, not
100         # the application.
101         if not bb.data.getVar('INHIBIT_DEFAULT_DEPS', d):
102                 if (bb.data.getVar('HOST_SYS', d, 1) !=
103                     bb.data.getVar('BUILD_SYS', d, 1)):
104                         deps += " virtual/${TARGET_PREFIX}gcc virtual/libc "
105         return deps
106
107 def base_read_file(filename):
108         import bb
109         try:
110                 f = file( filename, "r" )
111         except IOError, reason:
112                 return "" # WARNING: can't raise an error now because of the new RDEPENDS handling. This is a bit ugly. :M:
113         else:
114                 return f.read().strip()
115         return None
116
117 def base_conditional(variable, checkvalue, truevalue, falsevalue, d):
118         import bb
119         if bb.data.getVar(variable,d,1) == checkvalue:
120                 return truevalue
121         else:
122                 return falsevalue
123
124 def base_less_or_equal(variable, checkvalue, truevalue, falsevalue, d):
125         import bb
126         if float(bb.data.getVar(variable,d,1)) <= float(checkvalue):
127                 return truevalue
128         else:
129                 return falsevalue
130
131 def base_version_less_or_equal(variable, checkvalue, truevalue, falsevalue, d):
132     import bb
133     result = bb.vercmp(bb.data.getVar(variable,d,True), checkvalue)
134     if result <= 0:
135         return truevalue
136     else:
137         return falsevalue
138
139 def base_contains(variable, checkvalues, truevalue, falsevalue, d):
140         import bb
141         matches = 0
142         if type(checkvalues).__name__ == "str":
143                 checkvalues = [checkvalues]
144         for value in checkvalues:
145                 if bb.data.getVar(variable,d,1).find(value) != -1:      
146                         matches = matches + 1
147         if matches == len(checkvalues):
148                 return truevalue                
149         return falsevalue
150
151 def base_both_contain(variable1, variable2, checkvalue, d):
152        import bb
153        if bb.data.getVar(variable1,d,1).find(checkvalue) != -1 and bb.data.getVar(variable2,d,1).find(checkvalue) != -1:
154                return checkvalue
155        else:
156                return ""
157
158 DEPENDS_prepend="${@base_dep_prepend(d)} "
159
160 def base_set_filespath(path, d):
161         import os, bb
162         filespath = []
163         for p in path:
164                 overrides = bb.data.getVar("OVERRIDES", d, 1) or ""
165                 overrides = overrides + ":"
166                 for o in overrides.split(":"):
167                         filespath.append(os.path.join(p, o))
168         return ":".join(filespath)
169
170 FILESPATH = "${@base_set_filespath([ "${FILE_DIRNAME}/${PF}", "${FILE_DIRNAME}/${P}", "${FILE_DIRNAME}/${PN}", "${FILE_DIRNAME}/files", "${FILE_DIRNAME}" ], d)}"
171
172 def oe_filter(f, str, d):
173         from re import match
174         return " ".join(filter(lambda x: match(f, x, 0), str.split()))
175
176 def oe_filter_out(f, str, d):
177         from re import match
178         return " ".join(filter(lambda x: not match(f, x, 0), str.split()))
179
180 die() {
181         oefatal "$*"
182 }
183
184 oenote() {
185         echo "NOTE:" "$*"
186 }
187
188 oewarn() {
189         echo "WARNING:" "$*"
190 }
191
192 oefatal() {
193         echo "FATAL:" "$*"
194         exit 1
195 }
196
197 oedebug() {
198         test $# -ge 2 || {
199                 echo "Usage: oedebug level \"message\""
200                 exit 1
201         }
202
203         test ${OEDEBUG:-0} -ge $1 && {
204                 shift
205                 echo "DEBUG:" $*
206         }
207 }
208
209 oe_runmake() {
210         if [ x"$MAKE" = x ]; then MAKE=make; fi
211         oenote ${MAKE} ${EXTRA_OEMAKE} "$@"
212         ${MAKE} ${EXTRA_OEMAKE} "$@" || die "oe_runmake failed"
213 }
214
215 oe_soinstall() {
216         # Purpose: Install shared library file and
217         #          create the necessary links
218         # Example:
219         #
220         # oe_
221         #
222         #oenote installing shared library $1 to $2
223         #
224         libname=`basename $1`
225         install -m 755 $1 $2/$libname
226         sonamelink=`${HOST_PREFIX}readelf -d $1 |grep 'Library soname:' |sed -e 's/.*\[\(.*\)\].*/\1/'`
227         solink=`echo $libname | sed -e 's/\.so\..*/.so/'`
228         ln -sf $libname $2/$sonamelink
229         ln -sf $libname $2/$solink
230 }
231
232 oe_libinstall() {
233         # Purpose: Install a library, in all its forms
234         # Example
235         #
236         # oe_libinstall libltdl ${STAGING_LIBDIR}/
237         # oe_libinstall -C src/libblah libblah ${D}/${libdir}/
238         dir=""
239         libtool=""
240         silent=""
241         require_static=""
242         require_shared=""
243         staging_install=""
244         while [ "$#" -gt 0 ]; do
245                 case "$1" in
246                 -C)
247                         shift
248                         dir="$1"
249                         ;;
250                 -s)
251                         silent=1
252                         ;;
253                 -a)
254                         require_static=1
255                         ;;
256                 -so)
257                         require_shared=1
258                         ;;
259                 -*)
260                         oefatal "oe_libinstall: unknown option: $1"
261                         ;;
262                 *)
263                         break;
264                         ;;
265                 esac
266                 shift
267         done
268
269         libname="$1"
270         shift
271         destpath="$1"
272         if [ -z "$destpath" ]; then
273                 oefatal "oe_libinstall: no destination path specified"
274         fi
275         if echo "$destpath/" | egrep '^${STAGING_LIBDIR}/' >/dev/null
276         then
277                 staging_install=1
278         fi
279
280         __runcmd () {
281                 if [ -z "$silent" ]; then
282                         echo >&2 "oe_libinstall: $*"
283                 fi
284                 $*
285         }
286
287         if [ -z "$dir" ]; then
288                 dir=`pwd`
289         fi
290         dotlai=$libname.lai
291         dir=$dir`(cd $dir;find . -name "$dotlai") | sed "s/^\.//;s/\/$dotlai\$//;q"`
292         olddir=`pwd`
293         __runcmd cd $dir
294
295         lafile=$libname.la
296
297         # If such file doesn't exist, try to cut version suffix
298         if [ ! -f "$lafile" ]; then
299                 libname1=`echo "$libname" | sed 's/-[0-9.]*$//'`
300                 lafile1=$libname.la
301                 if [ -f "$lafile1" ]; then
302                         libname=$libname1
303                         lafile=$lafile1
304                 fi
305         fi
306
307         if [ -f "$lafile" ]; then
308                 # libtool archive
309                 eval `cat $lafile|grep "^library_names="`
310                 libtool=1
311         else
312                 library_names="$libname.so* $libname.dll.a"
313         fi
314
315         __runcmd install -d $destpath/
316         dota=$libname.a
317         if [ -f "$dota" -o -n "$require_static" ]; then
318                 __runcmd install -m 0644 $dota $destpath/
319         fi
320         if [ -f "$dotlai" -a -n "$libtool" ]; then
321                 if test -n "$staging_install"
322                 then
323                         # stop libtool using the final directory name for libraries
324                         # in staging:
325                         __runcmd rm -f $destpath/$libname.la
326                         __runcmd sed -e 's/^installed=yes$/installed=no/' \
327                                      -e '/^dependency_libs=/s,${WORKDIR}[[:alnum:]/\._+-]*/\([[:alnum:]\._+-]*\),${STAGING_LIBDIR}/\1,g' \
328                                      -e "/^dependency_libs=/s,\([[:space:]']+\)${libdir},\1${STAGING_LIBDIR},g" \
329                                      $dotlai >$destpath/$libname.la
330                 else
331                         __runcmd install -m 0644 $dotlai $destpath/$libname.la
332                 fi
333         fi
334
335         for name in $library_names; do
336                 files=`eval echo $name`
337                 for f in $files; do
338                         if [ ! -e "$f" ]; then
339                                 if [ -n "$libtool" ]; then
340                                         oefatal "oe_libinstall: $dir/$f not found."
341                                 fi
342                         elif [ -L "$f" ]; then
343                                 __runcmd cp -P "$f" $destpath/
344                         elif [ ! -L "$f" ]; then
345                                 libfile="$f"
346                                 __runcmd install -m 0755 $libfile $destpath/
347                         fi
348                 done
349         done
350
351         if [ -z "$libfile" ]; then
352                 if  [ -n "$require_shared" ]; then
353                         oefatal "oe_libinstall: unable to locate shared library"
354                 fi
355         elif [ -z "$libtool" ]; then
356                 # special case hack for non-libtool .so.#.#.# links
357                 baselibfile=`basename "$libfile"`
358                 if (echo $baselibfile | grep -qE '^lib.*\.so\.[0-9.]*$'); then
359                         sonamelink=`${HOST_PREFIX}readelf -d $libfile |grep 'Library soname:' |sed -e 's/.*\[\(.*\)\].*/\1/'`
360                         solink=`echo $baselibfile | sed -e 's/\.so\..*/.so/'`
361                         if [ -n "$sonamelink" -a x"$baselibfile" != x"$sonamelink" ]; then
362                                 __runcmd ln -sf $baselibfile $destpath/$sonamelink
363                         fi
364                         __runcmd ln -sf $baselibfile $destpath/$solink
365                 fi
366         fi
367
368         __runcmd cd "$olddir"
369 }
370
371 def package_stagefile(file, d):
372     import bb, os
373
374     if bb.data.getVar('PSTAGING_ACTIVE', d, True) == "1":
375         destfile = file.replace(bb.data.getVar("TMPDIR", d, 1), bb.data.getVar("PSTAGE_TMPDIR_STAGE", d, 1))
376         bb.mkdirhier(os.path.dirname(destfile))
377         #print "%s to %s" % (file, destfile)
378         bb.copyfile(file, destfile)
379
380 package_stagefile_shell() {
381         if [ "$PSTAGING_ACTIVE" = "1" ]; then
382                 srcfile=$1
383                 destfile=`echo $srcfile | sed s#${TMPDIR}#${PSTAGE_TMPDIR_STAGE}#`
384                 destdir=`dirname $destfile`
385                 mkdir -p $destdir
386                 cp -dp $srcfile $destfile
387         fi
388 }
389
390 oe_machinstall() {
391         # Purpose: Install machine dependent files, if available
392         #          If not available, check if there is a default
393         #          If no default, just touch the destination
394         # Example:
395         #                $1  $2   $3         $4
396         # oe_machinstall -m 0644 fstab ${D}/etc/fstab
397         #
398         # TODO: Check argument number?
399         #
400         filename=`basename $3`
401         dirname=`dirname $3`
402
403         for o in `echo ${OVERRIDES} | tr ':' ' '`; do
404                 if [ -e $dirname/$o/$filename ]; then
405                         oenote $dirname/$o/$filename present, installing to $4
406                         install $1 $2 $dirname/$o/$filename $4
407                         return
408                 fi
409         done
410 #       oenote overrides specific file NOT present, trying default=$3...
411         if [ -e $3 ]; then
412                 oenote $3 present, installing to $4
413                 install $1 $2 $3 $4
414         else
415                 oenote $3 NOT present, touching empty $4
416                 touch $4
417         fi
418 }
419
420 addtask listtasks
421 do_listtasks[nostamp] = "1"
422 python do_listtasks() {
423         import sys
424         # emit variables and shell functions
425         #bb.data.emit_env(sys.__stdout__, d)
426         # emit the metadata which isnt valid shell
427         for e in d.keys():
428                 if bb.data.getVarFlag(e, 'task', d):
429                         sys.__stdout__.write("%s\n" % e)
430 }
431
432 addtask clean
433 do_clean[dirs] = "${TOPDIR}"
434 do_clean[nostamp] = "1"
435 python base_do_clean() {
436         """clear the build and temp directories"""
437         dir = bb.data.expand("${WORKDIR}", d)
438         if dir == '//': raise bb.build.FuncFailed("wrong DATADIR")
439         bb.note("removing " + dir)
440         os.system('rm -rf ' + dir)
441
442         dir = "%s.*" % bb.data.expand(bb.data.getVar('STAMP', d), d)
443         bb.note("removing " + dir)
444         os.system('rm -f '+ dir)
445 }
446
447 #Uncomment this for bitbake 1.8.12
448 #addtask rebuild after do_${BB_DEFAULT_TASK}
449 addtask rebuild
450 do_rebuild[dirs] = "${TOPDIR}"
451 do_rebuild[nostamp] = "1"
452 python base_do_rebuild() {
453         """rebuild a package"""
454         from bb import __version__
455         try:
456                 from distutils.version import LooseVersion
457         except ImportError:
458                 def LooseVersion(v): print "WARNING: sanity.bbclass can't compare versions without python-distutils"; return 1
459         if (LooseVersion(__version__) < LooseVersion('1.8.11')):
460                 bb.build.exec_func('do_clean', d)
461                 bb.build.exec_task('do_' + bb.data.getVar('BB_DEFAULT_TASK', d, 1), d)
462 }
463
464 addtask mrproper
465 do_mrproper[dirs] = "${TOPDIR}"
466 do_mrproper[nostamp] = "1"
467 python base_do_mrproper() {
468         """clear downloaded sources, build and temp directories"""
469         dir = bb.data.expand("${DL_DIR}", d)
470         if dir == '/': bb.build.FuncFailed("wrong DATADIR")
471         bb.debug(2, "removing " + dir)
472         os.system('rm -rf ' + dir)
473         bb.build.exec_func('do_clean', d)
474 }
475
476 addtask fetch
477 do_fetch[dirs] = "${DL_DIR}"
478 do_fetch[depends] = "shasum-native:do_populate_staging"
479 python base_do_fetch() {
480         import sys
481
482         localdata = bb.data.createCopy(d)
483         bb.data.update_data(localdata)
484
485         src_uri = bb.data.getVar('SRC_URI', localdata, 1)
486         if not src_uri:
487                 return 1
488
489         try:
490                 bb.fetch.init(src_uri.split(),d)
491         except bb.fetch.NoMethodError:
492                 (type, value, traceback) = sys.exc_info()
493                 raise bb.build.FuncFailed("No method: %s" % value)
494
495         try:
496                 bb.fetch.go(localdata)
497         except bb.fetch.MissingParameterError:
498                 (type, value, traceback) = sys.exc_info()
499                 raise bb.build.FuncFailed("Missing parameters: %s" % value)
500         except bb.fetch.FetchError:
501                 (type, value, traceback) = sys.exc_info()
502                 raise bb.build.FuncFailed("Fetch failed: %s" % value)
503         except bb.fetch.MD5SumError:
504                 (type, value, traceback) = sys.exc_info()
505                 raise bb.build.FuncFailed("MD5  failed: %s" % value)
506         except:
507                 (type, value, traceback) = sys.exc_info()
508                 raise bb.build.FuncFailed("Unknown fetch Error: %s" % value)
509
510
511         # Verify the SHA and MD5 sums we have in OE and check what do
512         # in
513         check_sum = bb.which(bb.data.getVar('BBPATH', d, True), "conf/checksums.ini")
514         if not check_sum:
515                 bb.note("No conf/checksums.ini found, not checking checksums")
516                 return
517
518         try:
519                 parser = base_chk_load_parser(check_sum)
520         except:
521                 bb.note("Creating the CheckSum parser failed")
522                 return
523
524         pv = bb.data.getVar('PV', d, True)
525         pn = bb.data.getVar('PN', d, True)
526
527         # Check each URI
528         for url in src_uri.split():
529                 localpath = bb.data.expand(bb.fetch.localpath(url, localdata), localdata)
530                 (type,host,path,_,_,_) = bb.decodeurl(url)
531                 uri = "%s://%s%s" % (type,host,path)
532                 try:
533                         if type == "http" or type == "https" or type == "ftp" or type == "ftps":
534                                 if not base_chk_file(parser, pn, pv,uri, localpath, d):
535                                         bb.note("%s-%s: %s has no entry in conf/checksums.ini, not checking URI" % (pn,pv,uri))
536                 except Exception:
537                         raise bb.build.FuncFailed("Checksum of '%s' failed" % uri)
538 }
539
540 addtask fetchall after do_fetch
541 do_fetchall[recrdeptask] = "do_fetch"
542 base_do_fetchall() {
543         :
544 }
545
546 addtask buildall after do_build
547 do_buildall[recrdeptask] = "do_build"
548 base_do_buildall() {
549         :
550 }
551
552
553 def oe_unpack_file(file, data, url = None):
554         import bb, os
555         if not url:
556                 url = "file://%s" % file
557         dots = file.split(".")
558         if dots[-1] in ['gz', 'bz2', 'Z']:
559                 efile = os.path.join(bb.data.getVar('WORKDIR', data, 1),os.path.basename('.'.join(dots[0:-1])))
560         else:
561                 efile = file
562         cmd = None
563         if file.endswith('.tar'):
564                 cmd = 'tar x --no-same-owner -f %s' % file
565         elif file.endswith('.tgz') or file.endswith('.tar.gz') or file.endswith('.tar.Z'):
566                 cmd = 'tar xz --no-same-owner -f %s' % file
567         elif file.endswith('.tbz') or file.endswith('.tbz2') or file.endswith('.tar.bz2'):
568                 cmd = 'bzip2 -dc %s | tar x --no-same-owner -f -' % file
569         elif file.endswith('.gz') or file.endswith('.Z') or file.endswith('.z'):
570                 cmd = 'gzip -dc %s > %s' % (file, efile)
571         elif file.endswith('.bz2'):
572                 cmd = 'bzip2 -dc %s > %s' % (file, efile)
573         elif file.endswith('.zip'):
574                 cmd = 'unzip -q'
575                 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
576                 if 'dos' in parm:
577                         cmd = '%s -a' % cmd
578                 cmd = '%s %s' % (cmd, file)
579         elif os.path.isdir(file):
580                 filesdir = os.path.realpath(bb.data.getVar("FILESDIR", data, 1))
581                 destdir = "."
582                 if file[0:len(filesdir)] == filesdir:
583                         destdir = file[len(filesdir):file.rfind('/')]
584                         destdir = destdir.strip('/')
585                         if len(destdir) < 1:
586                                 destdir = "."
587                         elif not os.access("%s/%s" % (os.getcwd(), destdir), os.F_OK):
588                                 os.makedirs("%s/%s" % (os.getcwd(), destdir))
589                 cmd = 'cp -pPR %s %s/%s/' % (file, os.getcwd(), destdir)
590         else:
591                 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
592                 if not 'patch' in parm:
593                         # The "destdir" handling was specifically done for FILESPATH
594                         # items.  So, only do so for file:// entries.
595                         if type == "file":
596                                 destdir = bb.decodeurl(url)[1] or "."
597                         else:
598                                 destdir = "."
599                         bb.mkdirhier("%s/%s" % (os.getcwd(), destdir))
600                         cmd = 'cp %s %s/%s/' % (file, os.getcwd(), destdir)
601
602         if not cmd:
603                 return True
604
605         dest = os.path.join(os.getcwd(), os.path.basename(file))
606         if os.path.exists(dest):
607                 if os.path.samefile(file, dest):
608                         return True
609
610         cmd = "PATH=\"%s\" %s" % (bb.data.getVar('PATH', data, 1), cmd)
611         bb.note("Unpacking %s to %s/" % (file, os.getcwd()))
612         ret = os.system(cmd)
613         return ret == 0
614
615 addtask unpack after do_fetch
616 do_unpack[dirs] = "${WORKDIR}"
617 python base_do_unpack() {
618         import re, os
619
620         localdata = bb.data.createCopy(d)
621         bb.data.update_data(localdata)
622
623         src_uri = bb.data.getVar('SRC_URI', localdata)
624         if not src_uri:
625                 return
626         src_uri = bb.data.expand(src_uri, localdata)
627         for url in src_uri.split():
628                 try:
629                         local = bb.data.expand(bb.fetch.localpath(url, localdata), localdata)
630                 except bb.MalformedUrl, e:
631                         raise FuncFailed('Unable to generate local path for malformed uri: %s' % e)
632                 local = os.path.realpath(local)
633                 ret = oe_unpack_file(local, localdata, url)
634                 if not ret:
635                         raise bb.build.FuncFailed()
636 }
637
638
639 addhandler base_eventhandler
640 python base_eventhandler() {
641         from bb import note, error, data
642         from bb.event import Handled, NotHandled, getName
643         import os
644
645         messages = {}
646         messages["Completed"] = "completed"
647         messages["Succeeded"] = "completed"
648         messages["Started"] = "started"
649         messages["Failed"] = "failed"
650
651         name = getName(e)
652         msg = ""
653         if name.startswith("Pkg"):
654                 msg += "package %s: " % data.getVar("P", e.data, 1)
655                 msg += messages.get(name[3:]) or name[3:]
656         elif name.startswith("Task"):
657                 msg += "package %s: task %s: " % (data.getVar("PF", e.data, 1), e.task)
658                 msg += messages.get(name[4:]) or name[4:]
659         elif name.startswith("Build"):
660                 msg += "build %s: " % e.name
661                 msg += messages.get(name[5:]) or name[5:]
662         elif name == "UnsatisfiedDep":
663                 msg += "package %s: dependency %s %s" % (e.pkg, e.dep, name[:-3].lower())
664         if msg:
665                 note(msg)
666
667         if name.startswith("BuildStarted"):
668                 bb.data.setVar( 'BB_VERSION', bb.__version__, e.data )
669                 path_to_bbfiles = bb.data.getVar( 'BBFILES', e.data, 1 )
670                 path_to_packages = path_to_bbfiles[:path_to_bbfiles.rindex( "packages" )]
671                 monotone_revision = "<unknown>"
672                 try:
673                         monotone_revision = file( "%s/_MTN/revision" % path_to_packages ).read().strip()
674                         if monotone_revision.startswith( "format_version" ):
675                                 monotone_revision_words = monotone_revision.split()
676                                 monotone_revision = monotone_revision_words[ monotone_revision_words.index( "old_revision" )+1][1:-1]
677                 except IOError:
678                         pass
679                 bb.data.setVar( 'OE_REVISION', monotone_revision, e.data )
680                 statusvars = ['BB_VERSION', 'OE_REVISION', 'TARGET_ARCH', 'TARGET_OS', 'MACHINE', 'DISTRO', 'DISTRO_VERSION','TARGET_FPU']
681                 statuslines = ["%-14s = \"%s\"" % (i, bb.data.getVar(i, e.data, 1) or '') for i in statusvars]
682                 statusmsg = "\nOE Build Configuration:\n%s\n" % '\n'.join(statuslines)
683                 print statusmsg
684
685                 needed_vars = [ "TARGET_ARCH", "TARGET_OS" ]
686                 pesteruser = []
687                 for v in needed_vars:
688                         val = bb.data.getVar(v, e.data, 1)
689                         if not val or val == 'INVALID':
690                                 pesteruser.append(v)
691                 if pesteruser:
692                         bb.fatal('The following variable(s) were not set: %s\nPlease set them directly, or choose a MACHINE or DISTRO that sets them.' % ', '.join(pesteruser))
693
694         #
695         # Handle removing stamps for 'rebuild' task
696         #
697         if name.startswith("StampUpdate"):
698                 for (fn, task) in e.targets:
699                         #print "%s %s" % (task, fn)         
700                         if task == "do_rebuild":
701                                 dir = "%s.*" % e.stampPrefix[fn]
702                                 bb.note("Removing stamps: " + dir)
703                                 os.system('rm -f '+ dir)
704
705         if not data in e.__dict__:
706                 return NotHandled
707
708         log = data.getVar("EVENTLOG", e.data, 1)
709         if log:
710                 logfile = file(log, "a")
711                 logfile.write("%s\n" % msg)
712                 logfile.close()
713
714         return NotHandled
715 }
716
717 addtask configure after do_unpack do_patch
718 do_configure[dirs] = "${S} ${B}"
719 do_configure[deptask] = "do_populate_staging"
720 base_do_configure() {
721         :
722 }
723
724 addtask compile after do_configure
725 do_compile[dirs] = "${S} ${B}"
726 base_do_compile() {
727         if [ -e Makefile -o -e makefile ]; then
728                 oe_runmake || die "make failed"
729         else
730                 oenote "nothing to compile"
731         fi
732 }
733
734 base_do_stage () {
735         :
736 }
737
738 do_populate_staging[dirs] = "${STAGING_DIR_TARGET}/${layout_bindir} ${STAGING_DIR_TARGET}/${layout_libdir} \
739                              ${STAGING_DIR_TARGET}/${layout_includedir} \
740                              ${STAGING_BINDIR_NATIVE} ${STAGING_LIBDIR_NATIVE} \
741                              ${STAGING_INCDIR_NATIVE} \
742                              ${STAGING_DATADIR} \
743                              ${S} ${B}"
744
745 # Could be compile but populate_staging and do_install shouldn't run at the same time
746 addtask populate_staging after do_install
747
748 python do_populate_staging () {
749     bb.build.exec_func('do_stage', d)
750 }
751
752 addtask install after do_compile
753 do_install[dirs] = "${D} ${S} ${B}"
754 # Remove and re-create ${D} so that is it guaranteed to be empty
755 do_install[cleandirs] = "${D}"
756
757 base_do_install() {
758         :
759 }
760
761 base_do_package() {
762         :
763 }
764
765 addtask build after do_populate_staging
766 do_build = ""
767 do_build[func] = "1"
768
769 # Functions that update metadata based on files outputted
770 # during the build process.
771
772 def explode_deps(s):
773         r = []
774         l = s.split()
775         flag = False
776         for i in l:
777                 if i[0] == '(':
778                         flag = True
779                         j = []
780                 if flag:
781                         j.append(i)
782                         if i.endswith(')'):
783                                 flag = False
784                                 r[-1] += ' ' + ' '.join(j)
785                 else:
786                         r.append(i)
787         return r
788
789 def packaged(pkg, d):
790         import os, bb
791         return os.access(get_subpkgedata_fn(pkg, d) + '.packaged', os.R_OK)
792
793 def read_pkgdatafile(fn):
794         pkgdata = {}
795
796         def decode(str):
797                 import codecs
798                 c = codecs.getdecoder("string_escape")
799                 return c(str)[0]
800
801         import os
802         if os.access(fn, os.R_OK):
803                 import re
804                 f = file(fn, 'r')
805                 lines = f.readlines()
806                 f.close()
807                 r = re.compile("([^:]+):\s*(.*)")
808                 for l in lines:
809                         m = r.match(l)
810                         if m:
811                                 pkgdata[m.group(1)] = decode(m.group(2))
812
813         return pkgdata
814
815 def get_subpkgedata_fn(pkg, d):
816         import bb, os
817         archs = bb.data.expand("${PACKAGE_ARCHS}", d).split(" ")
818         archs.reverse()
819         pkgdata = bb.data.expand('${STAGING_DIR}/pkgdata/', d)
820         targetdir = bb.data.expand('${TARGET_VENDOR}-${TARGET_OS}/runtime/', d)
821         for arch in archs:
822                 fn = pkgdata + arch + targetdir + pkg
823                 if os.path.exists(fn):
824                         return fn
825         return bb.data.expand('${PKGDATA_DIR}/runtime/%s' % pkg, d)
826
827 def has_subpkgdata(pkg, d):
828         import bb, os
829         return os.access(get_subpkgedata_fn(pkg, d), os.R_OK)
830
831 def read_subpkgdata(pkg, d):
832         import bb, os
833         return read_pkgdatafile(get_subpkgedata_fn(pkg, d))
834
835 def has_pkgdata(pn, d):
836         import bb, os
837         fn = bb.data.expand('${PKGDATA_DIR}/%s' % pn, d)
838         return os.access(fn, os.R_OK)
839
840 def read_pkgdata(pn, d):
841         import bb, os
842         fn = bb.data.expand('${PKGDATA_DIR}/%s' % pn, d)
843         return read_pkgdatafile(fn)
844
845 python read_subpackage_metadata () {
846         import bb
847         data = read_pkgdata(bb.data.getVar('PN', d, 1), d)
848
849         for key in data.keys():
850                 bb.data.setVar(key, data[key], d)
851
852         for pkg in bb.data.getVar('PACKAGES', d, 1).split():
853                 sdata = read_subpkgdata(pkg, d)
854                 for key in sdata.keys():
855                         bb.data.setVar(key, sdata[key], d)
856 }
857
858 # Make sure MACHINE isn't exported
859 # (breaks binutils at least)
860 MACHINE[unexport] = "1"
861
862 # Make sure TARGET_ARCH isn't exported
863 # (breaks Makefiles using implicit rules, e.g. quilt, as GNU make has this 
864 # in them, undocumented)
865 TARGET_ARCH[unexport] = "1"
866
867 # Make sure DISTRO isn't exported
868 # (breaks sysvinit at least)
869 DISTRO[unexport] = "1"
870
871
872 def base_after_parse(d):
873     import bb, os, exceptions
874
875     source_mirror_fetch = bb.data.getVar('SOURCE_MIRROR_FETCH', d, 0)
876     if not source_mirror_fetch:
877         need_host = bb.data.getVar('COMPATIBLE_HOST', d, 1)
878         if need_host:
879             import re
880             this_host = bb.data.getVar('HOST_SYS', d, 1)
881             if not re.match(need_host, this_host):
882                 raise bb.parse.SkipPackage("incompatible with host %s" % this_host)
883
884         need_machine = bb.data.getVar('COMPATIBLE_MACHINE', d, 1)
885         if need_machine:
886             import re
887             this_machine = bb.data.getVar('MACHINE', d, 1)
888             if this_machine and not re.match(need_machine, this_machine):
889                 raise bb.parse.SkipPackage("incompatible with machine %s" % this_machine)
890
891     pn = bb.data.getVar('PN', d, 1)
892
893     # OBSOLETE in bitbake 1.7.4
894     srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
895     if srcdate != None:
896         bb.data.setVar('SRCDATE', srcdate, d)
897
898     use_nls = bb.data.getVar('USE_NLS_%s' % pn, d, 1)
899     if use_nls != None:
900         bb.data.setVar('USE_NLS', use_nls, d)
901
902     # Git packages should DEPEND on git-native
903     srcuri = bb.data.getVar('SRC_URI', d, 1)
904     if "git://" in srcuri:
905         depends = bb.data.getVarFlag('do_fetch', 'depends', d) or ""
906         depends = depends + " git-native:do_populate_staging"
907         bb.data.setVarFlag('do_fetch', 'depends', depends, d)
908
909     mach_arch = bb.data.getVar('MACHINE_ARCH', d, 1)
910     old_arch = bb.data.getVar('PACKAGE_ARCH', d, 1)
911     if (old_arch == mach_arch):
912         # Nothing to do
913         return
914
915     #
916     # We always try to scan SRC_URI for urls with machine overrides
917     # unless the package sets SRC_URI_OVERRIDES_PACKAGE_ARCH=0
918     #
919     override = bb.data.getVar('SRC_URI_OVERRIDES_PACKAGE_ARCH', d, 1)
920     if override == '0':
921         return
922
923     paths = []
924     for p in [ "${PF}", "${P}", "${PN}", "files", "" ]:
925         path = bb.data.expand(os.path.join("${FILE_DIRNAME}", p, "${MACHINE}"), d)
926         if os.path.isdir(path):
927             paths.append(path)
928     if len(paths) == 0:
929         return
930
931     for s in srcuri.split():
932         if not s.startswith("file://"):
933             continue
934         local = bb.data.expand(bb.fetch.localpath(s, d), d)
935         for mp in paths:
936             if local.startswith(mp):
937                 #bb.note("overriding PACKAGE_ARCH from %s to %s" % (old_arch, mach_arch))
938                 bb.data.setVar('PACKAGE_ARCH', "${MACHINE_ARCH}", d)
939                 return
940
941 python () {
942     import bb
943     from bb import __version__
944     base_after_parse(d)
945
946     # Remove this for bitbake 1.8.12
947     try:
948         from distutils.version import LooseVersion
949     except ImportError:
950         def LooseVersion(v): print "WARNING: sanity.bbclass can't compare versions without python-distutils"; return 1
951     if (LooseVersion(__version__) >= LooseVersion('1.8.11')):
952         deps = bb.data.getVarFlag('do_rebuild', 'deps', d) or []
953         deps.append('do_' + bb.data.getVar('BB_DEFAULT_TASK', d, 1))
954         bb.data.setVarFlag('do_rebuild', 'deps', deps, d)
955 }
956
957 def check_app_exists(app, d):
958         from bb import which, data
959
960         app = data.expand(app, d)
961         path = data.getVar('PATH', d, 1)
962         return len(which(path, app)) != 0
963
964 def check_gcc3(data):
965
966         gcc3_versions = 'gcc-3.4 gcc34 gcc-3.4.4 gcc-3.4.6 gcc-3.4.7 gcc-3.3 gcc33 gcc-3.3.6 gcc-3.2 gcc32'
967
968         for gcc3 in gcc3_versions.split():
969                 if check_app_exists(gcc3, data):
970                         return gcc3
971         
972         return False
973
974 # Patch handling
975 inherit patch
976
977 # Configuration data from site files
978 # Move to autotools.bbclass?
979 inherit siteinfo
980
981 EXPORT_FUNCTIONS do_clean do_mrproper do_fetch do_unpack do_configure do_compile do_install do_package do_populate_pkgs do_stage do_rebuild do_fetchall
982
983 MIRRORS[func] = "0"
984 MIRRORS () {
985 ${DEBIAN_MIRROR}/main   http://snapshot.debian.net/archive/pool
986 ${DEBIAN_MIRROR}        ftp://ftp.de.debian.org/debian/pool
987 ${DEBIAN_MIRROR}        ftp://ftp.au.debian.org/debian/pool
988 ${DEBIAN_MIRROR}        ftp://ftp.cl.debian.org/debian/pool
989 ${DEBIAN_MIRROR}        ftp://ftp.hr.debian.org/debian/pool
990 ${DEBIAN_MIRROR}        ftp://ftp.fi.debian.org/debian/pool
991 ${DEBIAN_MIRROR}        ftp://ftp.hk.debian.org/debian/pool
992 ${DEBIAN_MIRROR}        ftp://ftp.hu.debian.org/debian/pool
993 ${DEBIAN_MIRROR}        ftp://ftp.ie.debian.org/debian/pool
994 ${DEBIAN_MIRROR}        ftp://ftp.it.debian.org/debian/pool
995 ${DEBIAN_MIRROR}        ftp://ftp.jp.debian.org/debian/pool
996 ${DEBIAN_MIRROR}        ftp://ftp.no.debian.org/debian/pool
997 ${DEBIAN_MIRROR}        ftp://ftp.pl.debian.org/debian/pool
998 ${DEBIAN_MIRROR}        ftp://ftp.ro.debian.org/debian/pool
999 ${DEBIAN_MIRROR}        ftp://ftp.si.debian.org/debian/pool
1000 ${DEBIAN_MIRROR}        ftp://ftp.es.debian.org/debian/pool
1001 ${DEBIAN_MIRROR}        ftp://ftp.se.debian.org/debian/pool
1002 ${DEBIAN_MIRROR}        ftp://ftp.tr.debian.org/debian/pool
1003 ${GNU_MIRROR}   ftp://mirrors.kernel.org/gnu
1004 ${GNU_MIRROR}   ftp://ftp.matrix.com.br/pub/gnu
1005 ${GNU_MIRROR}   ftp://ftp.cs.ubc.ca/mirror2/gnu
1006 ${GNU_MIRROR}   ftp://sunsite.ust.hk/pub/gnu
1007 ${GNU_MIRROR}   ftp://ftp.ayamura.org/pub/gnu
1008 ${KERNELORG_MIRROR}     http://www.kernel.org/pub
1009 ${KERNELORG_MIRROR}     ftp://ftp.us.kernel.org/pub
1010 ${KERNELORG_MIRROR}     ftp://ftp.uk.kernel.org/pub
1011 ${KERNELORG_MIRROR}     ftp://ftp.hk.kernel.org/pub
1012 ${KERNELORG_MIRROR}     ftp://ftp.au.kernel.org/pub
1013 ${KERNELORG_MIRROR}     ftp://ftp.jp.kernel.org/pub
1014 ftp://ftp.gnupg.org/gcrypt/     ftp://ftp.franken.de/pub/crypt/mirror/ftp.gnupg.org/gcrypt/
1015 ftp://ftp.gnupg.org/gcrypt/     ftp://ftp.surfnet.nl/pub/security/gnupg/
1016 ftp://ftp.gnupg.org/gcrypt/     http://gulus.USherbrooke.ca/pub/appl/GnuPG/
1017 ftp://dante.ctan.org/tex-archive ftp://ftp.fu-berlin.de/tex/CTAN
1018 ftp://dante.ctan.org/tex-archive http://sunsite.sut.ac.jp/pub/archives/ctan/
1019 ftp://dante.ctan.org/tex-archive http://ctan.unsw.edu.au/
1020 ftp://ftp.gnutls.org/pub/gnutls ftp://ftp.gnutls.org/pub/gnutls/
1021 ftp://ftp.gnutls.org/pub/gnutls ftp://ftp.gnupg.org/gcrypt/gnutls/
1022 ftp://ftp.gnutls.org/pub/gnutls http://www.mirrors.wiretapped.net/security/network-security/gnutls/
1023 ftp://ftp.gnutls.org/pub/gnutls ftp://ftp.mirrors.wiretapped.net/pub/security/network-security/gnutls/
1024 ftp://ftp.gnutls.org/pub/gnutls http://josefsson.org/gnutls/releases/
1025 http://ftp.info-zip.org/pub/infozip/src/ http://mirror.switch.ch/ftp/mirror/infozip/src/
1026 http://ftp.info-zip.org/pub/infozip/src/ ftp://sunsite.icm.edu.pl/pub/unix/archiving/info-zip/src/
1027 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.cerias.purdue.edu/pub/tools/unix/sysutils/lsof/
1028 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.tau.ac.il/pub/unix/admin/
1029 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.cert.dfn.de/pub/tools/admin/lsof/
1030 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.fu-berlin.de/pub/unix/tools/lsof/
1031 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.kaizo.org/pub/lsof/
1032 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.tu-darmstadt.de/pub/sysadmin/lsof/
1033 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.tux.org/pub/sites/vic.cc.purdue.edu/tools/unix/lsof/
1034 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://gd.tuwien.ac.at/utils/admin-tools/lsof/
1035 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://sunsite.ualberta.ca/pub/Mirror/lsof/
1036 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://the.wiretapped.net/pub/security/host-security/lsof/
1037 http://www.apache.org/dist  http://archive.apache.org/dist
1038
1039 }
1040