conf/bitbake.conf: Merge in multimachine making it the standard layout as discussed...
[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         # The ":" ensures we have an 'empty' override
164         overrides = (bb.data.getVar("OVERRIDES", d, 1) or "") + ":"
165         for p in path:
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
291         dotlai=$libname.lai
292
293         # Sanity check that the libname.lai is unique
294         number_of_files=`(cd $dir; find . -name "$dotlai") | wc -l`
295         if [ $number_of_files -gt 1 ]; then
296                 oefatal "oe_libinstall: $dotlai is not unique in $dir"
297         fi
298
299
300         dir=$dir`(cd $dir;find . -name "$dotlai") | sed "s/^\.//;s/\/$dotlai\$//;q"`
301         olddir=`pwd`
302         __runcmd cd $dir
303
304         lafile=$libname.la
305
306         # If such file doesn't exist, try to cut version suffix
307         if [ ! -f "$lafile" ]; then
308                 libname1=`echo "$libname" | sed 's/-[0-9.]*$//'`
309                 lafile1=$libname.la
310                 if [ -f "$lafile1" ]; then
311                         libname=$libname1
312                         lafile=$lafile1
313                 fi
314         fi
315
316         if [ -f "$lafile" ]; then
317                 # libtool archive
318                 eval `cat $lafile|grep "^library_names="`
319                 libtool=1
320         else
321                 library_names="$libname.so* $libname.dll.a"
322         fi
323
324         __runcmd install -d $destpath/
325         dota=$libname.a
326         if [ -f "$dota" -o -n "$require_static" ]; then
327                 __runcmd install -m 0644 $dota $destpath/
328         fi
329         if [ -f "$dotlai" -a -n "$libtool" ]; then
330                 if test -n "$staging_install"
331                 then
332                         # stop libtool using the final directory name for libraries
333                         # in staging:
334                         __runcmd rm -f $destpath/$libname.la
335                         __runcmd sed -e 's/^installed=yes$/installed=no/' \
336                                      -e '/^dependency_libs=/s,${WORKDIR}[[:alnum:]/\._+-]*/\([[:alnum:]\._+-]*\),${STAGING_LIBDIR}/\1,g' \
337                                      -e "/^dependency_libs=/s,\([[:space:]']\)${libdir},\1${STAGING_LIBDIR},g" \
338                                      $dotlai >$destpath/$libname.la
339                 else
340                         __runcmd install -m 0644 $dotlai $destpath/$libname.la
341                 fi
342         fi
343
344         for name in $library_names; do
345                 files=`eval echo $name`
346                 for f in $files; do
347                         if [ ! -e "$f" ]; then
348                                 if [ -n "$libtool" ]; then
349                                         oefatal "oe_libinstall: $dir/$f not found."
350                                 fi
351                         elif [ -L "$f" ]; then
352                                 __runcmd cp -P "$f" $destpath/
353                         elif [ ! -L "$f" ]; then
354                                 libfile="$f"
355                                 __runcmd install -m 0755 $libfile $destpath/
356                         fi
357                 done
358         done
359
360         if [ -z "$libfile" ]; then
361                 if  [ -n "$require_shared" ]; then
362                         oefatal "oe_libinstall: unable to locate shared library"
363                 fi
364         elif [ -z "$libtool" ]; then
365                 # special case hack for non-libtool .so.#.#.# links
366                 baselibfile=`basename "$libfile"`
367                 if (echo $baselibfile | grep -qE '^lib.*\.so\.[0-9.]*$'); then
368                         sonamelink=`${HOST_PREFIX}readelf -d $libfile |grep 'Library soname:' |sed -e 's/.*\[\(.*\)\].*/\1/'`
369                         solink=`echo $baselibfile | sed -e 's/\.so\..*/.so/'`
370                         if [ -n "$sonamelink" -a x"$baselibfile" != x"$sonamelink" ]; then
371                                 __runcmd ln -sf $baselibfile $destpath/$sonamelink
372                         fi
373                         __runcmd ln -sf $baselibfile $destpath/$solink
374                 fi
375         fi
376
377         __runcmd cd "$olddir"
378 }
379
380 def package_stagefile(file, d):
381     import bb, os
382
383     if bb.data.getVar('PSTAGING_ACTIVE', d, True) == "1":
384         destfile = file.replace(bb.data.getVar("TMPDIR", d, 1), bb.data.getVar("PSTAGE_TMPDIR_STAGE", d, 1))
385         bb.mkdirhier(os.path.dirname(destfile))
386         #print "%s to %s" % (file, destfile)
387         bb.copyfile(file, destfile)
388
389 package_stagefile_shell() {
390         if [ "$PSTAGING_ACTIVE" = "1" ]; then
391                 srcfile=$1
392                 destfile=`echo $srcfile | sed s#${TMPDIR}#${PSTAGE_TMPDIR_STAGE}#`
393                 destdir=`dirname $destfile`
394                 mkdir -p $destdir
395                 cp -dp $srcfile $destfile
396         fi
397 }
398
399 oe_machinstall() {
400         # Purpose: Install machine dependent files, if available
401         #          If not available, check if there is a default
402         #          If no default, just touch the destination
403         # Example:
404         #                $1  $2   $3         $4
405         # oe_machinstall -m 0644 fstab ${D}/etc/fstab
406         #
407         # TODO: Check argument number?
408         #
409         filename=`basename $3`
410         dirname=`dirname $3`
411
412         for o in `echo ${OVERRIDES} | tr ':' ' '`; do
413                 if [ -e $dirname/$o/$filename ]; then
414                         oenote $dirname/$o/$filename present, installing to $4
415                         install $1 $2 $dirname/$o/$filename $4
416                         return
417                 fi
418         done
419 #       oenote overrides specific file NOT present, trying default=$3...
420         if [ -e $3 ]; then
421                 oenote $3 present, installing to $4
422                 install $1 $2 $3 $4
423         else
424                 oenote $3 NOT present, touching empty $4
425                 touch $4
426         fi
427 }
428
429 addtask listtasks
430 do_listtasks[nostamp] = "1"
431 python do_listtasks() {
432         import sys
433         # emit variables and shell functions
434         #bb.data.emit_env(sys.__stdout__, d)
435         # emit the metadata which isnt valid shell
436         for e in d.keys():
437                 if bb.data.getVarFlag(e, 'task', d):
438                         sys.__stdout__.write("%s\n" % e)
439 }
440
441 addtask clean
442 do_clean[dirs] = "${TOPDIR}"
443 do_clean[nostamp] = "1"
444 python base_do_clean() {
445         """clear the build and temp directories"""
446         dir = bb.data.expand("${WORKDIR}", d)
447         if dir == '//': raise bb.build.FuncFailed("wrong DATADIR")
448         bb.note("removing " + dir)
449         os.system('rm -rf ' + dir)
450
451         dir = "%s.*" % bb.data.expand(bb.data.getVar('STAMP', d), d)
452         bb.note("removing " + dir)
453         os.system('rm -f '+ dir)
454 }
455
456 #Uncomment this for bitbake 1.8.12
457 #addtask rebuild after do_${BB_DEFAULT_TASK}
458 addtask rebuild
459 do_rebuild[dirs] = "${TOPDIR}"
460 do_rebuild[nostamp] = "1"
461 python base_do_rebuild() {
462         """rebuild a package"""
463         from bb import __version__
464         try:
465                 from distutils.version import LooseVersion
466         except ImportError:
467                 def LooseVersion(v): print "WARNING: sanity.bbclass can't compare versions without python-distutils"; return 1
468         if (LooseVersion(__version__) < LooseVersion('1.8.11')):
469                 bb.build.exec_func('do_clean', d)
470                 bb.build.exec_task('do_' + bb.data.getVar('BB_DEFAULT_TASK', d, 1), d)
471 }
472
473 addtask mrproper
474 do_mrproper[dirs] = "${TOPDIR}"
475 do_mrproper[nostamp] = "1"
476 python base_do_mrproper() {
477         """clear downloaded sources, build and temp directories"""
478         dir = bb.data.expand("${DL_DIR}", d)
479         if dir == '/': bb.build.FuncFailed("wrong DATADIR")
480         bb.debug(2, "removing " + dir)
481         os.system('rm -rf ' + dir)
482         bb.build.exec_func('do_clean', d)
483 }
484
485 SCENEFUNCS += "base_scenefunction"
486                                                                                         
487 python base_do_setscene () {
488         for f in (bb.data.getVar('SCENEFUNCS', d, 1) or '').split():
489                 bb.build.exec_func(f, d)
490         if not os.path.exists(bb.data.getVar('STAMP', d, 1) + ".do_setscene"):
491                 bb.build.make_stamp("do_setscene", d)
492 }
493 do_setscene[selfstamp] = "1"
494 addtask setscene before do_fetch
495
496 python base_scenefunction () {
497         stamp = bb.data.getVar('STAMP', d, 1) + ".needclean"
498         if os.path.exists(stamp):
499                 bb.build.exec_func("do_clean", d)
500 }
501
502
503 addtask fetch
504 do_fetch[dirs] = "${DL_DIR}"
505 do_fetch[depends] = "shasum-native:do_populate_staging"
506 python base_do_fetch() {
507         import sys
508
509         localdata = bb.data.createCopy(d)
510         bb.data.update_data(localdata)
511
512         src_uri = bb.data.getVar('SRC_URI', localdata, 1)
513         if not src_uri:
514                 return 1
515
516         try:
517                 bb.fetch.init(src_uri.split(),d)
518         except bb.fetch.NoMethodError:
519                 (type, value, traceback) = sys.exc_info()
520                 raise bb.build.FuncFailed("No method: %s" % value)
521
522         try:
523                 bb.fetch.go(localdata)
524         except bb.fetch.MissingParameterError:
525                 (type, value, traceback) = sys.exc_info()
526                 raise bb.build.FuncFailed("Missing parameters: %s" % value)
527         except bb.fetch.FetchError:
528                 (type, value, traceback) = sys.exc_info()
529                 raise bb.build.FuncFailed("Fetch failed: %s" % value)
530         except bb.fetch.MD5SumError:
531                 (type, value, traceback) = sys.exc_info()
532                 raise bb.build.FuncFailed("MD5  failed: %s" % value)
533         except:
534                 (type, value, traceback) = sys.exc_info()
535                 raise bb.build.FuncFailed("Unknown fetch Error: %s" % value)
536
537
538         # Verify the SHA and MD5 sums we have in OE and check what do
539         # in
540         check_sum = bb.which(bb.data.getVar('BBPATH', d, True), "conf/checksums.ini")
541         if not check_sum:
542                 bb.note("No conf/checksums.ini found, not checking checksums")
543                 return
544
545         try:
546                 parser = base_chk_load_parser(check_sum)
547         except:
548                 bb.note("Creating the CheckSum parser failed")
549                 return
550
551         pv = bb.data.getVar('PV', d, True)
552         pn = bb.data.getVar('PN', d, True)
553
554         # Check each URI
555         for url in src_uri.split():
556                 localpath = bb.data.expand(bb.fetch.localpath(url, localdata), localdata)
557                 (type,host,path,_,_,_) = bb.decodeurl(url)
558                 uri = "%s://%s%s" % (type,host,path)
559                 try:
560                         if type == "http" or type == "https" or type == "ftp" or type == "ftps":
561                                 if not base_chk_file(parser, pn, pv,uri, localpath, d):
562                                         bb.note("%s-%s: %s has no entry in conf/checksums.ini, not checking URI" % (pn,pv,uri))
563                 except Exception:
564                         raise bb.build.FuncFailed("Checksum of '%s' failed" % uri)
565 }
566
567 addtask fetchall after do_fetch
568 do_fetchall[recrdeptask] = "do_fetch"
569 base_do_fetchall() {
570         :
571 }
572
573 addtask checkuri
574 do_checkuri[nostamp] = "1"
575 python do_checkuri() {
576         import sys
577
578         localdata = bb.data.createCopy(d)
579         bb.data.update_data(localdata)
580
581         src_uri = bb.data.getVar('SRC_URI', localdata, 1)
582
583         try:
584                 bb.fetch.init(src_uri.split(),d)
585         except bb.fetch.NoMethodError:
586                 (type, value, traceback) = sys.exc_info()
587                 raise bb.build.FuncFailed("No method: %s" % value)
588
589         try:
590                 bb.fetch.checkstatus(localdata)
591         except bb.fetch.MissingParameterError:
592                 (type, value, traceback) = sys.exc_info()
593                 raise bb.build.FuncFailed("Missing parameters: %s" % value)
594         except bb.fetch.FetchError:
595                 (type, value, traceback) = sys.exc_info()
596                 raise bb.build.FuncFailed("Fetch failed: %s" % value)
597         except bb.fetch.MD5SumError:
598                 (type, value, traceback) = sys.exc_info()
599                 raise bb.build.FuncFailed("MD5  failed: %s" % value)
600         except:
601                 (type, value, traceback) = sys.exc_info()
602                 raise bb.build.FuncFailed("Unknown fetch Error: %s" % value)
603 }
604
605 addtask checkuriall after do_checkuri
606 do_checkuriall[recrdeptask] = "do_checkuri"
607 do_checkuriall[nostamp] = "1"
608 base_do_checkuriall() {
609         :
610 }
611
612 addtask buildall after do_build
613 do_buildall[recrdeptask] = "do_build"
614 base_do_buildall() {
615         :
616 }
617
618
619 def oe_unpack_file(file, data, url = None):
620         import bb, os
621         if not url:
622                 url = "file://%s" % file
623         dots = file.split(".")
624         if dots[-1] in ['gz', 'bz2', 'Z']:
625                 efile = os.path.join(bb.data.getVar('WORKDIR', data, 1),os.path.basename('.'.join(dots[0:-1])))
626         else:
627                 efile = file
628         cmd = None
629         if file.endswith('.tar'):
630                 cmd = 'tar x --no-same-owner -f %s' % file
631         elif file.endswith('.tgz') or file.endswith('.tar.gz') or file.endswith('.tar.Z'):
632                 cmd = 'tar xz --no-same-owner -f %s' % file
633         elif file.endswith('.tbz') or file.endswith('.tbz2') or file.endswith('.tar.bz2'):
634                 cmd = 'bzip2 -dc %s | tar x --no-same-owner -f -' % file
635         elif file.endswith('.gz') or file.endswith('.Z') or file.endswith('.z'):
636                 cmd = 'gzip -dc %s > %s' % (file, efile)
637         elif file.endswith('.bz2'):
638                 cmd = 'bzip2 -dc %s > %s' % (file, efile)
639         elif file.endswith('.zip'):
640                 cmd = 'unzip -q -o'
641                 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
642                 if 'dos' in parm:
643                         cmd = '%s -a' % cmd
644                 cmd = '%s %s' % (cmd, file)
645         elif os.path.isdir(file):
646                 filesdir = os.path.realpath(bb.data.getVar("FILESDIR", data, 1))
647                 destdir = "."
648                 if file[0:len(filesdir)] == filesdir:
649                         destdir = file[len(filesdir):file.rfind('/')]
650                         destdir = destdir.strip('/')
651                         if len(destdir) < 1:
652                                 destdir = "."
653                         elif not os.access("%s/%s" % (os.getcwd(), destdir), os.F_OK):
654                                 os.makedirs("%s/%s" % (os.getcwd(), destdir))
655                 cmd = 'cp -pPR %s %s/%s/' % (file, os.getcwd(), destdir)
656         else:
657                 (type, host, path, user, pswd, parm) = bb.decodeurl(url)
658                 if not 'patch' in parm:
659                         # The "destdir" handling was specifically done for FILESPATH
660                         # items.  So, only do so for file:// entries.
661                         if type == "file":
662                                 destdir = bb.decodeurl(url)[1] or "."
663                         else:
664                                 destdir = "."
665                         bb.mkdirhier("%s/%s" % (os.getcwd(), destdir))
666                         cmd = 'cp %s %s/%s/' % (file, os.getcwd(), destdir)
667
668         if not cmd:
669                 return True
670
671         dest = os.path.join(os.getcwd(), os.path.basename(file))
672         if os.path.exists(dest):
673                 if os.path.samefile(file, dest):
674                         return True
675
676         cmd = "PATH=\"%s\" %s" % (bb.data.getVar('PATH', data, 1), cmd)
677         bb.note("Unpacking %s to %s/" % (file, os.getcwd()))
678         ret = os.system(cmd)
679         return ret == 0
680
681 addtask unpack after do_fetch
682 do_unpack[dirs] = "${WORKDIR}"
683 python base_do_unpack() {
684         import re, os
685
686         localdata = bb.data.createCopy(d)
687         bb.data.update_data(localdata)
688
689         src_uri = bb.data.getVar('SRC_URI', localdata)
690         if not src_uri:
691                 return
692         src_uri = bb.data.expand(src_uri, localdata)
693         for url in src_uri.split():
694                 try:
695                         local = bb.data.expand(bb.fetch.localpath(url, localdata), localdata)
696                 except bb.MalformedUrl, e:
697                         raise FuncFailed('Unable to generate local path for malformed uri: %s' % e)
698                 local = os.path.realpath(local)
699                 ret = oe_unpack_file(local, localdata, url)
700                 if not ret:
701                         raise bb.build.FuncFailed()
702 }
703
704 def base_get_scmbasepath(d):
705         import bb
706         path_to_bbfiles = bb.data.getVar( 'BBFILES', d, 1 ).split()
707         return path_to_bbfiles[0][:path_to_bbfiles[0].rindex( "packages" )]
708
709 def base_get_metadata_monotone_branch(d):
710         monotone_branch = "<unknown>"
711         try:
712                 monotone_branch = file( "%s/_MTN/options" % base_get_scmbasepath(d) ).read().strip()
713                 if monotone_branch.startswith( "database" ):
714                         monotone_branch_words = monotone_branch.split()
715                         monotone_branch = monotone_branch_words[ monotone_branch_words.index( "branch" )+1][1:-1]
716         except:
717                 pass
718         return monotone_branch
719
720 def base_get_metadata_monotone_revision(d):
721         monotone_revision = "<unknown>"
722         try:
723                 monotone_revision = file( "%s/_MTN/revision" % base_get_scmbasepath(d) ).read().strip()
724                 if monotone_revision.startswith( "format_version" ):
725                         monotone_revision_words = monotone_revision.split()
726                         monotone_revision = monotone_revision_words[ monotone_revision_words.index( "old_revision" )+1][1:-1]
727         except IOError:
728                 pass
729         return monotone_revision
730
731 def base_get_metadata_svn_revision(d):
732         revision = "<unknown>"
733         try:
734                 revision = file( "%s/.svn/entries" % base_get_scmbasepath(d) ).readlines()[3].strip()
735         except IOError:
736                 pass
737         return revision
738
739 METADATA_BRANCH ?= "${@base_get_metadata_monotone_branch(d)}"
740 METADATA_REVISION ?= "${@base_get_metadata_monotone_revision(d)}"
741
742 addhandler base_eventhandler
743 python base_eventhandler() {
744         from bb import note, error, data
745         from bb.event import Handled, NotHandled, getName
746         import os
747
748         messages = {}
749         messages["Completed"] = "completed"
750         messages["Succeeded"] = "completed"
751         messages["Started"] = "started"
752         messages["Failed"] = "failed"
753
754         name = getName(e)
755         msg = ""
756         if name.startswith("Pkg"):
757                 msg += "package %s: " % data.getVar("P", e.data, 1)
758                 msg += messages.get(name[3:]) or name[3:]
759         elif name.startswith("Task"):
760                 msg += "package %s: task %s: " % (data.getVar("PF", e.data, 1), e.task)
761                 msg += messages.get(name[4:]) or name[4:]
762         elif name.startswith("Build"):
763                 msg += "build %s: " % e.name
764                 msg += messages.get(name[5:]) or name[5:]
765         elif name == "UnsatisfiedDep":
766                 msg += "package %s: dependency %s %s" % (e.pkg, e.dep, name[:-3].lower())
767         if msg:
768                 note(msg)
769
770         if name.startswith("BuildStarted"):
771                 bb.data.setVar( 'BB_VERSION', bb.__version__, e.data )
772                 statusvars = ['BB_VERSION', 'METADATA_BRANCH', 'METADATA_REVISION', 'TARGET_ARCH', 'TARGET_OS', 'MACHINE', 'DISTRO', 'DISTRO_VERSION','TARGET_FPU']
773                 statuslines = ["%-17s = \"%s\"" % (i, bb.data.getVar(i, e.data, 1) or '') for i in statusvars]
774                 statusmsg = "\nOE Build Configuration:\n%s\n" % '\n'.join(statuslines)
775                 print statusmsg
776
777                 needed_vars = [ "TARGET_ARCH", "TARGET_OS" ]
778                 pesteruser = []
779                 for v in needed_vars:
780                         val = bb.data.getVar(v, e.data, 1)
781                         if not val or val == 'INVALID':
782                                 pesteruser.append(v)
783                 if pesteruser:
784                         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))
785
786         #
787         # Handle removing stamps for 'rebuild' task
788         #
789         if name.startswith("StampUpdate"):
790                 for (fn, task) in e.targets:
791                         #print "%s %s" % (task, fn)         
792                         if task == "do_rebuild":
793                                 dir = "%s.*" % e.stampPrefix[fn]
794                                 bb.note("Removing stamps: " + dir)
795                                 os.system('rm -f '+ dir)
796                                 os.system('touch ' + e.stampPrefix[fn] + '.needclean')
797
798         if not data in e.__dict__:
799                 return NotHandled
800
801         log = data.getVar("EVENTLOG", e.data, 1)
802         if log:
803                 logfile = file(log, "a")
804                 logfile.write("%s\n" % msg)
805                 logfile.close()
806
807         return NotHandled
808 }
809
810 addtask configure after do_unpack do_patch
811 do_configure[dirs] = "${S} ${B}"
812 do_configure[deptask] = "do_populate_staging"
813 base_do_configure() {
814         :
815 }
816
817 addtask compile after do_configure
818 do_compile[dirs] = "${S} ${B}"
819 base_do_compile() {
820         if [ -e Makefile -o -e makefile ]; then
821                 oe_runmake || die "make failed"
822         else
823                 oenote "nothing to compile"
824         fi
825 }
826
827 base_do_stage () {
828         :
829 }
830
831 do_populate_staging[dirs] = "${STAGING_DIR_TARGET}/${layout_bindir} ${STAGING_DIR_TARGET}/${layout_libdir} \
832                              ${STAGING_DIR_TARGET}/${layout_includedir} \
833                              ${STAGING_BINDIR_NATIVE} ${STAGING_LIBDIR_NATIVE} \
834                              ${STAGING_INCDIR_NATIVE} \
835                              ${STAGING_DATADIR} \
836                              ${S} ${B}"
837
838 # Could be compile but populate_staging and do_install shouldn't run at the same time
839 addtask populate_staging after do_install
840
841 python do_populate_staging () {
842     bb.build.exec_func('do_stage', d)
843 }
844
845 addtask install after do_compile
846 do_install[dirs] = "${D} ${S} ${B}"
847 # Remove and re-create ${D} so that is it guaranteed to be empty
848 do_install[cleandirs] = "${D}"
849
850 base_do_install() {
851         :
852 }
853
854 base_do_package() {
855         :
856 }
857
858 addtask build after do_populate_staging
859 do_build = ""
860 do_build[func] = "1"
861
862 # Functions that update metadata based on files outputted
863 # during the build process.
864
865 def explode_deps(s):
866         r = []
867         l = s.split()
868         flag = False
869         for i in l:
870                 if i[0] == '(':
871                         flag = True
872                         j = []
873                 if flag:
874                         j.append(i)
875                         if i.endswith(')'):
876                                 flag = False
877                                 r[-1] += ' ' + ' '.join(j)
878                 else:
879                         r.append(i)
880         return r
881
882 def packaged(pkg, d):
883         import os, bb
884         return os.access(get_subpkgedata_fn(pkg, d) + '.packaged', os.R_OK)
885
886 def read_pkgdatafile(fn):
887         pkgdata = {}
888
889         def decode(str):
890                 import codecs
891                 c = codecs.getdecoder("string_escape")
892                 return c(str)[0]
893
894         import os
895         if os.access(fn, os.R_OK):
896                 import re
897                 f = file(fn, 'r')
898                 lines = f.readlines()
899                 f.close()
900                 r = re.compile("([^:]+):\s*(.*)")
901                 for l in lines:
902                         m = r.match(l)
903                         if m:
904                                 pkgdata[m.group(1)] = decode(m.group(2))
905
906         return pkgdata
907
908 def get_subpkgedata_fn(pkg, d):
909         import bb, os
910         archs = bb.data.expand("${PACKAGE_ARCHS}", d).split(" ")
911         archs.reverse()
912         pkgdata = bb.data.expand('${STAGING_DIR}/pkgdata/', d)
913         targetdir = bb.data.expand('${TARGET_VENDOR}-${TARGET_OS}/runtime/', d)
914         for arch in archs:
915                 fn = pkgdata + arch + targetdir + pkg
916                 if os.path.exists(fn):
917                         return fn
918         return bb.data.expand('${PKGDATA_DIR}/runtime/%s' % pkg, d)
919
920 def has_subpkgdata(pkg, d):
921         import bb, os
922         return os.access(get_subpkgedata_fn(pkg, d), os.R_OK)
923
924 def read_subpkgdata(pkg, d):
925         import bb
926         return read_pkgdatafile(get_subpkgedata_fn(pkg, d))
927
928 def has_pkgdata(pn, d):
929         import bb, os
930         fn = bb.data.expand('${PKGDATA_DIR}/%s' % pn, d)
931         return os.access(fn, os.R_OK)
932
933 def read_pkgdata(pn, d):
934         import bb
935         fn = bb.data.expand('${PKGDATA_DIR}/%s' % pn, d)
936         return read_pkgdatafile(fn)
937
938 python read_subpackage_metadata () {
939         import bb
940         data = read_pkgdata(bb.data.getVar('PN', d, 1), d)
941
942         for key in data.keys():
943                 bb.data.setVar(key, data[key], d)
944
945         for pkg in bb.data.getVar('PACKAGES', d, 1).split():
946                 sdata = read_subpkgdata(pkg, d)
947                 for key in sdata.keys():
948                         bb.data.setVar(key, sdata[key], d)
949 }
950
951 # Make sure MACHINE isn't exported
952 # (breaks binutils at least)
953 MACHINE[unexport] = "1"
954
955 # Make sure TARGET_ARCH isn't exported
956 # (breaks Makefiles using implicit rules, e.g. quilt, as GNU make has this 
957 # in them, undocumented)
958 TARGET_ARCH[unexport] = "1"
959
960 # Make sure DISTRO isn't exported
961 # (breaks sysvinit at least)
962 DISTRO[unexport] = "1"
963
964
965 def base_after_parse(d):
966     import bb, os, exceptions
967
968     source_mirror_fetch = bb.data.getVar('SOURCE_MIRROR_FETCH', d, 0)
969     if not source_mirror_fetch:
970         need_host = bb.data.getVar('COMPATIBLE_HOST', d, 1)
971         if need_host:
972             import re
973             this_host = bb.data.getVar('HOST_SYS', d, 1)
974             if not re.match(need_host, this_host):
975                 raise bb.parse.SkipPackage("incompatible with host %s" % this_host)
976
977         need_machine = bb.data.getVar('COMPATIBLE_MACHINE', d, 1)
978         if need_machine:
979             import re
980             this_machine = bb.data.getVar('MACHINE', d, 1)
981             if this_machine and not re.match(need_machine, this_machine):
982                 raise bb.parse.SkipPackage("incompatible with machine %s" % this_machine)
983
984     pn = bb.data.getVar('PN', d, 1)
985
986     # OBSOLETE in bitbake 1.7.4
987     srcdate = bb.data.getVar('SRCDATE_%s' % pn, d, 1)
988     if srcdate != None:
989         bb.data.setVar('SRCDATE', srcdate, d)
990
991     use_nls = bb.data.getVar('USE_NLS_%s' % pn, d, 1)
992     if use_nls != None:
993         bb.data.setVar('USE_NLS', use_nls, d)
994
995     # Git packages should DEPEND on git-native
996     srcuri = bb.data.getVar('SRC_URI', d, 1)
997     if "git://" in srcuri:
998         depends = bb.data.getVarFlag('do_fetch', 'depends', d) or ""
999         depends = depends + " git-native:do_populate_staging"
1000         bb.data.setVarFlag('do_fetch', 'depends', depends, d)
1001
1002     # 'multimachine' handling
1003     mach_arch = bb.data.getVar('MACHINE_ARCH', d, 1)
1004     pkg_arch = bb.data.getVar('PACKAGE_ARCH', d, 1)
1005
1006     if (pkg_arch == mach_arch):
1007         # Already machine specific - nothing further to do
1008         return
1009
1010     #
1011     # We always try to scan SRC_URI for urls with machine overrides
1012     # unless the package sets SRC_URI_OVERRIDES_PACKAGE_ARCH=0
1013     #
1014     override = bb.data.getVar('SRC_URI_OVERRIDES_PACKAGE_ARCH', d, 1)
1015     if override != '0':
1016         paths = []
1017         for p in [ "${PF}", "${P}", "${PN}", "files", "" ]:
1018             path = bb.data.expand(os.path.join("${FILE_DIRNAME}", p, "${MACHINE}"), d)
1019             if os.path.isdir(path):
1020                 paths.append(path)
1021         if len(paths) != 0:
1022             for s in srcuri.split():
1023                 if not s.startswith("file://"):
1024                     continue
1025                 local = bb.data.expand(bb.fetch.localpath(s, d), d)
1026                 for mp in paths:
1027                     if local.startswith(mp):
1028                         #bb.note("overriding PACKAGE_ARCH from %s to %s" % (pkg_arch, mach_arch))
1029                         bb.data.setVar('PACKAGE_ARCH', "${MACHINE_ARCH}", d)
1030                         bb.data.setVar('MULTIMACH_ARCH', mach_arch, d)
1031                         return
1032
1033     multiarch = pkg_arch
1034
1035     packages = bb.data.getVar('PACKAGES', d, 1).split()
1036     for pkg in packages:
1037         pkgarch = bb.data.getVar("PACKAGE_ARCH_%s" % pkg, d, 1)
1038
1039         # We could look for != PACKAGE_ARCH here but how to choose 
1040         # if multiple differences are present?
1041         # Look through PACKAGE_ARCHS for the priority order?
1042         if pkgarch and pkgarch == mach_arch:
1043             multiarch = mach_arch
1044             break
1045
1046     bb.data.setVar('MULTIMACH_ARCH', multiarch, d)
1047
1048 python () {
1049     import bb
1050     from bb import __version__
1051     base_after_parse(d)
1052
1053     # Remove this for bitbake 1.8.12
1054     try:
1055         from distutils.version import LooseVersion
1056     except ImportError:
1057         def LooseVersion(v): print "WARNING: sanity.bbclass can't compare versions without python-distutils"; return 1
1058     if (LooseVersion(__version__) >= LooseVersion('1.8.11')):
1059         deps = bb.data.getVarFlag('do_rebuild', 'deps', d) or []
1060         deps.append('do_' + bb.data.getVar('BB_DEFAULT_TASK', d, 1))
1061         bb.data.setVarFlag('do_rebuild', 'deps', deps, d)
1062 }
1063
1064 def check_app_exists(app, d):
1065         from bb import which, data
1066
1067         app = data.expand(app, d)
1068         path = data.getVar('PATH', d, 1)
1069         return len(which(path, app)) != 0
1070
1071 def check_gcc3(data):
1072
1073         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'
1074
1075         for gcc3 in gcc3_versions.split():
1076                 if check_app_exists(gcc3, data):
1077                         return gcc3
1078         
1079         return False
1080
1081 # Patch handling
1082 inherit patch
1083
1084 # Configuration data from site files
1085 # Move to autotools.bbclass?
1086 inherit siteinfo
1087
1088 EXPORT_FUNCTIONS do_setscene 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
1089
1090 MIRRORS[func] = "0"
1091 MIRRORS () {
1092 ${DEBIAN_MIRROR}/main   http://snapshot.debian.net/archive/pool
1093 ${DEBIAN_MIRROR}        ftp://ftp.de.debian.org/debian/pool
1094 ${DEBIAN_MIRROR}        ftp://ftp.au.debian.org/debian/pool
1095 ${DEBIAN_MIRROR}        ftp://ftp.cl.debian.org/debian/pool
1096 ${DEBIAN_MIRROR}        ftp://ftp.hr.debian.org/debian/pool
1097 ${DEBIAN_MIRROR}        ftp://ftp.fi.debian.org/debian/pool
1098 ${DEBIAN_MIRROR}        ftp://ftp.hk.debian.org/debian/pool
1099 ${DEBIAN_MIRROR}        ftp://ftp.hu.debian.org/debian/pool
1100 ${DEBIAN_MIRROR}        ftp://ftp.ie.debian.org/debian/pool
1101 ${DEBIAN_MIRROR}        ftp://ftp.it.debian.org/debian/pool
1102 ${DEBIAN_MIRROR}        ftp://ftp.jp.debian.org/debian/pool
1103 ${DEBIAN_MIRROR}        ftp://ftp.no.debian.org/debian/pool
1104 ${DEBIAN_MIRROR}        ftp://ftp.pl.debian.org/debian/pool
1105 ${DEBIAN_MIRROR}        ftp://ftp.ro.debian.org/debian/pool
1106 ${DEBIAN_MIRROR}        ftp://ftp.si.debian.org/debian/pool
1107 ${DEBIAN_MIRROR}        ftp://ftp.es.debian.org/debian/pool
1108 ${DEBIAN_MIRROR}        ftp://ftp.se.debian.org/debian/pool
1109 ${DEBIAN_MIRROR}        ftp://ftp.tr.debian.org/debian/pool
1110 ${GNU_MIRROR}   ftp://mirrors.kernel.org/gnu
1111 ${GNU_MIRROR}   ftp://ftp.matrix.com.br/pub/gnu
1112 ${GNU_MIRROR}   ftp://ftp.cs.ubc.ca/mirror2/gnu
1113 ${GNU_MIRROR}   ftp://sunsite.ust.hk/pub/gnu
1114 ${GNU_MIRROR}   ftp://ftp.ayamura.org/pub/gnu
1115 ${KERNELORG_MIRROR}     http://www.kernel.org/pub
1116 ${KERNELORG_MIRROR}     ftp://ftp.us.kernel.org/pub
1117 ${KERNELORG_MIRROR}     ftp://ftp.uk.kernel.org/pub
1118 ${KERNELORG_MIRROR}     ftp://ftp.hk.kernel.org/pub
1119 ${KERNELORG_MIRROR}     ftp://ftp.au.kernel.org/pub
1120 ${KERNELORG_MIRROR}     ftp://ftp.jp.kernel.org/pub
1121 ftp://ftp.gnupg.org/gcrypt/     ftp://ftp.franken.de/pub/crypt/mirror/ftp.gnupg.org/gcrypt/
1122 ftp://ftp.gnupg.org/gcrypt/     ftp://ftp.surfnet.nl/pub/security/gnupg/
1123 ftp://ftp.gnupg.org/gcrypt/     http://gulus.USherbrooke.ca/pub/appl/GnuPG/
1124 ftp://dante.ctan.org/tex-archive ftp://ftp.fu-berlin.de/tex/CTAN
1125 ftp://dante.ctan.org/tex-archive http://sunsite.sut.ac.jp/pub/archives/ctan/
1126 ftp://dante.ctan.org/tex-archive http://ctan.unsw.edu.au/
1127 ftp://ftp.gnutls.org/pub/gnutls ftp://ftp.gnutls.org/pub/gnutls/
1128 ftp://ftp.gnutls.org/pub/gnutls ftp://ftp.gnupg.org/gcrypt/gnutls/
1129 ftp://ftp.gnutls.org/pub/gnutls http://www.mirrors.wiretapped.net/security/network-security/gnutls/
1130 ftp://ftp.gnutls.org/pub/gnutls ftp://ftp.mirrors.wiretapped.net/pub/security/network-security/gnutls/
1131 ftp://ftp.gnutls.org/pub/gnutls http://josefsson.org/gnutls/releases/
1132 http://ftp.info-zip.org/pub/infozip/src/ http://mirror.switch.ch/ftp/mirror/infozip/src/
1133 http://ftp.info-zip.org/pub/infozip/src/ ftp://sunsite.icm.edu.pl/pub/unix/archiving/info-zip/src/
1134 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.cerias.purdue.edu/pub/tools/unix/sysutils/lsof/
1135 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.tau.ac.il/pub/unix/admin/
1136 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.cert.dfn.de/pub/tools/admin/lsof/
1137 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.fu-berlin.de/pub/unix/tools/lsof/
1138 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.kaizo.org/pub/lsof/
1139 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.tu-darmstadt.de/pub/sysadmin/lsof/
1140 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://ftp.tux.org/pub/sites/vic.cc.purdue.edu/tools/unix/lsof/
1141 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://gd.tuwien.ac.at/utils/admin-tools/lsof/
1142 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://sunsite.ualberta.ca/pub/Mirror/lsof/
1143 ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/  ftp://the.wiretapped.net/pub/security/host-security/lsof/
1144 http://www.apache.org/dist  http://archive.apache.org/dist
1145
1146 }
1147