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