wafsamba: Pass down the install argument for samba modules
[kai/samba-autobuild/.git] / buildtools / wafsamba / wafsamba.py
1 # a waf tool to add autoconf-like macros to the configure section
2 # and for SAMBA_ macros for building libraries, binaries etc
3
4 import Build, os, sys, Options, Task, Utils, cc, TaskGen, fnmatch, re, shutil, Logs, Constants
5 from Configure import conf
6 from Logs import debug
7 from samba_utils import SUBST_VARS_RECURSIVE
8 TaskGen.task_gen.apply_verif = Utils.nada
9
10 # bring in the other samba modules
11 from samba_optimisation import *
12 from samba_utils import *
13 from samba_version import *
14 from samba_autoconf import *
15 from samba_patterns import *
16 from samba_pidl import *
17 from samba_autoproto import *
18 from samba_python import *
19 from samba_perl import *
20 from samba_deps import *
21 from samba_bundled import *
22 from samba_third_party import *
23 import samba_cross
24 import samba_install
25 import samba_conftests
26 import samba_abi
27 import samba_headers
28 import tru64cc
29 import irixcc
30 import hpuxcc
31 import generic_cc
32 import samba_dist
33 import samba_wildcard
34 import stale_files
35 import symbols
36 import pkgconfig
37 import configure_file
38
39 # some systems have broken threading in python
40 if os.environ.get('WAF_NOTHREADS') == '1':
41     import nothreads
42
43 LIB_PATH="shared"
44
45 os.environ['PYTHONUNBUFFERED'] = '1'
46
47
48 if Constants.HEXVERSION < 0x105019:
49     Logs.error('''
50 Please use the version of waf that comes with Samba, not
51 a system installed version. See http://wiki.samba.org/index.php/Waf
52 for details.
53
54 Alternatively, please run ./configure and make as usual. That will
55 call the right version of waf.''')
56     sys.exit(1)
57
58
59 @conf
60 def SAMBA_BUILD_ENV(conf):
61     '''create the samba build environment'''
62     conf.env.BUILD_DIRECTORY = conf.blddir
63     mkdir_p(os.path.join(conf.blddir, LIB_PATH))
64     mkdir_p(os.path.join(conf.blddir, LIB_PATH, "private"))
65     mkdir_p(os.path.join(conf.blddir, "modules"))
66     mkdir_p(os.path.join(conf.blddir, 'python/samba/dcerpc'))
67     # this allows all of the bin/shared and bin/python targets
68     # to be expressed in terms of build directory paths
69     mkdir_p(os.path.join(conf.blddir, 'default'))
70     for (source, target) in [('shared', 'shared'), ('modules', 'modules'), ('python', 'python_modules')]:
71         link_target = os.path.join(conf.blddir, 'default/' + target)
72         if not os.path.lexists(link_target):
73             os.symlink('../' + source, link_target)
74
75     # get perl to put the blib files in the build directory
76     blib_bld = os.path.join(conf.blddir, 'default/pidl/blib')
77     blib_src = os.path.join(conf.srcdir, 'pidl/blib')
78     mkdir_p(blib_bld + '/man1')
79     mkdir_p(blib_bld + '/man3')
80     if os.path.islink(blib_src):
81         os.unlink(blib_src)
82     elif os.path.exists(blib_src):
83         shutil.rmtree(blib_src)
84
85
86 def ADD_INIT_FUNCTION(bld, subsystem, target, init_function):
87     '''add an init_function to the list for a subsystem'''
88     if init_function is None:
89         return
90     bld.ASSERT(subsystem is not None, "You must specify a subsystem for init_function '%s'" % init_function)
91     cache = LOCAL_CACHE(bld, 'INIT_FUNCTIONS')
92     if not subsystem in cache:
93         cache[subsystem] = []
94     cache[subsystem].append( { 'TARGET':target, 'INIT_FUNCTION':init_function } )
95 Build.BuildContext.ADD_INIT_FUNCTION = ADD_INIT_FUNCTION
96
97
98 def generate_empty_file(task):
99     task.outputs[0].write('')
100     return 0
101
102 #################################################################
103 def SAMBA_LIBRARY(bld, libname, source,
104                   deps='',
105                   public_deps='',
106                   includes='',
107                   public_headers=None,
108                   public_headers_install=True,
109                   private_headers=None,
110                   header_path=None,
111                   pc_files=None,
112                   vnum=None,
113                   soname=None,
114                   cflags='',
115                   ldflags='',
116                   external_library=False,
117                   realname=None,
118                   keep_underscore=False,
119                   autoproto=None,
120                   autoproto_extra_source='',
121                   group='main',
122                   depends_on='',
123                   local_include=True,
124                   global_include=True,
125                   vars=None,
126                   subdir=None,
127                   install_path=None,
128                   install=True,
129                   pyembed=False,
130                   pyext=False,
131                   target_type='LIBRARY',
132                   bundled_extension=False,
133                   bundled_name=None,
134                   link_name=None,
135                   abi_directory=None,
136                   abi_match=None,
137                   hide_symbols=False,
138                   manpages=None,
139                   private_library=False,
140                   grouping_library=False,
141                   allow_undefined_symbols=False,
142                   allow_warnings=False,
143                   enabled=True):
144     '''define a Samba library'''
145
146     if pyembed and bld.env['IS_EXTRA_PYTHON']:
147         public_headers = None
148
149     if private_library and public_headers:
150         raise Utils.WafError("private library '%s' must not have public header files" %
151                              libname)
152
153     if LIB_MUST_BE_PRIVATE(bld, libname):
154         private_library = True
155
156     if not enabled:
157         SET_TARGET_TYPE(bld, libname, 'DISABLED')
158         return
159
160     source = bld.EXPAND_VARIABLES(source, vars=vars)
161     if subdir:
162         source = bld.SUBDIR(subdir, source)
163
164     # remember empty libraries, so we can strip the dependencies
165     if ((source == '') or (source == [])):
166         if deps == '' and public_deps == '':
167             SET_TARGET_TYPE(bld, libname, 'EMPTY')
168             return
169         empty_c = libname + '.empty.c'
170         bld.SAMBA_GENERATOR('%s_empty_c' % libname,
171                             rule=generate_empty_file,
172                             target=empty_c)
173         source=empty_c
174
175     if BUILTIN_LIBRARY(bld, libname):
176         obj_target = libname
177     else:
178         obj_target = libname + '.objlist'
179
180     if group == 'libraries':
181         subsystem_group = 'main'
182     else:
183         subsystem_group = group
184
185     # first create a target for building the object files for this library
186     # by separating in this way, we avoid recompiling the C files
187     # separately for the install library and the build library
188     bld.SAMBA_SUBSYSTEM(obj_target,
189                         source         = source,
190                         deps           = deps,
191                         public_deps    = public_deps,
192                         includes       = includes,
193                         public_headers = public_headers,
194                         public_headers_install = public_headers_install,
195                         private_headers= private_headers,
196                         header_path    = header_path,
197                         cflags         = cflags,
198                         group          = subsystem_group,
199                         autoproto      = autoproto,
200                         autoproto_extra_source=autoproto_extra_source,
201                         depends_on     = depends_on,
202                         hide_symbols   = hide_symbols,
203                         allow_warnings = allow_warnings,
204                         pyembed        = pyembed,
205                         pyext          = pyext,
206                         local_include  = local_include,
207                         global_include = global_include)
208
209     if BUILTIN_LIBRARY(bld, libname):
210         return
211
212     if not SET_TARGET_TYPE(bld, libname, target_type):
213         return
214
215     # the library itself will depend on that object target
216     deps += ' ' + public_deps
217     deps = TO_LIST(deps)
218     deps.append(obj_target)
219
220     realname = bld.map_shlib_extension(realname, python=(target_type=='PYTHON'))
221     link_name = bld.map_shlib_extension(link_name, python=(target_type=='PYTHON'))
222
223     # we don't want any public libraries without version numbers
224     if (not private_library and target_type != 'PYTHON' and not realname):
225         if vnum is None and soname is None:
226             raise Utils.WafError("public library '%s' must have a vnum" %
227                     libname)
228         if pc_files is None:
229             raise Utils.WafError("public library '%s' must have pkg-config file" %
230                        libname)
231         if public_headers is None and not bld.env['IS_EXTRA_PYTHON']:
232             raise Utils.WafError("public library '%s' must have header files" %
233                        libname)
234
235     if bundled_name is not None:
236         pass
237     elif target_type == 'PYTHON' or realname or not private_library:
238         if keep_underscore:
239             bundled_name = libname
240         else:
241             bundled_name = libname.replace('_', '-')
242     else:
243         assert (private_library == True and realname is None)
244         if abi_directory or vnum or soname:
245             bundled_extension=True
246         bundled_name = PRIVATE_NAME(bld, libname.replace('_', '-'),
247                                     bundled_extension, private_library)
248
249     ldflags = TO_LIST(ldflags)
250     if bld.env['ENABLE_RELRO'] is True:
251         ldflags.extend(TO_LIST('-Wl,-z,relro,-z,now'))
252
253     features = 'c cshlib symlink_lib install_lib'
254     if pyext:
255         features += ' pyext'
256     if pyembed:
257         features += ' pyembed'
258
259     if abi_directory:
260         features += ' abi_check'
261
262     if pyembed and bld.env['PYTHON_SO_ABI_FLAG']:
263         # For ABI checking, we don't care about the exact Python version.
264         # Replace the Python ABI tag (e.g. ".cpython-35m") by a generic ".py3"
265         abi_flag = bld.env['PYTHON_SO_ABI_FLAG']
266         replacement = '.py%s' % bld.env['PYTHON_VERSION'].split('.')[0]
267         version_libname = libname.replace(abi_flag, replacement)
268     else:
269         version_libname = libname
270
271     vscript = None
272     if bld.env.HAVE_LD_VERSION_SCRIPT:
273         if private_library:
274             version = "%s_%s" % (Utils.g_module.APPNAME, Utils.g_module.VERSION)
275         elif vnum:
276             version = "%s_%s" % (libname, vnum)
277         else:
278             version = None
279         if version:
280             vscript = "%s.vscript" % libname
281             bld.ABI_VSCRIPT(version_libname, abi_directory, version, vscript,
282                             abi_match)
283             fullname = apply_pattern(bundled_name, bld.env.shlib_PATTERN)
284             fullpath = bld.path.find_or_declare(fullname)
285             vscriptpath = bld.path.find_or_declare(vscript)
286             if not fullpath:
287                 raise Utils.WafError("unable to find fullpath for %s" % fullname)
288             if not vscriptpath:
289                 raise Utils.WafError("unable to find vscript path for %s" % vscript)
290             bld.add_manual_dependency(fullpath, vscriptpath)
291             if bld.is_install:
292                 # also make the .inst file depend on the vscript
293                 instname = apply_pattern(bundled_name + '.inst', bld.env.shlib_PATTERN)
294                 bld.add_manual_dependency(bld.path.find_or_declare(instname), bld.path.find_or_declare(vscript))
295             vscript = os.path.join(bld.path.abspath(bld.env), vscript)
296
297     bld.SET_BUILD_GROUP(group)
298     t = bld(
299         features        = features,
300         source          = [],
301         target          = bundled_name,
302         depends_on      = depends_on,
303         samba_ldflags   = ldflags,
304         samba_deps      = deps,
305         samba_includes  = includes,
306         version_script  = vscript,
307         version_libname = version_libname,
308         local_include   = local_include,
309         global_include  = global_include,
310         vnum            = vnum,
311         soname          = soname,
312         install_path    = None,
313         samba_inst_path = install_path,
314         name            = libname,
315         samba_realname  = realname,
316         samba_install   = install,
317         abi_directory   = "%s/%s" % (bld.path.abspath(), abi_directory),
318         abi_match       = abi_match,
319         private_library = private_library,
320         grouping_library=grouping_library,
321         allow_undefined_symbols=allow_undefined_symbols
322         )
323
324     if realname and not link_name:
325         link_name = 'shared/%s' % realname
326
327     if link_name:
328         t.link_name = link_name
329
330     if pc_files is not None and not private_library:
331         if pyembed and bld.env['IS_EXTRA_PYTHON']:
332             bld.PKG_CONFIG_FILES(pc_files, vnum=vnum, extra_name=bld.env['PYTHON_SO_ABI_FLAG'])
333         else:
334             bld.PKG_CONFIG_FILES(pc_files, vnum=vnum)
335
336     if (manpages is not None and 'XSLTPROC_MANPAGES' in bld.env and
337         bld.env['XSLTPROC_MANPAGES']):
338         bld.MANPAGES(manpages, install)
339
340
341 Build.BuildContext.SAMBA_LIBRARY = SAMBA_LIBRARY
342
343
344 #################################################################
345 def SAMBA_BINARY(bld, binname, source,
346                  deps='',
347                  includes='',
348                  public_headers=None,
349                  private_headers=None,
350                  header_path=None,
351                  modules=None,
352                  ldflags=None,
353                  cflags='',
354                  autoproto=None,
355                  use_hostcc=False,
356                  use_global_deps=True,
357                  compiler=None,
358                  group='main',
359                  manpages=None,
360                  local_include=True,
361                  global_include=True,
362                  subsystem_name=None,
363                  pyembed=False,
364                  vars=None,
365                  subdir=None,
366                  install=True,
367                  install_path=None,
368                  enabled=True):
369     '''define a Samba binary'''
370
371     if not enabled:
372         SET_TARGET_TYPE(bld, binname, 'DISABLED')
373         return
374
375     if not SET_TARGET_TYPE(bld, binname, 'BINARY'):
376         return
377
378     features = 'c cprogram symlink_bin install_bin'
379     if pyembed:
380         features += ' pyembed'
381
382     obj_target = binname + '.objlist'
383
384     source = bld.EXPAND_VARIABLES(source, vars=vars)
385     if subdir:
386         source = bld.SUBDIR(subdir, source)
387     source = unique_list(TO_LIST(source))
388
389     if group == 'binaries':
390         subsystem_group = 'main'
391     else:
392         subsystem_group = group
393
394     # only specify PIE flags for binaries
395     pie_cflags = cflags
396     pie_ldflags = TO_LIST(ldflags)
397     if bld.env['ENABLE_PIE'] is True:
398         pie_cflags += ' -fPIE'
399         pie_ldflags.extend(TO_LIST('-pie'))
400     if bld.env['ENABLE_RELRO'] is True:
401         pie_ldflags.extend(TO_LIST('-Wl,-z,relro,-z,now'))
402
403     # first create a target for building the object files for this binary
404     # by separating in this way, we avoid recompiling the C files
405     # separately for the install binary and the build binary
406     bld.SAMBA_SUBSYSTEM(obj_target,
407                         source         = source,
408                         deps           = deps,
409                         includes       = includes,
410                         cflags         = pie_cflags,
411                         group          = subsystem_group,
412                         autoproto      = autoproto,
413                         subsystem_name = subsystem_name,
414                         local_include  = local_include,
415                         global_include = global_include,
416                         use_hostcc     = use_hostcc,
417                         pyext          = pyembed,
418                         use_global_deps= use_global_deps)
419
420     bld.SET_BUILD_GROUP(group)
421
422     # the binary itself will depend on that object target
423     deps = TO_LIST(deps)
424     deps.append(obj_target)
425
426     t = bld(
427         features       = features,
428         source         = [],
429         target         = binname,
430         samba_deps     = deps,
431         samba_includes = includes,
432         local_include  = local_include,
433         global_include = global_include,
434         samba_modules  = modules,
435         top            = True,
436         samba_subsystem= subsystem_name,
437         install_path   = None,
438         samba_inst_path= install_path,
439         samba_install  = install,
440         samba_ldflags  = pie_ldflags
441         )
442
443     if manpages is not None and 'XSLTPROC_MANPAGES' in bld.env and bld.env['XSLTPROC_MANPAGES']:
444         bld.MANPAGES(manpages, install)
445
446 Build.BuildContext.SAMBA_BINARY = SAMBA_BINARY
447
448
449 #################################################################
450 def SAMBA_MODULE(bld, modname, source,
451                  deps='',
452                  includes='',
453                  subsystem=None,
454                  init_function=None,
455                  module_init_name='samba_init_module',
456                  autoproto=None,
457                  autoproto_extra_source='',
458                  cflags='',
459                  internal_module=True,
460                  local_include=True,
461                  global_include=True,
462                  vars=None,
463                  subdir=None,
464                  enabled=True,
465                  pyembed=False,
466                  manpages=None,
467                  allow_undefined_symbols=False,
468                  allow_warnings=False,
469                  install=True
470                  ):
471     '''define a Samba module.'''
472
473     bld.ASSERT(subsystem, "You must specify a subsystem for SAMBA_MODULE(%s)" % modname)
474
475     source = bld.EXPAND_VARIABLES(source, vars=vars)
476     if subdir:
477         source = bld.SUBDIR(subdir, source)
478
479     if internal_module or BUILTIN_LIBRARY(bld, modname):
480         # Do not create modules for disabled subsystems
481         if GET_TARGET_TYPE(bld, subsystem) == 'DISABLED':
482             return
483         bld.SAMBA_SUBSYSTEM(modname, source,
484                     deps=deps,
485                     includes=includes,
486                     autoproto=autoproto,
487                     autoproto_extra_source=autoproto_extra_source,
488                     cflags=cflags,
489                     local_include=local_include,
490                     global_include=global_include,
491                     allow_warnings=allow_warnings,
492                     enabled=enabled)
493
494         bld.ADD_INIT_FUNCTION(subsystem, modname, init_function)
495         return
496
497     if not enabled:
498         SET_TARGET_TYPE(bld, modname, 'DISABLED')
499         return
500
501     # Do not create modules for disabled subsystems
502     if GET_TARGET_TYPE(bld, subsystem) == 'DISABLED':
503         return
504
505     realname = modname
506     deps += ' ' + subsystem
507     while realname.startswith("lib"+subsystem+"_"):
508         realname = realname[len("lib"+subsystem+"_"):]
509     while realname.startswith(subsystem+"_"):
510         realname = realname[len(subsystem+"_"):]
511
512     build_name = "%s_module_%s" % (subsystem, realname)
513
514     realname = bld.make_libname(realname)
515     while realname.startswith("lib"):
516         realname = realname[len("lib"):]
517
518     build_link_name = "modules/%s/%s" % (subsystem, realname)
519
520     if init_function:
521         cflags += " -D%s=%s" % (init_function, module_init_name)
522
523     bld.SAMBA_LIBRARY(modname,
524                       source,
525                       deps=deps,
526                       includes=includes,
527                       cflags=cflags,
528                       realname = realname,
529                       autoproto = autoproto,
530                       local_include=local_include,
531                       global_include=global_include,
532                       vars=vars,
533                       bundled_name=build_name,
534                       link_name=build_link_name,
535                       install_path="${MODULESDIR}/%s" % subsystem,
536                       pyembed=pyembed,
537                       manpages=manpages,
538                       allow_undefined_symbols=allow_undefined_symbols,
539                       allow_warnings=allow_warnings,
540                       install=install
541                       )
542
543
544 Build.BuildContext.SAMBA_MODULE = SAMBA_MODULE
545
546
547 #################################################################
548 def SAMBA_SUBSYSTEM(bld, modname, source,
549                     deps='',
550                     public_deps='',
551                     includes='',
552                     public_headers=None,
553                     public_headers_install=True,
554                     private_headers=None,
555                     header_path=None,
556                     cflags='',
557                     cflags_end=None,
558                     group='main',
559                     init_function_sentinel=None,
560                     autoproto=None,
561                     autoproto_extra_source='',
562                     depends_on='',
563                     local_include=True,
564                     local_include_first=True,
565                     global_include=True,
566                     subsystem_name=None,
567                     enabled=True,
568                     use_hostcc=False,
569                     use_global_deps=True,
570                     vars=None,
571                     subdir=None,
572                     hide_symbols=False,
573                     allow_warnings=False,
574                     pyext=False,
575                     pyembed=False):
576     '''define a Samba subsystem'''
577
578     if not enabled:
579         SET_TARGET_TYPE(bld, modname, 'DISABLED')
580         return
581
582     # remember empty subsystems, so we can strip the dependencies
583     if ((source == '') or (source == [])):
584         if deps == '' and public_deps == '':
585             SET_TARGET_TYPE(bld, modname, 'EMPTY')
586             return
587         empty_c = modname + '.empty.c'
588         bld.SAMBA_GENERATOR('%s_empty_c' % modname,
589                             rule=generate_empty_file,
590                             target=empty_c)
591         source=empty_c
592
593     if not SET_TARGET_TYPE(bld, modname, 'SUBSYSTEM'):
594         return
595
596     source = bld.EXPAND_VARIABLES(source, vars=vars)
597     if subdir:
598         source = bld.SUBDIR(subdir, source)
599     source = unique_list(TO_LIST(source))
600
601     deps += ' ' + public_deps
602
603     bld.SET_BUILD_GROUP(group)
604
605     features = 'c'
606     if pyext:
607         features += ' pyext'
608     if pyembed:
609         features += ' pyembed'
610
611     t = bld(
612         features       = features,
613         source         = source,
614         target         = modname,
615         samba_cflags   = CURRENT_CFLAGS(bld, modname, cflags,
616                                         allow_warnings=allow_warnings,
617                                         hide_symbols=hide_symbols),
618         depends_on     = depends_on,
619         samba_deps     = TO_LIST(deps),
620         samba_includes = includes,
621         local_include  = local_include,
622         local_include_first  = local_include_first,
623         global_include = global_include,
624         samba_subsystem= subsystem_name,
625         samba_use_hostcc = use_hostcc,
626         samba_use_global_deps = use_global_deps,
627         )
628
629     if cflags_end is not None:
630         t.samba_cflags.extend(TO_LIST(cflags_end))
631
632     if autoproto is not None:
633         bld.SAMBA_AUTOPROTO(autoproto, source + TO_LIST(autoproto_extra_source))
634     if public_headers is not None:
635         bld.PUBLIC_HEADERS(public_headers, header_path=header_path,
636                            public_headers_install=public_headers_install)
637     return t
638
639
640 Build.BuildContext.SAMBA_SUBSYSTEM = SAMBA_SUBSYSTEM
641
642
643 def SAMBA_GENERATOR(bld, name, rule, source='', target='',
644                     group='generators', enabled=True,
645                     public_headers=None,
646                     public_headers_install=True,
647                     private_headers=None,
648                     header_path=None,
649                     vars=None,
650                     dep_vars=[],
651                     always=False):
652     '''A generic source generator target'''
653
654     if not SET_TARGET_TYPE(bld, name, 'GENERATOR'):
655         return
656
657     if not enabled:
658         return
659
660     dep_vars.append('ruledeps')
661     dep_vars.append('SAMBA_GENERATOR_VARS')
662
663     bld.SET_BUILD_GROUP(group)
664     t = bld(
665         rule=rule,
666         source=bld.EXPAND_VARIABLES(source, vars=vars),
667         target=target,
668         shell=isinstance(rule, str),
669         update_outputs=True,
670         before='cc',
671         ext_out='.c',
672         samba_type='GENERATOR',
673         dep_vars = dep_vars,
674         name=name)
675
676     if vars is None:
677         vars = {}
678     t.env.SAMBA_GENERATOR_VARS = vars
679
680     if always:
681         t.always = True
682
683     if public_headers is not None:
684         bld.PUBLIC_HEADERS(public_headers, header_path=header_path,
685                            public_headers_install=public_headers_install)
686     return t
687 Build.BuildContext.SAMBA_GENERATOR = SAMBA_GENERATOR
688
689
690
691 @Utils.run_once
692 def SETUP_BUILD_GROUPS(bld):
693     '''setup build groups used to ensure that the different build
694     phases happen consecutively'''
695     bld.p_ln = bld.srcnode # we do want to see all targets!
696     bld.env['USING_BUILD_GROUPS'] = True
697     bld.add_group('setup')
698     bld.add_group('build_compiler_source')
699     bld.add_group('vscripts')
700     bld.add_group('base_libraries')
701     bld.add_group('generators')
702     bld.add_group('compiler_prototypes')
703     bld.add_group('compiler_libraries')
704     bld.add_group('build_compilers')
705     bld.add_group('build_source')
706     bld.add_group('prototypes')
707     bld.add_group('headers')
708     bld.add_group('main')
709     bld.add_group('symbolcheck')
710     bld.add_group('syslibcheck')
711     bld.add_group('final')
712 Build.BuildContext.SETUP_BUILD_GROUPS = SETUP_BUILD_GROUPS
713
714
715 def SET_BUILD_GROUP(bld, group):
716     '''set the current build group'''
717     if not 'USING_BUILD_GROUPS' in bld.env:
718         return
719     bld.set_group(group)
720 Build.BuildContext.SET_BUILD_GROUP = SET_BUILD_GROUP
721
722
723
724 @conf
725 def ENABLE_TIMESTAMP_DEPENDENCIES(conf):
726     """use timestamps instead of file contents for deps
727     this currently doesn't work"""
728     def h_file(filename):
729         import stat
730         st = os.stat(filename)
731         if stat.S_ISDIR(st[stat.ST_MODE]): raise IOError('not a file')
732         m = Utils.md5()
733         m.update(str(st.st_mtime))
734         m.update(str(st.st_size))
735         m.update(filename)
736         return m.digest()
737     Utils.h_file = h_file
738
739
740 def SAMBA_SCRIPT(bld, name, pattern, installdir, installname=None):
741     '''used to copy scripts from the source tree into the build directory
742        for use by selftest'''
743
744     source = bld.path.ant_glob(pattern, flat=True)
745
746     bld.SET_BUILD_GROUP('build_source')
747     for s in TO_LIST(source):
748         iname = s
749         if installname is not None:
750             iname = installname
751         target = os.path.join(installdir, iname)
752         tgtdir = os.path.dirname(os.path.join(bld.srcnode.abspath(bld.env), '..', target))
753         mkdir_p(tgtdir)
754         link_src = os.path.normpath(os.path.join(bld.curdir, s))
755         link_dst = os.path.join(tgtdir, os.path.basename(iname))
756         if os.path.islink(link_dst) and os.readlink(link_dst) == link_src:
757             continue
758         if os.path.exists(link_dst):
759             os.unlink(link_dst)
760         Logs.info("symlink: %s -> %s/%s" % (s, installdir, iname))
761         os.symlink(link_src, link_dst)
762 Build.BuildContext.SAMBA_SCRIPT = SAMBA_SCRIPT
763
764
765 def copy_and_fix_python_path(task):
766     pattern='sys.path.insert(0, "bin/python")'
767     if task.env["PYTHONARCHDIR"] in sys.path and task.env["PYTHONDIR"] in sys.path:
768         replacement = ""
769     elif task.env["PYTHONARCHDIR"] == task.env["PYTHONDIR"]:
770         replacement="""sys.path.insert(0, "%s")""" % task.env["PYTHONDIR"]
771     else:
772         replacement="""sys.path.insert(0, "%s")
773 sys.path.insert(1, "%s")""" % (task.env["PYTHONARCHDIR"], task.env["PYTHONDIR"])
774
775     if task.env["PYTHON"][0] == "/":
776         replacement_shebang = "#!%s\n" % task.env["PYTHON"]
777     else:
778         replacement_shebang = "#!/usr/bin/env %s\n" % task.env["PYTHON"]
779
780     installed_location=task.outputs[0].bldpath(task.env)
781     source_file = open(task.inputs[0].srcpath(task.env))
782     installed_file = open(installed_location, 'w')
783     lineno = 0
784     for line in source_file:
785         newline = line
786         if (lineno == 0 and task.env["PYTHON_SPECIFIED"] is True and
787                 line[:2] == "#!"):
788             newline = replacement_shebang
789         elif pattern in line:
790             newline = line.replace(pattern, replacement)
791         installed_file.write(newline)
792         lineno = lineno + 1
793     installed_file.close()
794     os.chmod(installed_location, 0755)
795     return 0
796
797 def copy_and_fix_perl_path(task):
798     pattern='use lib "$RealBin/lib";'
799
800     replacement = ""
801     if not task.env["PERL_LIB_INSTALL_DIR"] in task.env["PERL_INC"]:
802          replacement = 'use lib "%s";' % task.env["PERL_LIB_INSTALL_DIR"]
803
804     if task.env["PERL"][0] == "/":
805         replacement_shebang = "#!%s\n" % task.env["PERL"]
806     else:
807         replacement_shebang = "#!/usr/bin/env %s\n" % task.env["PERL"]
808
809     installed_location=task.outputs[0].bldpath(task.env)
810     source_file = open(task.inputs[0].srcpath(task.env))
811     installed_file = open(installed_location, 'w')
812     lineno = 0
813     for line in source_file:
814         newline = line
815         if lineno == 0 and task.env["PERL_SPECIFIED"] == True and line[:2] == "#!":
816             newline = replacement_shebang
817         elif pattern in line:
818             newline = line.replace(pattern, replacement)
819         installed_file.write(newline)
820         lineno = lineno + 1
821     installed_file.close()
822     os.chmod(installed_location, 0755)
823     return 0
824
825
826 def install_file(bld, destdir, file, chmod=MODE_644, flat=False,
827                  python_fixup=False, perl_fixup=False,
828                  destname=None, base_name=None):
829     '''install a file'''
830     destdir = bld.EXPAND_VARIABLES(destdir)
831     if not destname:
832         destname = file
833         if flat:
834             destname = os.path.basename(destname)
835     dest = os.path.join(destdir, destname)
836     if python_fixup:
837         # fix the path python will use to find Samba modules
838         inst_file = file + '.inst'
839         bld.SAMBA_GENERATOR('python_%s' % destname,
840                             rule=copy_and_fix_python_path,
841                             dep_vars=["PYTHON","PYTHON_SPECIFIED","PYTHONDIR","PYTHONARCHDIR"],
842                             source=file,
843                             target=inst_file)
844         file = inst_file
845     if perl_fixup:
846         # fix the path perl will use to find Samba modules
847         inst_file = file + '.inst'
848         bld.SAMBA_GENERATOR('perl_%s' % destname,
849                             rule=copy_and_fix_perl_path,
850                             dep_vars=["PERL","PERL_SPECIFIED","PERL_LIB_INSTALL_DIR"],
851                             source=file,
852                             target=inst_file)
853         file = inst_file
854     if base_name:
855         file = os.path.join(base_name, file)
856     bld.install_as(dest, file, chmod=chmod)
857
858
859 def INSTALL_FILES(bld, destdir, files, chmod=MODE_644, flat=False,
860                   python_fixup=False, perl_fixup=False,
861                   destname=None, base_name=None):
862     '''install a set of files'''
863     for f in TO_LIST(files):
864         install_file(bld, destdir, f, chmod=chmod, flat=flat,
865                      python_fixup=python_fixup, perl_fixup=perl_fixup,
866                      destname=destname, base_name=base_name)
867 Build.BuildContext.INSTALL_FILES = INSTALL_FILES
868
869
870 def INSTALL_WILDCARD(bld, destdir, pattern, chmod=MODE_644, flat=False,
871                      python_fixup=False, exclude=None, trim_path=None):
872     '''install a set of files matching a wildcard pattern'''
873     files=TO_LIST(bld.path.ant_glob(pattern, flat=True))
874     if trim_path:
875         files2 = []
876         for f in files:
877             files2.append(os_path_relpath(f, trim_path))
878         files = files2
879
880     if exclude:
881         for f in files[:]:
882             if fnmatch.fnmatch(f, exclude):
883                 files.remove(f)
884     INSTALL_FILES(bld, destdir, files, chmod=chmod, flat=flat,
885                   python_fixup=python_fixup, base_name=trim_path)
886 Build.BuildContext.INSTALL_WILDCARD = INSTALL_WILDCARD
887
888
889 def INSTALL_DIRS(bld, destdir, dirs):
890     '''install a set of directories'''
891     destdir = bld.EXPAND_VARIABLES(destdir)
892     dirs = bld.EXPAND_VARIABLES(dirs)
893     for d in TO_LIST(dirs):
894         bld.install_dir(os.path.join(destdir, d))
895 Build.BuildContext.INSTALL_DIRS = INSTALL_DIRS
896
897
898 def MANPAGES(bld, manpages, install):
899     '''build and install manual pages'''
900     bld.env.MAN_XSL = 'http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl'
901     for m in manpages.split():
902         source = m + '.xml'
903         bld.SAMBA_GENERATOR(m,
904                             source=source,
905                             target=m,
906                             group='final',
907                             rule='${XSLTPROC} --xinclude -o ${TGT} --nonet ${MAN_XSL} ${SRC}'
908                             )
909         if install:
910             bld.INSTALL_FILES('${MANDIR}/man%s' % m[-1], m, flat=True)
911 Build.BuildContext.MANPAGES = MANPAGES
912
913 def SAMBAMANPAGES(bld, manpages, extra_source=None):
914     '''build and install manual pages'''
915     bld.env.SAMBA_EXPAND_XSL = bld.srcnode.abspath() + '/docs-xml/xslt/expand-sambadoc.xsl'
916     bld.env.SAMBA_MAN_XSL = bld.srcnode.abspath() + '/docs-xml/xslt/man.xsl'
917     bld.env.SAMBA_CATALOG = bld.srcnode.abspath() + '/bin/default/docs-xml/build/catalog.xml'
918     bld.env.SAMBA_CATALOGS = 'file:///etc/xml/catalog file:///usr/local/share/xml/catalog file://' + bld.env.SAMBA_CATALOG
919
920     for m in manpages.split():
921         source = m + '.xml'
922         if extra_source is not None:
923             source = [source, extra_source]
924         bld.SAMBA_GENERATOR(m,
925                             source=source,
926                             target=m,
927                             group='final',
928                             dep_vars=['SAMBA_MAN_XSL', 'SAMBA_EXPAND_XSL', 'SAMBA_CATALOG'],
929                             rule='''XML_CATALOG_FILES="${SAMBA_CATALOGS}"
930                                     export XML_CATALOG_FILES
931                                     ${XSLTPROC} --xinclude --stringparam noreference 0 -o ${TGT}.xml --nonet ${SAMBA_EXPAND_XSL} ${SRC[0].abspath(env)}
932                                     ${XSLTPROC} --nonet -o ${TGT} ${SAMBA_MAN_XSL} ${TGT}.xml'''
933                             )
934         bld.INSTALL_FILES('${MANDIR}/man%s' % m[-1], m, flat=True)
935 Build.BuildContext.SAMBAMANPAGES = SAMBAMANPAGES
936
937 #############################################################
938 # give a nicer display when building different types of files
939 def progress_display(self, msg, fname):
940     col1 = Logs.colors(self.color)
941     col2 = Logs.colors.NORMAL
942     total = self.position[1]
943     n = len(str(total))
944     fs = '[%%%dd/%%%dd] %s %%s%%s%%s\n' % (n, n, msg)
945     return fs % (self.position[0], self.position[1], col1, fname, col2)
946
947 def link_display(self):
948     if Options.options.progress_bar != 0:
949         return Task.Task.old_display(self)
950     fname = self.outputs[0].bldpath(self.env)
951     return progress_display(self, 'Linking', fname)
952 Task.TaskBase.classes['cc_link'].display = link_display
953
954 def samba_display(self):
955     if Options.options.progress_bar != 0:
956         return Task.Task.old_display(self)
957
958     targets    = LOCAL_CACHE(self, 'TARGET_TYPE')
959     if self.name in targets:
960         target_type = targets[self.name]
961         type_map = { 'GENERATOR' : 'Generating',
962                      'PROTOTYPE' : 'Generating'
963                      }
964         if target_type in type_map:
965             return progress_display(self, type_map[target_type], self.name)
966
967     if len(self.inputs) == 0:
968         return Task.Task.old_display(self)
969
970     fname = self.inputs[0].bldpath(self.env)
971     if fname[0:3] == '../':
972         fname = fname[3:]
973     ext_loc = fname.rfind('.')
974     if ext_loc == -1:
975         return Task.Task.old_display(self)
976     ext = fname[ext_loc:]
977
978     ext_map = { '.idl' : 'Compiling IDL',
979                 '.et'  : 'Compiling ERRTABLE',
980                 '.asn1': 'Compiling ASN1',
981                 '.c'   : 'Compiling' }
982     if ext in ext_map:
983         return progress_display(self, ext_map[ext], fname)
984     return Task.Task.old_display(self)
985
986 Task.TaskBase.classes['Task'].old_display = Task.TaskBase.classes['Task'].display
987 Task.TaskBase.classes['Task'].display = samba_display
988
989
990 @after('apply_link')
991 @feature('cshlib')
992 def apply_bundle_remove_dynamiclib_patch(self):
993     if self.env['MACBUNDLE'] or getattr(self,'mac_bundle',False):
994         if not getattr(self,'vnum',None):
995             try:
996                 self.env['LINKFLAGS'].remove('-dynamiclib')
997                 self.env['LINKFLAGS'].remove('-single_module')
998             except ValueError:
999                 pass