firefox: Perform a number of cleanups and fix consistency issues.
[openembedded.git] / 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 def base_path_relative(src, dest):
14     """ Return a relative path from src to dest.
15
16     >>> base_path_relative("/usr/bin", "/tmp/foo/bar")
17     ../../tmp/foo/bar
18
19     >>> base_path_relative("/usr/bin", "/usr/lib")
20     ../lib
21
22     >>> base_path_relative("/tmp", "/tmp/foo/bar")
23     foo/bar
24     """
25     from os.path import sep, pardir, normpath, commonprefix
26
27     destlist = normpath(dest).split(sep)
28     srclist = normpath(src).split(sep)
29
30     # Find common section of the path
31     common = commonprefix([destlist, srclist])
32     commonlen = len(common)
33
34     # Climb back to the point where they differentiate
35     relpath = [ pardir ] * (len(srclist) - commonlen)
36     if commonlen < len(destlist):
37         # Add remaining portion
38         relpath += destlist[commonlen:]
39
40     return sep.join(relpath)
41
42 def base_path_out(path, d):
43     """ Prepare a path for display to the user. """
44     rel = base_path_relative(d.getVar("TOPDIR", 1), path)
45     if len(rel) > len(path):
46         return path
47     else:
48         return rel
49
50 # for MD5/SHA handling
51 def base_chk_load_parser(config_paths):
52     import ConfigParser
53     parser = ConfigParser.ConfigParser()
54     if len(parser.read(config_paths)) < 1:
55         raise ValueError("no ini files could be found")
56
57     return parser
58
59 def base_chk_file_vars(parser, localpath, params, data):
60     try:
61         name = params["name"]
62     except KeyError:
63         return False
64     flagName = "%s.md5sum" % name
65     want_md5sum = bb.data.getVarFlag("SRC_URI", flagName, data)
66     flagName = "%s.sha256sum" % name
67     want_sha256sum = bb.data.getVarFlag("SRC_URI", flagName, data)
68
69     if (want_sha256sum == None and want_md5sum == None):
70         # no checksums to check, nothing to do
71         return False
72
73     if not os.path.exists(localpath):
74         localpath = base_path_out(localpath, data)
75         bb.note("The localpath does not exist '%s'" % localpath)
76         raise Exception("The path does not exist '%s'" % localpath)
77
78     if want_md5sum:
79         try:
80             md5pipe = os.popen('PATH=%s md5sum %s' % (bb.data.getVar('PATH', data, True), localpath))
81             md5data = (md5pipe.readline().split() or [ "" ])[0]
82             md5pipe.close()
83         except OSError, e:
84             raise Exception("Executing md5sum failed")
85         if want_md5sum != md5data:
86             bb.note("The MD5Sums did not match. Wanted: '%s' and Got: '%s'" % (want_md5sum, md5data))
87             raise Exception("MD5 Sums do not match. Wanted: '%s' Got: '%s'" % (want_md5sum, md5data))
88
89     if want_sha256sum:
90         try:
91             shapipe = os.popen('PATH=%s oe_sha256sum %s' % (bb.data.getVar('PATH', data, True), localpath))
92             sha256data = (shapipe.readline().split() or [ "" ])[0]
93             shapipe.close()
94         except OSError, e:
95             raise Exception("Executing shasum failed")
96         if want_sha256sum != sha256data:
97             bb.note("The SHA256Sums did not match. Wanted: '%s' and Got: '%s'" % (want_sha256sum, sha256data))
98             raise Exception("SHA256 Sums do not match. Wanted: '%s' Got: '%s'" % (want_sha256sum, sha256data))
99
100     return True
101
102
103 def base_chk_file(parser, pn, pv, src_uri, localpath, data):
104     no_checksum = False
105     # Try PN-PV-SRC_URI first and then try PN-SRC_URI
106     # we rely on the get method to create errors
107     pn_pv_src = "%s-%s-%s" % (pn,pv,src_uri)
108     pn_src    = "%s-%s" % (pn,src_uri)
109     if parser.has_section(pn_pv_src):
110         md5    = parser.get(pn_pv_src, "md5")
111         sha256 = parser.get(pn_pv_src, "sha256")
112     elif parser.has_section(pn_src):
113         md5    = parser.get(pn_src, "md5")
114         sha256 = parser.get(pn_src, "sha256")
115     elif parser.has_section(src_uri):
116         md5    = parser.get(src_uri, "md5")
117         sha256 = parser.get(src_uri, "sha256")
118     else:
119         no_checksum = True
120
121     # md5 and sha256 should be valid now
122     if not os.path.exists(localpath):
123         localpath = base_path_out(localpath, data)
124         bb.note("The localpath does not exist '%s'" % localpath)
125         raise Exception("The path does not exist '%s'" % localpath)
126
127
128     # call md5(sum) and shasum
129     try:
130         md5pipe = os.popen('PATH=%s md5sum %s' % (bb.data.getVar('PATH', data, True), localpath))
131         md5data = (md5pipe.readline().split() or [ "" ])[0]
132         md5pipe.close()
133     except OSError:
134         raise Exception("Executing md5sum failed")
135
136     try:
137         shapipe = os.popen('PATH=%s oe_sha256sum %s' % (bb.data.getVar('PATH', data, True), localpath))
138         shadata = (shapipe.readline().split() or [ "" ])[0]
139         shapipe.close()
140     except OSError:
141         raise Exception("Executing shasum failed")
142
143     if no_checksum == True:     # we do not have conf/checksums.ini entry
144         try:
145             file = open("%s/checksums.ini" % bb.data.getVar("TMPDIR", data, 1), "a")
146         except:
147             return False
148
149         if not file:
150             raise Exception("Creating checksums.ini failed")
151         
152         file.write("[%s]\nmd5=%s\nsha256=%s\n\n" % (src_uri, md5data, shadata))
153         file.close()
154
155         from string import maketrans
156         trtable = maketrans("", "")
157         uname = src_uri.split("/")[-1].translate(trtable, "-+._")
158
159         try:
160             ufile = open("%s/%s.sum" % (bb.data.getVar("TMPDIR", data, 1), uname), "wt")
161         except:
162             return False
163
164         if not ufile:
165             raise Exception("Creating %s.sum failed" % uname)
166
167         ufile.write("SRC_URI = \"%s;name=%s\"\nSRC_URI[%s.md5sum] = \"%s\"\nSRC_URI[%s.sha256sum] = \"%s\"\n" % (src_uri, uname, uname, md5data, uname, shadata))
168         ufile.close()
169
170         if not bb.data.getVar("OE_STRICT_CHECKSUMS",data, True):
171             bb.note("This package has no entry in checksums.ini, please add one")
172             bb.note("\n[%s]\nmd5=%s\nsha256=%s" % (src_uri, md5data, shadata))
173             bb.note("This package has no checksums in corresponding recipe, please add")
174             bb.note("SRC_URI = \"%s;name=%s\"\nSRC_URI[%s.md5sum] = \"%s\"\nSRC_URI[%s.sha256sum] = \"%s\"\n" % (src_uri, uname, uname, md5data, uname, shadata))
175             return True
176         else:
177             bb.note("Missing checksum")
178             return False
179
180     if not md5 == md5data:
181         bb.note("The MD5Sums did not match. Wanted: '%s' and Got: '%s'" % (md5,md5data))
182         raise Exception("MD5 Sums do not match. Wanted: '%s' Got: '%s'" % (md5, md5data))
183
184     if not sha256 == shadata:
185         bb.note("The SHA256 Sums do not match. Wanted: '%s' Got: '%s'" % (sha256,shadata))
186         raise Exception("SHA256 Sums do not match. Wanted: '%s' Got: '%s'" % (sha256, shadata))
187
188     return True
189
190
191 def base_dep_prepend(d):
192         #
193         # Ideally this will check a flag so we will operate properly in
194         # the case where host == build == target, for now we don't work in
195         # that case though.
196         #
197         deps = "shasum-native coreutils-native"
198         if bb.data.getVar('PN', d, True) == "shasum-native" or bb.data.getVar('PN', d, True) == "stagemanager-native":
199                 deps = ""
200         if bb.data.getVar('PN', d, True) == "coreutils-native":
201                 deps = "shasum-native"
202
203         # INHIBIT_DEFAULT_DEPS doesn't apply to the patch command.  Whether or  not
204         # we need that built is the responsibility of the patch function / class, not
205         # the application.
206         if not bb.data.getVar('INHIBIT_DEFAULT_DEPS', d):
207                 if (bb.data.getVar('HOST_SYS', d, 1) !=
208                     bb.data.getVar('BUILD_SYS', d, 1)):
209                         deps += " virtual/${TARGET_PREFIX}gcc virtual/libc "
210         return deps
211
212 def base_read_file(filename):
213         try:
214                 f = file( filename, "r" )
215         except IOError, reason:
216                 return "" # WARNING: can't raise an error now because of the new RDEPENDS handling. This is a bit ugly. :M:
217         else:
218                 return f.read().strip()
219         return None
220
221 def base_ifelse(condition, iftrue = True, iffalse = False):
222     if condition:
223         return iftrue
224     else:
225         return iffalse
226
227 def base_conditional(variable, checkvalue, truevalue, falsevalue, d):
228         if bb.data.getVar(variable,d,1) == checkvalue:
229                 return truevalue
230         else:
231                 return falsevalue
232
233 def base_less_or_equal(variable, checkvalue, truevalue, falsevalue, d):
234         if float(bb.data.getVar(variable,d,1)) <= float(checkvalue):
235                 return truevalue
236         else:
237                 return falsevalue
238
239 def base_version_less_or_equal(variable, checkvalue, truevalue, falsevalue, d):
240     result = bb.vercmp(bb.data.getVar(variable,d,True), checkvalue)
241     if result <= 0:
242         return truevalue
243     else:
244         return falsevalue
245
246 def base_contains(variable, checkvalues, truevalue, falsevalue, d):
247         val = bb.data.getVar(variable,d,1)
248         if not val:
249                 return falsevalue
250         matches = 0
251         if type(checkvalues).__name__ == "str":
252                 checkvalues = [checkvalues]
253         for value in checkvalues:
254                 if val.find(value) != -1:
255                         matches = matches + 1
256         if matches == len(checkvalues):
257                 return truevalue
258         return falsevalue
259
260 def base_both_contain(variable1, variable2, checkvalue, d):
261        if bb.data.getVar(variable1,d,1).find(checkvalue) != -1 and bb.data.getVar(variable2,d,1).find(checkvalue) != -1:
262                return checkvalue
263        else:
264                return ""
265
266 DEPENDS_prepend="${@base_dep_prepend(d)} "
267 DEPENDS_virtclass-native_prepend="${@base_dep_prepend(d)} "
268 DEPENDS_virtclass-nativesdk_prepend="${@base_dep_prepend(d)} "
269
270 def base_prune_suffix(var, suffixes, d):
271     # See if var ends with any of the suffixes listed and 
272     # remove it if found
273     for suffix in suffixes:
274         if var.endswith(suffix):
275             return var.replace(suffix, "")
276     return var
277
278 def base_set_filespath(path, d):
279         bb.note("base_set_filespath usage is deprecated, %s should be fixed" % d.getVar("P", 1))
280         filespath = []
281         # The ":" ensures we have an 'empty' override
282         overrides = (bb.data.getVar("OVERRIDES", d, 1) or "") + ":"
283         for p in path:
284                 for o in overrides.split(":"):
285                         filespath.append(os.path.join(p, o))
286         return ":".join(filespath)
287
288 def oe_filter(f, str, d):
289         from re import match
290         return " ".join(filter(lambda x: match(f, x, 0), str.split()))
291
292 def oe_filter_out(f, str, d):
293         from re import match
294         return " ".join(filter(lambda x: not match(f, x, 0), str.split()))
295
296 die() {
297         oefatal "$*"
298 }
299
300 oenote() {
301         echo "NOTE:" "$*"
302 }
303
304 oewarn() {
305         echo "WARNING:" "$*"
306 }
307
308 oefatal() {
309         echo "FATAL:" "$*"
310         exit 1
311 }
312
313 oedebug() {
314         test $# -ge 2 || {
315                 echo "Usage: oedebug level \"message\""
316                 exit 1
317         }
318
319         test ${OEDEBUG:-0} -ge $1 && {
320                 shift
321                 echo "DEBUG:" $*
322         }
323 }
324
325 oe_runmake() {
326         if [ x"$MAKE" = x ]; then MAKE=make; fi
327         oenote ${MAKE} ${EXTRA_OEMAKE} "$@"
328         ${MAKE} ${EXTRA_OEMAKE} "$@" || die "oe_runmake failed"
329 }
330
331 oe_soinstall() {
332         # Purpose: Install shared library file and
333         #          create the necessary links
334         # Example:
335         #
336         # oe_
337         #
338         #oenote installing shared library $1 to $2
339         #
340         libname=`basename $1`
341         install -m 755 $1 $2/$libname
342         sonamelink=`${HOST_PREFIX}readelf -d $1 |grep 'Library soname:' |sed -e 's/.*\[\(.*\)\].*/\1/'`
343         solink=`echo $libname | sed -e 's/\.so\..*/.so/'`
344         ln -sf $libname $2/$sonamelink
345         ln -sf $libname $2/$solink
346 }
347
348 oe_libinstall() {
349         # Purpose: Install a library, in all its forms
350         # Example
351         #
352         # oe_libinstall libltdl ${STAGING_LIBDIR}/
353         # oe_libinstall -C src/libblah libblah ${D}/${libdir}/
354         dir=""
355         libtool=""
356         silent=""
357         require_static=""
358         require_shared=""
359         staging_install=""
360         while [ "$#" -gt 0 ]; do
361                 case "$1" in
362                 -C)
363                         shift
364                         dir="$1"
365                         ;;
366                 -s)
367                         silent=1
368                         ;;
369                 -a)
370                         require_static=1
371                         ;;
372                 -so)
373                         require_shared=1
374                         ;;
375                 -*)
376                         oefatal "oe_libinstall: unknown option: $1"
377                         ;;
378                 *)
379                         break;
380                         ;;
381                 esac
382                 shift
383         done
384
385         libname="$1"
386         shift
387         destpath="$1"
388         if [ -z "$destpath" ]; then
389                 oefatal "oe_libinstall: no destination path specified"
390         fi
391         if echo "$destpath/" | egrep '^${STAGING_LIBDIR}/' >/dev/null
392         then
393                 staging_install=1
394         fi
395
396         __runcmd () {
397                 if [ -z "$silent" ]; then
398                         echo >&2 "oe_libinstall: $*"
399                 fi
400                 $*
401         }
402
403         if [ -z "$dir" ]; then
404                 dir=`pwd`
405         fi
406
407         dotlai=$libname.lai
408
409         # Sanity check that the libname.lai is unique
410         number_of_files=`(cd $dir; find . -name "$dotlai") | wc -l`
411         if [ $number_of_files -gt 1 ]; then
412                 oefatal "oe_libinstall: $dotlai is not unique in $dir"
413         fi
414
415
416         dir=$dir`(cd $dir;find . -name "$dotlai") | sed "s/^\.//;s/\/$dotlai\$//;q"`
417         olddir=`pwd`
418         __runcmd cd $dir
419
420         lafile=$libname.la
421
422         # If such file doesn't exist, try to cut version suffix
423         if [ ! -f "$lafile" ]; then
424                 libname1=`echo "$libname" | sed 's/-[0-9.]*$//'`
425                 lafile1=$libname.la
426                 if [ -f "$lafile1" ]; then
427                         libname=$libname1
428                         lafile=$lafile1
429                 fi
430         fi
431
432         if [ -f "$lafile" ]; then
433                 # libtool archive
434                 eval `cat $lafile|grep "^library_names="`
435                 libtool=1
436         else
437                 library_names="$libname.so* $libname.dll.a"
438         fi
439
440         __runcmd install -d $destpath/
441         dota=$libname.a
442         if [ -f "$dota" -o -n "$require_static" ]; then
443                 __runcmd install -m 0644 $dota $destpath/
444         fi
445         if [ -f "$dotlai" -a -n "$libtool" ]; then
446                 if test -n "$staging_install"
447                 then
448                         # stop libtool using the final directory name for libraries
449                         # in staging:
450                         __runcmd rm -f $destpath/$libname.la
451                         __runcmd sed -e 's/^installed=yes$/installed=no/' \
452                                      -e '/^dependency_libs=/s,${WORKDIR}[[:alnum:]/\._+-]*/\([[:alnum:]\._+-]*\),${STAGING_LIBDIR}/\1,g' \
453                                      -e "/^dependency_libs=/s,\([[:space:]']\)${libdir},\1${STAGING_LIBDIR},g" \
454                                      $dotlai >$destpath/$libname.la
455                 else
456                         __runcmd install -m 0644 $dotlai $destpath/$libname.la
457                 fi
458         fi
459
460         for name in $library_names; do
461                 files=`eval echo $name`
462                 for f in $files; do
463                         if [ ! -e "$f" ]; then
464                                 if [ -n "$libtool" ]; then
465                                         oefatal "oe_libinstall: $dir/$f not found."
466                                 fi
467                         elif [ -L "$f" ]; then
468                                 __runcmd cp -P "$f" $destpath/
469                         elif [ ! -L "$f" ]; then
470                                 libfile="$f"
471                                 __runcmd install -m 0755 $libfile $destpath/
472                         fi
473                 done
474         done
475
476         if [ -z "$libfile" ]; then
477                 if  [ -n "$require_shared" ]; then
478                         oefatal "oe_libinstall: unable to locate shared library"
479                 fi
480         elif [ -z "$libtool" ]; then
481                 # special case hack for non-libtool .so.#.#.# links
482                 baselibfile=`basename "$libfile"`
483                 if (echo $baselibfile | grep -qE '^lib.*\.so\.[0-9.]*$'); then
484                         sonamelink=`${HOST_PREFIX}readelf -d $libfile |grep 'Library soname:' |sed -e 's/.*\[\(.*\)\].*/\1/'`
485                         solink=`echo $baselibfile | sed -e 's/\.so\..*/.so/'`
486                         if [ -n "$sonamelink" -a x"$baselibfile" != x"$sonamelink" ]; then
487                                 __runcmd ln -sf $baselibfile $destpath/$sonamelink
488                         fi
489                         __runcmd ln -sf $baselibfile $destpath/$solink
490                 fi
491         fi
492
493         __runcmd cd "$olddir"
494 }
495
496 def package_stagefile(file, d):
497
498     if bb.data.getVar('PSTAGING_ACTIVE', d, True) == "1":
499         destfile = file.replace(bb.data.getVar("TMPDIR", d, 1), bb.data.getVar("PSTAGE_TMPDIR_STAGE", d, 1))
500         bb.mkdirhier(os.path.dirname(destfile))
501         #print "%s to %s" % (file, destfile)
502         bb.copyfile(file, destfile)
503
504 package_stagefile_shell() {
505         if [ "$PSTAGING_ACTIVE" = "1" ]; then
506                 srcfile=$1
507                 destfile=`echo $srcfile | sed s#${TMPDIR}#${PSTAGE_TMPDIR_STAGE}#`
508                 destdir=`dirname $destfile`
509                 mkdir -p $destdir
510                 cp -dp $srcfile $destfile
511         fi
512 }
513
514 oe_machinstall() {
515         # Purpose: Install machine dependent files, if available
516         #          If not available, check if there is a default
517         #          If no default, just touch the destination
518         # Example:
519         #                $1  $2   $3         $4
520         # oe_machinstall -m 0644 fstab ${D}/etc/fstab
521         #
522         # TODO: Check argument number?
523         #
524         filename=`basename $3`
525         dirname=`dirname $3`
526
527         for o in `echo ${OVERRIDES} | tr ':' ' '`; do
528                 if [ -e $dirname/$o/$filename ]; then
529                         oenote $dirname/$o/$filename present, installing to $4
530                         install $1 $2 $dirname/$o/$filename $4
531                         return
532                 fi
533         done
534 #       oenote overrides specific file NOT present, trying default=$3...
535         if [ -e $3 ]; then
536                 oenote $3 present, installing to $4
537                 install $1 $2 $3 $4
538         else
539                 oenote $3 NOT present, touching empty $4
540                 touch $4
541         fi
542 }
543
544 addtask listtasks
545 do_listtasks[nostamp] = "1"
546 python do_listtasks() {
547         import sys
548         # emit variables and shell functions
549         #bb.data.emit_env(sys.__stdout__, d)
550         # emit the metadata which isnt valid shell
551         for e in d.keys():
552                 if bb.data.getVarFlag(e, 'task', d):
553                         sys.__stdout__.write("%s\n" % e)
554 }
555
556 addtask clean
557 do_clean[dirs] = "${TOPDIR}"
558 do_clean[nostamp] = "1"
559 python base_do_clean() {
560         """clear the build and temp directories"""
561         dir = bb.data.expand("${WORKDIR}", d)
562         if dir == '//': raise bb.build.FuncFailed("wrong DATADIR")
563         bb.note("removing " + base_path_out(dir, d))
564         os.system('rm -rf ' + dir)
565
566         dir = "%s.*" % bb.data.expand(bb.data.getVar('STAMP', d), d)
567         bb.note("removing " + base_path_out(dir, d))
568         os.system('rm -f '+ dir)
569 }
570
571 python do_cleanall() {
572     pass
573 }
574 do_cleanall[recrdeptask] = "do_clean"
575 addtask cleanall after do_clean
576
577 addtask rebuild after do_${BB_DEFAULT_TASK}
578 do_rebuild[dirs] = "${TOPDIR}"
579 do_rebuild[nostamp] = "1"
580 python base_do_rebuild() {
581         """rebuild a package"""
582 }
583
584 addtask mrproper
585 do_mrproper[dirs] = "${TOPDIR}"
586 do_mrproper[nostamp] = "1"
587 python base_do_mrproper() {
588         """clear downloaded sources, build and temp directories"""
589         dir = bb.data.expand("${DL_DIR}", d)
590         if dir == '/': bb.build.FuncFailed("wrong DATADIR")
591         bb.debug(2, "removing " + dir)
592         os.system('rm -rf ' + dir)
593         bb.build.exec_func('do_clean', d)
594 }
595
596 addtask distclean
597 do_distclean[dirs] = "${TOPDIR}"
598 do_distclean[nostamp] = "1"
599 python base_do_distclean() {
600         """clear downloaded sources, build and temp directories"""
601
602         bb.build.exec_func('do_clean', d)
603
604         src_uri = bb.data.getVar('SRC_URI', d, 1)
605         if not src_uri:
606                 return
607
608         for uri in src_uri.split():
609                 if bb.decodeurl(uri)[0] == "file":
610                         continue
611
612                 try:
613                         local = bb.data.expand(bb.fetch.localpath(uri, d), d)
614                 except bb.MalformedUrl, e:
615                         bb.debug(1, 'Unable to generate local path for malformed uri: %s' % e)
616                 else:
617                         bb.note("removing %s" % base_path_out(local, d))
618                         try:
619                                 if os.path.exists(local + ".md5"):
620                                         os.remove(local + ".md5")
621                                 if os.path.exists(local):
622                                         os.remove(local)
623                         except OSError, e:
624                                 bb.note("Error in removal: %s" % e)
625 }
626
627 SCENEFUNCS += "base_scenefunction"
628                                                                                         
629 python base_do_setscene () {
630         for f in (bb.data.getVar('SCENEFUNCS', d, 1) or '').split():
631                 bb.build.exec_func(f, d)
632         if not os.path.exists(bb.data.getVar('STAMP', d, 1) + ".do_setscene"):
633                 bb.build.make_stamp("do_setscene", d)
634 }
635 do_setscene[selfstamp] = "1"
636 addtask setscene before do_fetch
637
638 python base_scenefunction () {
639         stamp = bb.data.getVar('STAMP', d, 1) + ".needclean"
640         if os.path.exists(stamp):
641                 bb.build.exec_func("do_clean", d)
642 }
643
644
645 addtask fetch
646 do_fetch[dirs] = "${DL_DIR}"
647 do_fetch[depends] = "shasum-native:do_populate_staging"
648 python base_do_fetch() {
649         import sys
650
651         localdata = bb.data.createCopy(d)
652         bb.data.update_data(localdata)
653
654         src_uri = bb.data.getVar('SRC_URI', localdata, 1)
655         if not src_uri:
656                 return 1
657
658         try:
659                 bb.fetch.init(src_uri.split(),d)
660         except bb.fetch.NoMethodError:
661                 (type, value, traceback) = sys.exc_info()
662                 raise bb.build.FuncFailed("No method: %s" % value)
663         except bb.MalformedUrl:
664                 (type, value, traceback) = sys.exc_info()
665                 raise bb.build.FuncFailed("Malformed URL: %s" % value)
666
667         try:
668                 bb.fetch.go(localdata)
669         except bb.fetch.MissingParameterError:
670                 (type, value, traceback) = sys.exc_info()
671                 raise bb.build.FuncFailed("Missing parameters: %s" % value)
672         except bb.fetch.FetchError:
673                 (type, value, traceback) = sys.exc_info()
674                 raise bb.build.FuncFailed("Fetch failed: %s" % value)
675         except bb.fetch.MD5SumError:
676                 (type, value, traceback) = sys.exc_info()
677                 raise bb.build.FuncFailed("MD5  failed: %s" % value)
678         except:
679                 (type, value, traceback) = sys.exc_info()
680                 raise bb.build.FuncFailed("Unknown fetch Error: %s" % value)
681
682
683         # Verify the SHA and MD5 sums we have in OE and check what do
684         # in
685         checksum_paths = bb.data.getVar('BBPATH', d, True).split(":")
686
687         # reverse the list to give precedence to directories that
688         # appear first in BBPATH
689         checksum_paths.reverse()
690
691         checksum_files = ["%s/conf/checksums.ini" % path for path in checksum_paths]
692         try:
693                 parser = base_chk_load_parser(checksum_files)
694         except ValueError:
695                 bb.note("No conf/checksums.ini found, not checking checksums")
696                 return
697         except:
698                 bb.note("Creating the CheckSum parser failed: %s:%s" % (sys.exc_info()[0], sys.exc_info()[1]))
699                 return
700
701         pv = bb.data.getVar('PV', d, True)
702         pn = bb.data.getVar('PN', d, True)
703
704         # Check each URI
705         for url in src_uri.split():
706                 localpath = bb.data.expand(bb.fetch.localpath(url, localdata), localdata)
707                 (type,host,path,_,_,params) = bb.decodeurl(url)
708                 uri = "%s://%s%s" % (type,host,path)
709                 try:
710                         if type in [ "http", "https", "ftp", "ftps" ]:
711                                 if not (base_chk_file_vars(parser, localpath, params, d) or base_chk_file(parser, pn, pv,uri, localpath, d)):
712                                         if not bb.data.getVar("OE_ALLOW_INSECURE_DOWNLOADS", d, True):
713                                                 bb.fatal("%s-%s: %s has no checksum defined, cannot check archive integrity" % (pn,pv,uri))
714                                         else:
715                                                 bb.note("%s-%s: %s has no checksum defined, archive integrity not checked" % (pn,pv,uri))
716                 except Exception:
717                         raise bb.build.FuncFailed("Checksum of '%s' failed" % uri)
718 }
719
720 addtask fetchall after do_fetch
721 do_fetchall[recrdeptask] = "do_fetch"
722 base_do_fetchall() {
723         :
724 }
725
726 addtask checkuri
727 do_checkuri[nostamp] = "1"
728 python do_checkuri() {
729         import sys
730
731         localdata = bb.data.createCopy(d)
732         bb.data.update_data(localdata)
733
734         src_uri = bb.data.getVar('SRC_URI', localdata, 1)
735
736         try:
737                 bb.fetch.init(src_uri.split(),d)
738         except bb.fetch.NoMethodError:
739                 (type, value, traceback) = sys.exc_info()
740                 raise bb.build.FuncFailed("No method: %s" % value)
741
742         try:
743                 bb.fetch.checkstatus(localdata)
744         except bb.fetch.MissingParameterError:
745                 (type, value, traceback) = sys.exc_info()
746                 raise bb.build.FuncFailed("Missing parameters: %s" % value)
747         except bb.fetch.FetchError:
748                 (type, value, traceback) = sys.exc_info()
749                 raise bb.build.FuncFailed("Fetch failed: %s" % value)
750         except bb.fetch.MD5SumError:
751                 (type, value, traceback) = sys.exc_info()
752                 raise bb.build.FuncFailed("MD5  failed: %s" % value)
753         except:
754                 (type, value, traceback) = sys.exc_info()
755                 raise bb.build.FuncFailed("Unknown fetch Error: %s" % value)
756 }
757
758 addtask checkuriall after do_checkuri
759 do_checkuriall[recrdeptask] = "do_checkuri"
760 do_checkuriall[nostamp] = "1"
761 base_do_checkuriall() {
762         :
763 }
764
765 addtask buildall after do_build
766 do_buildall[recrdeptask] = "do_build"
767 base_do_buildall() {
768         :
769 }
770
771 def subprocess_setup():
772         import signal
773         # Python installs a SIGPIPE handler by default. This is usually not what
774         # non-Python subprocesses expect.
775         signal.signal(signal.SIGPIPE, signal.SIG_DFL)
776
777 def oe_unpack_file(file, data, url = None):
778         import subprocess
779         if not url:
780                 url = "file://%s" % file
781         dots = file.split(".")
782         if dots[-1] in ['gz', 'bz2', 'Z']:
783                 efile = os.path.join(bb.data.getVar('WORKDIR', data, 1),os.path.basename('.'.join(dots[0:-1])))
784         else:
785                 efile = file
786         cmd = None
787         if file.endswith('.tar'):
788                 cmd = 'tar x --no-same-owner -f %s' % file
789         elif file.endswith('.tgz') or file.endswith('.tar.gz') or file.endswith('.tar.Z'):
790                 cmd = 'tar xz --no-same-owner -f %s' % file
791         elif file.endswith('.tbz') or file.endswith('.tbz2') or file.endswith('.tar.bz2'):
792                 cmd = 'bzip2 -dc %s | tar x --no-same-owner -f -' % file
793         elif file.endswith('.gz') or file.endswith('.Z') or file.endswith('.z'):
794                 cmd = 'gzip -dc %s > %s' % (file, efile)
795         elif file.endswith('.bz2'):
796                 cmd = 'bzip2 -dc %s > %s' % (file, efile)
797         elif file.endswith('.tar.xz'):
798                 cmd = 'xz -dc %s | tar x --no-same-owner -f -' % file
799         elif file.endswith('.xz'):
800                 cmd = 'xz -dc %s > %s' % (file, efile)
801         elif file.endswith('.zip') or file.endswith('.jar'):
802                 cmd = 'unzip -q -o'
803                 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
804                 if 'dos' in parm:
805                         cmd = '%s -a' % cmd
806                 cmd = '%s %s' % (cmd, file)
807         elif os.path.isdir(file):
808                 destdir = "."
809                 filespath = bb.data.getVar("FILESPATH", data, 1).split(":")
810                 for fp in filespath:
811                         if file[0:len(fp)] == fp:
812                                 destdir = file[len(fp):file.rfind('/')]
813                                 destdir = destdir.strip('/')
814                                 if len(destdir) < 1:
815                                         destdir = "."
816                                 elif not os.access("%s/%s" % (os.getcwd(), destdir), os.F_OK):
817                                         os.makedirs("%s/%s" % (os.getcwd(), destdir))
818                                 break
819
820                 cmd = 'cp -pPR %s %s/%s/' % (file, os.getcwd(), destdir)
821         else:
822                 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
823                 if not 'patch' in parm:
824                         # The "destdir" handling was specifically done for FILESPATH
825                         # items.  So, only do so for file:// entries.
826                         if type == "file":
827                                 destdir = bb.decodeurl(url)[1] or "."
828                         else:
829                                 destdir = "."
830                         bb.mkdirhier("%s/%s" % (os.getcwd(), destdir))
831                         cmd = 'cp %s %s/%s/' % (file, os.getcwd(), destdir)
832
833         if not cmd:
834                 return True
835
836         dest = os.path.join(os.getcwd(), os.path.basename(file))
837         if os.path.exists(dest):
838                 if os.path.samefile(file, dest):
839                         return True
840
841         # Change to subdir before executing command
842         save_cwd = os.getcwd();
843         parm = bb.decodeurl(url)[5]
844         if 'subdir' in parm:
845                 newdir = ("%s/%s" % (os.getcwd(), parm['subdir']))
846                 bb.mkdirhier(newdir)
847                 os.chdir(newdir)
848
849         cmd = "PATH=\"%s\" %s" % (bb.data.getVar('PATH', data, 1), cmd)
850         bb.note("Unpacking %s to %s/" % (base_path_out(file, data), base_path_out(os.getcwd(), data)))
851         ret = subprocess.call(cmd, preexec_fn=subprocess_setup, shell=True)
852
853         os.chdir(save_cwd)
854
855         return ret == 0
856
857 addtask unpack after do_fetch
858 do_unpack[dirs] = "${WORKDIR}"
859 python base_do_unpack() {
860         import re
861
862         localdata = bb.data.createCopy(d)
863         bb.data.update_data(localdata)
864
865         src_uri = bb.data.getVar('SRC_URI', localdata)
866         if not src_uri:
867                 return
868         src_uri = bb.data.expand(src_uri, localdata)
869         for url in src_uri.split():
870                 try:
871                         local = bb.data.expand(bb.fetch.localpath(url, localdata), localdata)
872                 except bb.MalformedUrl, e:
873                         raise bb.build.FuncFailed('Unable to generate local path for malformed uri: %s' % e)
874                 if not local:
875                         raise bb.build.FuncFailed('Unable to locate local file for %s' % url)
876                 local = os.path.realpath(local)
877                 ret = oe_unpack_file(local, localdata, url)
878                 if not ret:
879                         raise bb.build.FuncFailed()
880 }
881
882 METADATA_SCM = "${@base_get_scm(d)}"
883 METADATA_REVISION = "${@base_get_scm_revision(d)}"
884 METADATA_BRANCH = "${@base_get_scm_branch(d)}"
885
886 def base_get_scm(d):
887         from bb import which
888         baserepo = os.path.dirname(os.path.dirname(which(d.getVar("BBPATH", 1), "classes/base.bbclass")))
889         for (scm, scmpath) in {"svn": ".svn",
890                                "git": ".git",
891                                "monotone": "_MTN"}.iteritems():
892                 if os.path.exists(os.path.join(baserepo, scmpath)):
893                         return "%s %s" % (scm, baserepo)
894         return "<unknown> %s" % baserepo
895
896 def base_get_scm_revision(d):
897         (scm, path) = d.getVar("METADATA_SCM", 1).split()
898         try:
899                 if scm != "<unknown>":
900                         return globals()["base_get_metadata_%s_revision" % scm](path, d)
901                 else:
902                         return scm
903         except KeyError:
904                 return "<unknown>"
905
906 def base_get_scm_branch(d):
907         (scm, path) = d.getVar("METADATA_SCM", 1).split()
908         try:
909                 if scm != "<unknown>":
910                         return globals()["base_get_metadata_%s_branch" % scm](path, d)
911                 else:
912                         return scm
913         except KeyError:
914                 return "<unknown>"
915
916 def base_get_metadata_monotone_branch(path, d):
917         monotone_branch = "<unknown>"
918         try:
919                 monotone_branch = file( "%s/_MTN/options" % path ).read().strip()
920                 if monotone_branch.startswith( "database" ):
921                         monotone_branch_words = monotone_branch.split()
922                         monotone_branch = monotone_branch_words[ monotone_branch_words.index( "branch" )+1][1:-1]
923         except:
924                 pass
925         return monotone_branch
926
927 def base_get_metadata_monotone_revision(path, d):
928         monotone_revision = "<unknown>"
929         try:
930                 monotone_revision = file( "%s/_MTN/revision" % path ).read().strip()
931                 if monotone_revision.startswith( "format_version" ):
932                         monotone_revision_words = monotone_revision.split()
933                         monotone_revision = monotone_revision_words[ monotone_revision_words.index( "old_revision" )+1][1:-1]
934         except IOError:
935                 pass
936         return monotone_revision
937
938 def base_get_metadata_svn_revision(path, d):
939         revision = "<unknown>"
940         try:
941                 revision = file( "%s/.svn/entries" % path ).readlines()[3].strip()
942         except IOError:
943                 pass
944         return revision
945
946 def base_get_metadata_git_branch(path, d):
947         branch = os.popen('cd %s; PATH=%s git symbolic-ref HEAD 2>/dev/null' % (path, d.getVar("PATH", 1))).read().rstrip()
948
949         if len(branch) != 0:
950                 return branch.replace("refs/heads/", "")
951         return "<unknown>"
952
953 def base_get_metadata_git_revision(path, d):
954         rev = os.popen("cd %s; PATH=%s git show-ref HEAD 2>/dev/null" % (path, d.getVar("PATH", 1))).read().split(" ")[0].rstrip()
955         if len(rev) != 0:
956                 return rev
957         return "<unknown>"
958
959
960 addhandler base_eventhandler
961 python base_eventhandler() {
962         from bb import note, error, data
963         from bb.event import Handled, NotHandled, getName
964
965
966         name = getName(e)
967         if name == "TaskCompleted":
968                 msg = "package %s: task %s is complete." % (data.getVar("PF", e.data, 1), e.task)
969         elif name == "UnsatisfiedDep":
970                 msg = "package %s: dependency %s %s" % (e.pkg, e.dep, name[:-3].lower())
971         else:
972                 return NotHandled
973
974         # Only need to output when using 1.8 or lower, the UI code handles it
975         # otherwise
976         if (int(bb.__version__.split(".")[0]) <= 1 and int(bb.__version__.split(".")[1]) <= 8):
977                 if msg:
978                         note(msg)
979
980         if name.startswith("BuildStarted"):
981                 bb.data.setVar( 'BB_VERSION', bb.__version__, e.data )
982                 statusvars = bb.data.getVar("BUILDCFG_VARS", e.data, 1).split()
983                 statuslines = ["%-17s = \"%s\"" % (i, bb.data.getVar(i, e.data, 1) or '') for i in statusvars]
984                 statusmsg = "\n%s\n%s\n" % (bb.data.getVar("BUILDCFG_HEADER", e.data, 1), "\n".join(statuslines))
985                 print statusmsg
986
987                 needed_vars = bb.data.getVar("BUILDCFG_NEEDEDVARS", e.data, 1).split()
988                 pesteruser = []
989                 for v in needed_vars:
990                         val = bb.data.getVar(v, e.data, 1)
991                         if not val or val == 'INVALID':
992                                 pesteruser.append(v)
993                 if pesteruser:
994                         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))
995
996         #
997         # Handle removing stamps for 'rebuild' task
998         #
999         if name.startswith("StampUpdate"):
1000                 for (fn, task) in e.targets:
1001                         #print "%s %s" % (task, fn)         
1002                         if task == "do_rebuild":
1003                                 dir = "%s.*" % e.stampPrefix[fn]
1004                                 bb.note("Removing stamps: " + dir)
1005                                 os.system('rm -f '+ dir)
1006                                 os.system('touch ' + e.stampPrefix[fn] + '.needclean')
1007
1008         if not data in e.__dict__:
1009                 return NotHandled
1010
1011         log = data.getVar("EVENTLOG", e.data, 1)
1012         if log:
1013                 logfile = file(log, "a")
1014                 logfile.write("%s\n" % msg)
1015                 logfile.close()
1016
1017         return NotHandled
1018 }
1019
1020 addtask configure after do_unpack do_patch
1021 do_configure[dirs] = "${S} ${B}"
1022 do_configure[deptask] = "do_populate_staging"
1023 base_do_configure() {
1024         :
1025 }
1026
1027 addtask compile after do_configure
1028 do_compile[dirs] = "${S} ${B}"
1029 base_do_compile() {
1030         if [ -e Makefile -o -e makefile ]; then
1031                 oe_runmake || die "make failed"
1032         else
1033                 oenote "nothing to compile"
1034         fi
1035 }
1036
1037
1038 sysroot_stage_dir() {
1039         src="$1"
1040         dest="$2"
1041         # This will remove empty directories so we can ignore them
1042         rmdir "$src" 2> /dev/null || true
1043         if [ -d "$src" ]; then
1044                 mkdir -p "$dest"
1045                 cp -fpPR "$src"/* "$dest"
1046         fi
1047 }
1048
1049 sysroot_stage_libdir() {
1050         src="$1"
1051         dest="$2"
1052
1053         olddir=`pwd`
1054         cd $src
1055         las=$(find . -name \*.la -type f)
1056         cd $olddir
1057         echo "Found la files: $las"              
1058         for i in $las
1059         do
1060                 sed -e 's/^installed=yes$/installed=no/' \
1061                     -e '/^dependency_libs=/s,${WORKDIR}[[:alnum:]/\._+-]*/\([[:alnum:]\._+-]*\),${STAGING_LIBDIR}/\1,g' \
1062                     -e "/^dependency_libs=/s,\([[:space:]']\)${libdir},\1${STAGING_LIBDIR},g" \
1063                     -i $src/$i
1064         done
1065         sysroot_stage_dir $src $dest
1066 }
1067
1068 sysroot_stage_dirs() {
1069         from="$1"
1070         to="$2"
1071
1072         sysroot_stage_dir $from${includedir} $to${STAGING_INCDIR}
1073         if [ "${BUILD_SYS}" = "${HOST_SYS}" ]; then
1074                 sysroot_stage_dir $from${bindir} $to${STAGING_DIR_HOST}${bindir}
1075                 sysroot_stage_dir $from${sbindir} $to${STAGING_DIR_HOST}${sbindir}
1076                 sysroot_stage_dir $from${base_bindir} $to${STAGING_DIR_HOST}${base_bindir}
1077                 sysroot_stage_dir $from${base_sbindir} $to${STAGING_DIR_HOST}${base_sbindir}
1078                 sysroot_stage_dir $from${libexecdir} $to${STAGING_DIR_HOST}${libexecdir}
1079                 if [ "${prefix}/lib" != "${libdir}" ]; then
1080                         # python puts its files in here, make sure they are staged as well
1081                         autotools_stage_dir $from/${prefix}/lib $to${STAGING_DIR_HOST}${prefix}/lib
1082                 fi
1083         fi
1084         if [ -d $from${libdir} ]
1085         then
1086                 sysroot_stage_libdir $from/${libdir} $to${STAGING_LIBDIR}
1087         fi
1088         if [ -d $from${base_libdir} ]
1089         then
1090                 sysroot_stage_libdir $from${base_libdir} $to${STAGING_DIR_HOST}${base_libdir}
1091         fi
1092         sysroot_stage_dir $from${datadir} $to${STAGING_DATADIR}
1093 }
1094
1095 sysroot_stage_all() {
1096         sysroot_stage_dirs ${D} ${SYSROOT_DESTDIR}
1097 }
1098
1099 def is_legacy_staging(d):
1100     stagefunc = bb.data.getVar('do_stage', d, True)
1101     legacy = True
1102     if stagefunc is None:
1103         legacy = False
1104     elif stagefunc.strip() == "autotools_stage_all":
1105         legacy = False
1106     elif stagefunc.strip() == "do_stage_native" and bb.data.getVar('AUTOTOOLS_NATIVE_STAGE_INSTALL', d, 1) == "1":
1107         legacy = False
1108     elif bb.data.getVar('NATIVE_INSTALL_WORKS', d, 1) == "1":
1109         legacy = False
1110     if bb.data.getVar('PSTAGE_BROKEN_DESTDIR', d, 1) == "1":
1111         legacy = True
1112     if bb.data.getVar('FORCE_LEGACY_STAGING', d, 1) == "1":
1113         legacy = True
1114     return legacy
1115
1116 do_populate_staging[dirs] = "${STAGING_DIR_TARGET}/${bindir} ${STAGING_DIR_TARGET}/${libdir} \
1117                              ${STAGING_DIR_TARGET}/${includedir} \
1118                              ${STAGING_BINDIR_NATIVE} ${STAGING_LIBDIR_NATIVE} \
1119                              ${STAGING_INCDIR_NATIVE} \
1120                              ${STAGING_DATADIR} \
1121                              ${S} ${B}"
1122
1123 # Could be compile but populate_staging and do_install shouldn't run at the same time
1124 addtask populate_staging after do_install
1125
1126 SYSROOT_PREPROCESS_FUNCS ?= ""
1127 SYSROOT_DESTDIR = "${WORKDIR}/sysroot-destdir/"
1128 SYSROOT_LOCK = "${STAGING_DIR}/staging.lock"
1129
1130 python populate_staging_prehook () {
1131         return
1132 }
1133
1134 python populate_staging_posthook () {
1135         return
1136 }
1137
1138 packagedstaging_fastpath () {
1139         :
1140 }
1141
1142 python do_populate_staging () {
1143     #
1144     # if do_stage exists, we're legacy. In that case run the do_stage,
1145     # modify the SYSROOT_DESTDIR variable and then run the staging preprocess
1146     # functions against staging directly.
1147     #
1148     # Otherwise setup a destdir, copy the results from do_install
1149     # and run the staging preprocess against that
1150     #
1151     pstageactive = (bb.data.getVar("PSTAGING_ACTIVE", d, True) == "1")
1152     lockfile = bb.data.getVar("SYSROOT_LOCK", d, True)
1153     stagefunc = bb.data.getVar('do_stage', d, True)
1154     legacy = is_legacy_staging(d)
1155     if legacy:
1156         bb.data.setVar("SYSROOT_DESTDIR", "", d)
1157         bb.note("Legacy staging mode for %s" % bb.data.getVar("FILE", d, True))
1158
1159         try:
1160             file = open("%s/legacy-staging.log" % bb.data.getVar("TMPDIR", d, 1), "a")
1161             file.write("%s\n" % bb.data.getVar("FILE", d, True))
1162             file.close()
1163         except:
1164             pass
1165
1166         if bb.data.getVarFlags('do_stage', d) is None:
1167             bb.fatal("This recipe (%s) has a do_stage_prepend or do_stage_append and do_stage now doesn't exist. Please rename this to do_stage()" % bb.data.getVar("FILE", d, True))
1168         lock = bb.utils.lockfile(lockfile)
1169         bb.build.exec_func('populate_staging_prehook', d)
1170         bb.build.exec_func('do_stage', d)
1171         for f in (bb.data.getVar('SYSROOT_PREPROCESS_FUNCS', d, True) or '').split():
1172             bb.build.exec_func(f, d)
1173         bb.build.exec_func('populate_staging_posthook', d)
1174         bb.utils.unlockfile(lock)
1175     else:
1176         dest = bb.data.getVar('D', d, True)
1177         sysrootdest = bb.data.expand('${SYSROOT_DESTDIR}${STAGING_DIR_TARGET}', d)
1178         bb.mkdirhier(sysrootdest)
1179
1180         bb.build.exec_func("sysroot_stage_all", d)
1181         #os.system('cp -pPR %s/* %s/' % (dest, sysrootdest))
1182         for f in (bb.data.getVar('SYSROOT_PREPROCESS_FUNCS', d, True) or '').split():
1183             bb.build.exec_func(f, d)
1184         bb.build.exec_func("packagedstaging_fastpath", d)
1185
1186         lock = bb.utils.lockfile(lockfile)
1187         os.system(bb.data.expand('cp -pPR ${SYSROOT_DESTDIR}${TMPDIR}/* ${TMPDIR}/', d))
1188         bb.utils.unlockfile(lock)
1189 }
1190
1191 addtask install after do_compile
1192 do_install[dirs] = "${D} ${S} ${B}"
1193 # Remove and re-create ${D} so that is it guaranteed to be empty
1194 do_install[cleandirs] = "${D}"
1195
1196 base_do_install() {
1197         :
1198 }
1199
1200 base_do_package() {
1201         :
1202 }
1203
1204 addtask build after do_populate_staging
1205 do_build = ""
1206 do_build[func] = "1"
1207
1208 inherit packagedata
1209
1210 # Functions that update metadata based on files outputted
1211 # during the build process.
1212
1213 def explode_deps(s):
1214         r = []
1215         l = s.split()
1216         flag = False
1217         for i in l:
1218                 if i[0] == '(':
1219                         flag = True
1220                         j = []
1221                 if flag:
1222                         j.append(i)
1223                         if i.endswith(')'):
1224                                 flag = False
1225                                 r[-1] += ' ' + ' '.join(j)
1226                 else:
1227                         r.append(i)
1228         return r
1229
1230 # Make sure MACHINE isn't exported
1231 # (breaks binutils at least)
1232 MACHINE[unexport] = "1"
1233
1234 # Make sure TARGET_ARCH isn't exported
1235 # (breaks Makefiles using implicit rules, e.g. quilt, as GNU make has this 
1236 # in them, undocumented)
1237 TARGET_ARCH[unexport] = "1"
1238
1239 # Make sure DISTRO isn't exported
1240 # (breaks sysvinit at least)
1241 DISTRO[unexport] = "1"
1242
1243
1244 def base_after_parse(d):
1245     import exceptions
1246
1247     source_mirror_fetch = bb.data.getVar('SOURCE_MIRROR_FETCH', d, 0)
1248     if not source_mirror_fetch:
1249         need_host = bb.data.getVar('COMPATIBLE_HOST', d, 1)
1250         if need_host:
1251             import re
1252             this_host = bb.data.getVar('HOST_SYS', d, 1)
1253             if not re.match(need_host, this_host):
1254                 raise bb.parse.SkipPackage("incompatible with host %s" % this_host)
1255
1256         need_machine = bb.data.getVar('COMPATIBLE_MACHINE', d, 1)
1257         if need_machine:
1258             import re
1259             this_machine = bb.data.getVar('MACHINE', d, 1)
1260             if this_machine and not re.match(need_machine, this_machine):
1261                 raise bb.parse.SkipPackage("incompatible with machine %s" % this_machine)
1262
1263     pn = bb.data.getVar('PN', d, 1)
1264
1265     # OBSOLETE in bitbake 1.7.4
1266     srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
1267     if srcdate != None:
1268         bb.data.setVar('SRCDATE', srcdate, d)
1269
1270     use_nls = bb.data.getVar('USE_NLS_%s' % pn, d, 1)
1271     if use_nls != None:
1272         bb.data.setVar('USE_NLS', use_nls, d)
1273
1274     # Git packages should DEPEND on git-native
1275     srcuri = bb.data.getVar('SRC_URI', d, 1)
1276     if "git://" in srcuri:
1277         depends = bb.data.getVarFlag('do_fetch', 'depends', d) or ""
1278         depends = depends + " git-native:do_populate_staging"
1279         bb.data.setVarFlag('do_fetch', 'depends', depends, d)
1280
1281     # 'multimachine' handling
1282     mach_arch = bb.data.getVar('MACHINE_ARCH', d, 1)
1283     pkg_arch = bb.data.getVar('PACKAGE_ARCH', d, 1)
1284
1285     if (pkg_arch == mach_arch):
1286         # Already machine specific - nothing further to do
1287         return
1288
1289     #
1290     # We always try to scan SRC_URI for urls with machine overrides
1291     # unless the package sets SRC_URI_OVERRIDES_PACKAGE_ARCH=0
1292     #
1293     override = bb.data.getVar('SRC_URI_OVERRIDES_PACKAGE_ARCH', d, 1)
1294     if override != '0':
1295         paths = []
1296         for p in [ "${PF}", "${P}", "${PN}", "files", "" ]:
1297             path = bb.data.expand(os.path.join("${FILE_DIRNAME}", p, "${MACHINE}"), d)
1298             if os.path.isdir(path):
1299                 paths.append(path)
1300         if len(paths) != 0:
1301             for s in srcuri.split():
1302                 if not s.startswith("file://"):
1303                     continue
1304                 local = bb.data.expand(bb.fetch.localpath(s, d), d)
1305                 for mp in paths:
1306                     if local.startswith(mp):
1307                         #bb.note("overriding PACKAGE_ARCH from %s to %s" % (pkg_arch, mach_arch))
1308                         bb.data.setVar('PACKAGE_ARCH', "${MACHINE_ARCH}", d)
1309                         bb.data.setVar('MULTIMACH_ARCH', mach_arch, d)
1310                         return
1311
1312     multiarch = pkg_arch
1313
1314     packages = bb.data.getVar('PACKAGES', d, 1).split()
1315     for pkg in packages:
1316         pkgarch = bb.data.getVar("PACKAGE_ARCH_%s" % pkg, d, 1)
1317
1318         # We could look for != PACKAGE_ARCH here but how to choose 
1319         # if multiple differences are present?
1320         # Look through PACKAGE_ARCHS for the priority order?
1321         if pkgarch and pkgarch == mach_arch:
1322             multiarch = mach_arch
1323             break
1324
1325     bb.data.setVar('MULTIMACH_ARCH', multiarch, d)
1326
1327 python () {
1328     base_after_parse(d)
1329     if is_legacy_staging(d):
1330         bb.debug(1, "Legacy staging mode for %s" % bb.data.getVar("FILE", d, True))
1331         if bb.data.getVarFlags('do_stage', d) is None:
1332             bb.error("This recipe (%s) has a do_stage_prepend or do_stage_append and do_stage now doesn't exist. Please rename this to do_stage()" % bb.data.getVar("FILE", d, True))
1333
1334 }
1335
1336 def check_app_exists(app, d):
1337         from bb import which, data
1338
1339         app = data.expand(app, d)
1340         path = data.getVar('PATH', d, 1)
1341         return len(which(path, app)) != 0
1342
1343 def check_gcc3(data):
1344         # Primarly used by qemu to make sure we have a workable gcc-3.x.
1345         # Start by checking for the program name as we build it as there
1346         # are some distribtuion provided gcc-3.x's that will not work.
1347         gcc3_versions = 'gcc-3.4.6 gcc-3.4.4 gcc34 gcc-3.4 gcc-3.4.7 gcc-3.3 gcc33 gcc-3.3.6 gcc-3.2 gcc32'
1348
1349         for gcc3 in gcc3_versions.split():
1350                 if check_app_exists(gcc3, data):
1351                         return gcc3
1352
1353         return False
1354
1355 # Patch handling
1356 inherit patch
1357
1358 # Configuration data from site files
1359 # Move to autotools.bbclass?
1360 inherit siteinfo
1361
1362 EXPORT_FUNCTIONS do_setscene do_clean do_mrproper do_distclean do_fetch do_unpack do_configure do_compile do_install do_package do_populate_pkgs do_rebuild do_fetchall
1363
1364 MIRRORS[func] = "0"
1365 MIRRORS () {
1366 ${DEBIAN_MIRROR}/main   http://snapshot.debian.net/archive/pool
1367 ${DEBIAN_MIRROR}        ftp://ftp.de.debian.org/debian/pool
1368 ${DEBIAN_MIRROR}        ftp://ftp.au.debian.org/debian/pool
1369 ${DEBIAN_MIRROR}        ftp://ftp.cl.debian.org/debian/pool
1370 ${DEBIAN_MIRROR}        ftp://ftp.hr.debian.org/debian/pool
1371 ${DEBIAN_MIRROR}        ftp://ftp.fi.debian.org/debian/pool
1372 ${DEBIAN_MIRROR}        ftp://ftp.hk.debian.org/debian/pool
1373 ${DEBIAN_MIRROR}        ftp://ftp.hu.debian.org/debian/pool
1374 ${DEBIAN_MIRROR}        ftp://ftp.ie.debian.org/debian/pool
1375 ${DEBIAN_MIRROR}        ftp://ftp.it.debian.org/debian/pool
1376 ${DEBIAN_MIRROR}        ftp://ftp.jp.debian.org/debian/pool
1377 ${DEBIAN_MIRROR}        ftp://ftp.no.debian.org/debian/pool
1378 ${DEBIAN_MIRROR}        ftp://ftp.pl.debian.org/debian/pool
1379 ${DEBIAN_MIRROR}        ftp://ftp.ro.debian.org/debian/pool
1380 ${DEBIAN_MIRROR}        ftp://ftp.si.debian.org/debian/pool
1381 ${DEBIAN_MIRROR}        ftp://ftp.es.debian.org/debian/pool
1382 ${DEBIAN_MIRROR}        ftp://ftp.se.debian.org/debian/pool
1383 ${DEBIAN_MIRROR}        ftp://ftp.tr.debian.org/debian/pool
1384 ${GNU_MIRROR}   ftp://mirrors.kernel.org/gnu
1385 ${GNU_MIRROR}   ftp://ftp.cs.ubc.ca/mirror2/gnu
1386 ${GNU_MIRROR}   ftp://sunsite.ust.hk/pub/gnu
1387 ${GNU_MIRROR}   ftp://ftp.ayamura.org/pub/gnu
1388 ${KERNELORG_MIRROR}     http://www.kernel.org/pub
1389 ${KERNELORG_MIRROR}     ftp://ftp.us.kernel.org/pub
1390 ${KERNELORG_MIRROR}     ftp://ftp.uk.kernel.org/pub
1391 ${KERNELORG_MIRROR}     ftp://ftp.hk.kernel.org/pub
1392 ${KERNELORG_MIRROR}     ftp://ftp.au.kernel.org/pub
1393 ${KERNELORG_MIRROR}     ftp://ftp.jp.kernel.org/pub
1394 ftp://ftp.gnupg.org/gcrypt/     ftp://ftp.franken.de/pub/crypt/mirror/ftp.gnupg.org/gcrypt/
1395 ftp://ftp.gnupg.org/gcrypt/     ftp://ftp.surfnet.nl/pub/security/gnupg/
1396 ftp://ftp.gnupg.org/gcrypt/     http://gulus.USherbrooke.ca/pub/appl/GnuPG/
1397 ftp://dante.ctan.org/tex-archive ftp://ftp.fu-berlin.de/tex/CTAN
1398 ftp://dante.ctan.org/tex-archive http://sunsite.sut.ac.jp/pub/archives/ctan/
1399 ftp://dante.ctan.org/tex-archive http://ctan.unsw.edu.au/
1400 ftp://ftp.gnutls.org/pub/gnutls ftp://ftp.gnutls.org/pub/gnutls/
1401 ftp://ftp.gnutls.org/pub/gnutls ftp://ftp.gnupg.org/gcrypt/gnutls/
1402 ftp://ftp.gnutls.org/pub/gnutls http://www.mirrors.wiretapped.net/security/network-security/gnutls/
1403 ftp://ftp.gnutls.org/pub/gnutls ftp://ftp.mirrors.wiretapped.net/pub/security/network-security/gnutls/
1404 ftp://ftp.gnutls.org/pub/gnutls http://josefsson.org/gnutls/releases/
1405 http://ftp.info-zip.org/pub/infozip/src/ http://mirror.switch.ch/ftp/mirror/infozip/src/
1406 http://ftp.info-zip.org/pub/infozip/src/ ftp://sunsite.icm.edu.pl/pub/unix/archiving/info-zip/src/
1407 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.cerias.purdue.edu/pub/tools/unix/sysutils/lsof/
1408 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.tau.ac.il/pub/unix/admin/
1409 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.cert.dfn.de/pub/tools/admin/lsof/
1410 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.fu-berlin.de/pub/unix/tools/lsof/
1411 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.kaizo.org/pub/lsof/
1412 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.tu-darmstadt.de/pub/sysadmin/lsof/
1413 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.tux.org/pub/sites/vic.cc.purdue.edu/tools/unix/lsof/
1414 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://gd.tuwien.ac.at/utils/admin-tools/lsof/
1415 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://sunsite.ualberta.ca/pub/Mirror/lsof/
1416 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://the.wiretapped.net/pub/security/host-security/lsof/
1417 http://www.apache.org/dist  http://archive.apache.org/dist
1418 ftp://.*/.*     http://mirrors.openembedded.org/
1419 https?$://.*/.* http://mirrors.openembedded.org/
1420 ftp://.*/.*     http://sources.openembedded.org/
1421 https?$://.*/.* http://sources.openembedded.org/
1422
1423 }
1424