• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2
3import json
4import os
5import sys
6
7PRINT_ORIGINAL_FULL = False
8
9# This flags are augmented with flags added to the json files but not present in .gn or .gni files
10IGNORED_FLAGS = [
11    '-D_DEBUG',
12    '-Werror',
13    '-Xclang',
14    '-target-feature',
15    '+crc',
16    '+crypto',
17]
18IGNORED_DEFINES = [
19    'HAVE_ARM64_CRC32C=1'
20]
21DEFAULT_CFLAGS = [
22    '-DHAVE_ARM64_CRC32C=0',
23    '-DUSE_AURA=1',
24    '-DUSE_GLIB=1',
25    '-DUSE_NSS_CERTS=1',
26    '-DUSE_UDEV',
27    '-DUSE_X11=1',
28    '-DWEBRTC_ANDROID_PLATFORM_BUILD=1',
29    '-DWEBRTC_APM_DEBUG_DUMP=0',
30    '-D_FILE_OFFSET_BITS=64',
31    '-D_GNU_SOURCE',
32    '-D_LARGEFILE64_SOURCE',
33    '-D_LARGEFILE_SOURCE',
34    '-Wno-global-constructors',
35    '-Wno-implicit-const-int-float-conversion',
36    '-Wno-missing-field-initializers',
37    '-Wno-unreachable-code-aggressive',
38    '-Wno-unreachable-code-break',
39]
40
41DEFAULT_CFLAGS_BY_ARCH = {
42        'x86': ['-mavx2', '-mfma', '-msse2', '-msse3'],
43        'x64': ['-mavx2', '-mfma', '-msse2', '-msse3'],
44        'arm': ['-mthumb'],
45        'arm64': [],
46        'riscv64': [],
47        }
48
49FLAGS = ['cflags', 'cflags_c', 'cflags_cc', 'asmflags']
50FLAG_NAME_MAP = {
51    'cflags': 'cflags',
52    'asmflags': 'asflags',
53    'cflags_cc': 'cppflags',
54    'cflags_c': 'conlyflags',
55}
56
57ARCH_NAME_MAP = {n: n for n in DEFAULT_CFLAGS_BY_ARCH.keys()}
58ARCH_NAME_MAP['x64'] = 'x86_64'
59
60ARCHS = sorted(ARCH_NAME_MAP.keys())
61
62def FormatList(l):
63    return json.dumps(sorted(list(l)))
64
65def IsInclude(name):
66    return name.endswith('.h') or name.endswith('.inc')
67
68def FilterIncludes(l):
69    return filter(lambda x: not IsInclude(x), l)
70
71def PrintOrigin(target):
72    print('/* From target:')
73    if PRINT_ORIGINAL_FULL:
74        print(json.dumps(target, sort_keys = True, indent = 4))
75    else:
76        print(target['original_name'])
77    print('*/')
78
79def MakeRelatives(l):
80    return map(lambda x: x.split('//').pop(), l)
81
82def FormatName(name):
83    return 'webrtc_' + name.split('/').pop().replace(':', '__')
84
85def FormatNames(target):
86    target['original_name'] = target['name']
87    target['name'] = FormatName(target['name'])
88    target['deps'] = sorted([FormatName(d) for d in target['deps']])
89    return target
90
91def FilterFlags(flags, to_skip = set()):
92    skipped_opts = set(IGNORED_FLAGS).union(to_skip)
93    return [x for x in flags if not any([x.startswith(y) for y in skipped_opts])]
94
95def PrintHeader():
96    print('package {')
97    print('    default_applicable_licenses: ["external_webrtc_license"],')
98    print('}')
99    print('')
100    print('// Added automatically by a large-scale-change that took the approach of')
101    print('// \'apply every license found to every target\'. While this makes sure we respect')
102    print('// every license restriction, it may not be entirely correct.')
103    print('//')
104    print('// e.g. GPL in an MIT project might only apply to the contrib/ directory.')
105    print('//')
106    print('// Please consider splitting the single license below into multiple licenses,')
107    print('// taking care not to lose any license_kind information, and overriding the')
108    print('// default license using the \'licenses: [...]\' property on targets as needed.')
109    print('//')
110    print('// For unused files, consider creating a \'fileGroup\' with "//visibility:private"')
111    print('// to attach the license to, and including a comment whether the files may be')
112    print('// used in the current project.')
113    print('//')
114    print('// large-scale-change included anything that looked like it might be a license')
115    print('// text as a license_text. e.g. LICENSE, NOTICE, COPYING etc.')
116    print('//')
117    print('// Please consider removing redundant or irrelevant files from \'license_text:\'.')
118    print('// See: http://go/android-license-faq')
119    print('')
120    print('///////////////////////////////////////////////////////////////////////////////')
121    print('// Do not edit this file directly, it\'s automatically generated by a script. //')
122    print('// Modify android_tools/generate_android_bp.py and run that instead.         //')
123    print('///////////////////////////////////////////////////////////////////////////////')
124    print('')
125    print('license {')
126    print('    name: "external_webrtc_license",')
127    print('    visibility: [":__subpackages__"],')
128    print('    license_kinds: [')
129    print('        "SPDX-license-identifier-Apache-2.0",')
130    print('        "SPDX-license-identifier-BSD",')
131    print('        "SPDX-license-identifier-MIT",')
132    print('        "SPDX-license-identifier-Zlib",')
133    print('        "legacy_notice",')
134    print('        "legacy_unencumbered",')
135    print('    ],')
136    print('    license_text: [')
137    print('        "LICENSE",')
138    print('        "PATENTS",')
139    print('        "license_template.txt",')
140    print('    ],')
141    print('}')
142
143
144
145def GatherDefaultFlags(targets_by_arch):
146    # Iterate through all of the targets for each architecture collecting the flags that
147    # are the same for all targets in that architecture.  Use a list instead of a set
148    # to maintain the flag ordering, which may be significant (e.g. -Wno-shadow has to
149    # come after -Wshadow).
150    arch_default_flags = {}
151    for arch, targets in targets_by_arch.items():
152        arch_default_flags[arch] = {}
153        for target in targets.values():
154            typ = target['type']
155            if typ != 'static_library':
156                continue
157            for flag_type in FLAGS:
158                if not flag_type in arch_default_flags:
159                    arch_default_flags[arch][flag_type] = target[flag_type]
160                else:
161                    target_flags = set(target[flag_type])
162                    flags = arch_default_flags[arch][flag_type]
163                    flags[:]  = [ x for x in flags if x in target_flags ]
164        for flag_type, flags in arch_default_flags[arch].items():
165            arch_default_flags[arch][flag_type] = FilterFlags(flags)
166        # Add in the hardcoded extra default cflags
167        arch_default_flags[arch]['cflags'] += DEFAULT_CFLAGS_BY_ARCH.get(arch, [])
168
169    # Iterate through all of the architectures collecting the flags that are the same
170    # for all targets in all architectures.
171    default_flags = {}
172    for arch, flagset in arch_default_flags.items():
173        for flag_type, arch_flags in flagset.items():
174            if not flag_type in default_flags:
175                default_flags[flag_type] = arch_flags.copy()
176            else:
177                flags = default_flags[flag_type]
178                flags[:] = [ x for x in flags if x in arch_flags ]
179    # Add in the hardcoded extra default cflags
180    default_flags['cflags'] += DEFAULT_CFLAGS
181
182    # Remove the global default flags from the per-architecture default flags
183    for arch, flagset in arch_default_flags.items():
184        for flag_type in flagset.keys():
185            flags = flagset[flag_type]
186            flags[:] = [ x for x in flags if x not in default_flags[flag_type] ]
187
188    default_flags['arch'] = arch_default_flags
189    return default_flags
190
191def GenerateDefault(targets_by_arch):
192    in_default = GatherDefaultFlags(targets_by_arch)
193    print('cc_defaults {')
194    print('    name: "webrtc_defaults",')
195    print('    local_include_dirs: [')
196    print('      ".",')
197    print('      "webrtc",')
198    print('      "third_party/crc32c/src/include",')
199    print('    ],')
200    for typ in sorted(in_default.keys() - {'arch'}):
201        flags = in_default[typ]
202        if len(flags) > 0:
203            print('    {0}: ['.format(FLAG_NAME_MAP[typ]))
204            for flag in flags:
205                print('        "{0}",'.format(flag.replace('"', '\\"')))
206            print('    ],')
207    print('    header_libs: [')
208    print('      "libwebrtc_absl_headers",')
209    print('    ],')
210    print('    static_libs: [')
211    print('        "libaom",')
212    print('        "libevent",')
213    print('        "libopus",')
214    print('        "libsrtp2",')
215    print('        "libvpx",')
216    print('        "libyuv",')
217    print('        "libpffft",')
218    print('        "rnnoise_rnn_vad",')
219    print('    ],')
220    print('    shared_libs: [')
221    print('        "libcrypto",')
222    print('        "libprotobuf-cpp-full",')
223    print('        "libprotobuf-cpp-lite",')
224    print('        "libssl",')
225    print('    ],')
226    print('    host_supported: true,')
227    print('    // vendor needed for libpreprocessing effects.')
228    print('    vendor: true,')
229    print('    target: {')
230    print('        darwin: {')
231    print('            enabled: false,')
232    print('        },')
233    print('    },')
234    print('    arch: {')
235    for a in ARCHS:
236        print('        {0}: {{'.format(ARCH_NAME_MAP[a]))
237        for typ in FLAGS:
238            flags = in_default['arch'].get(a, {}).get(typ, [])
239            if len(flags) > 0:
240                print('            {0}: ['.format(FLAG_NAME_MAP[typ]))
241                for flag in flags:
242                    print('                "{0}",'.format(flag.replace('"', '\\"')))
243                print('            ],')
244        print('        },')
245    print('    },')
246    print('    visibility: [')
247    print('        "//frameworks/av/media/libeffects/preprocessing:__subpackages__",')
248    print('        "//device/google/cuttlefish/host/frontend/webrtc:__subpackages__",')
249    print('    ],')
250    print('}')
251
252    # The flags in the default entry can be safely removed from the targets
253    for arch, targets in targets_by_arch.items():
254        for flag_type in FLAGS:
255            default_flags = set(in_default[flag_type]) | set(in_default['arch'][arch][flag_type])
256            for target in targets.values():
257                target[flag_type] = FilterFlags(target.get(flag_type, []), default_flags)
258                if len(target[flag_type]) == 0:
259                    target.pop(flag_type)
260
261    return in_default
262
263
264def TransitiveDependencies(name, dep_type, targets):
265    target = targets[name]
266    field = 'transitive_' + dep_type
267    if field in target.keys():
268        return target[field]
269    target[field] = {'global': set()}
270    for a in ARCHS:
271        target[field][a] = set()
272    if target['type'] == dep_type:
273        target[field]['global'].add(name)
274    for d in target.get('deps', []):
275        if targets[d]['type'] == dep_type:
276            target[field]['global'].add(d)
277        tDeps = TransitiveDependencies(d, dep_type, targets)
278        target[field]['global'] |= tDeps['global']
279        for a in ARCHS:
280            target[field][a] |= tDeps[a]
281    if 'arch' in target:
282        for a, x in target['arch'].items():
283            for d in x.get('deps', []):
284                tDeps = TransitiveDependencies(d, dep_type, targets)
285                target[field][a] |= tDeps['global'] | tDeps[a]
286            target[field][a] -= target[field]['global']
287
288    return target[field]
289
290def GenerateGroup(target):
291    # PrintOrigin(target)
292    pass
293
294def GenerateStaticLib(target, targets):
295    PrintOrigin(target)
296    name = target['name']
297    print('cc_library_static {')
298    print('    name: "{0}",'.format(name))
299    print('    defaults: ["webrtc_defaults"],')
300    sources = target.get('sources', [])
301    print('    srcs: {0},'.format(FormatList(sources)))
302    print('    host_supported: true,')
303    if 'asmflags' in target.keys():
304        asmflags = target['asmflags']
305        if len(asmflags) > 0:
306            print('    asflags: {0},'.format(FormatList(asmflags)))
307    if 'cflags' in target.keys():
308        cflags = target['cflags']
309        print('    cflags: {0},'.format(FormatList(cflags)))
310    if 'cflags_c' in target.keys():
311        cflags_c = target['cflags_c']
312        if len(cflags_c) > 0:
313            print('    conlyflags: {0},'.format(FormatList(cflags_c)))
314    if 'cflags_cc' in target.keys():
315        cflags_cc = target['cflags_cc']
316        if len(cflags_cc) > 0:
317            print('    cppflags: {0},'.format(FormatList(cflags_cc)))
318    if 'arch' in target:
319        print('   arch: {')
320        for arch_name in ARCHS:
321            if arch_name not in target['arch'].keys():
322                continue
323            arch = target['arch'][arch_name]
324            print('       ' + ARCH_NAME_MAP[arch_name] + ': {')
325            if 'cflags' in arch.keys():
326                cflags = arch['cflags']
327                print('            cflags: {0},'.format(FormatList(cflags)))
328            if 'cflags_c' in arch.keys():
329                cflags_c = arch['cflags_c']
330                if len(cflags_c) > 0:
331                    print('            conlyflags: {0},'.format(FormatList(cflags_c)))
332            if 'cflags_cc' in arch.keys():
333                cflags_cc = arch['cflags_cc']
334                if len(cflags_cc) > 0:
335                    print('            cppflags: {0},'.format(FormatList(cflags_cc)))
336            if 'sources' in arch:
337                  sources = arch['sources']
338                  print('            srcs: {0},'.format(FormatList(sources)))
339            if 'enabled' in arch:
340                print('            enabled: {0},'.format(arch['enabled']))
341            print('        },')
342        print('   },')
343    print('}')
344    return name
345
346def DFS(seed, targets):
347    visited = set()
348    stack = [seed]
349    while len(stack) > 0:
350        nxt = stack.pop()
351        if nxt in visited:
352            continue
353        visited.add(nxt)
354        stack += targets[nxt]['deps']
355        if 'arch' not in targets[nxt]:
356            continue
357        for arch in targets[nxt]['arch']:
358            if 'deps' in arch:
359                stack += arch['deps']
360    return visited
361
362def Preprocess(project):
363    targets = {}
364    for name, target in project['targets'].items():
365        target['name'] = name
366        targets[name] = target
367        if target['type'] == 'shared_library':
368            # Don't bother creating shared libraries
369            target['type'] = 'static_library'
370        if target['type'] == 'source_set':
371            # Convert source_sets to static libraires to avoid recompiling sources multiple times.
372            target['type'] = 'static_library'
373        if 'defines' in target:
374            target['cflags'] = target.get('cflags', []) + ['-D{0}'.format(d) for d in target['defines'] if d not in IGNORED_DEFINES]
375            target.pop('defines')
376        if 'sources' not in target:
377            continue
378        sources = list(MakeRelatives(FilterIncludes(target['sources'])))
379        if len(sources) > 0:
380            target['sources'] = sources
381        else:
382            target.pop('sources')
383
384    # These dependencies are provided by aosp
385    ignored_targets = {
386            '//third_party/libaom:libaom',
387            '//third_party/libevent:libevent',
388            '//third_party/opus:opus',
389            '//third_party/libsrtp:libsrtp',
390            '//third_party/libvpx:libvpx',
391            '//third_party/libyuv:libyuv',
392            '//third_party/pffft:pffft',
393            '//third_party/rnnoise:rnn_vad',
394            '//third_party/boringssl:boringssl',
395            '//third_party/android_ndk:cpu_features',
396            '//buildtools/third_party/libunwind:libunwind',
397            '//buildtools/third_party/libc++:libc++',
398        }
399    for name, target in targets.items():
400        # Skip all "action" targets
401        if target['type'] in {'action', 'action_foreach'}:
402            ignored_targets.add(name)
403    targets = {name: target for name, target in targets.items() if name not in ignored_targets}
404
405    for target in targets.values():
406        # Don't depend on ignored targets
407        target['deps'] = [d for d in target['deps'] if d not in ignored_targets]
408
409    # Ignore empty static libraries
410    empty_libs = set()
411    for name, target in targets.items():
412        if target['type'] == 'static_library' and 'sources' not in target and name != '//:webrtc':
413            empty_libs.add(name)
414    for empty_lib in empty_libs:
415        empty_lib_deps = targets[empty_lib].get('deps', [])
416        for target in targets.values():
417            target['deps'] = FlattenEmptyLibs(target['deps'], empty_lib, empty_lib_deps)
418    for s in empty_libs:
419        targets.pop(s)
420
421    # Select libwebrtc, libaudio_processing and its dependencies
422    selected = set()
423    selected |= DFS('//:webrtc', targets)
424    selected |= DFS('//modules/audio_processing:audio_processing', targets)
425
426    return {FormatName(n): FormatNames(targets[n]) for n in selected}
427
428def _FlattenEmptyLibs(deps, empty_lib, empty_lib_deps):
429    for x in deps:
430        if x == empty_lib:
431            yield from empty_lib_deps
432        else:
433            yield x
434
435def FlattenEmptyLibs(deps, empty_lib, empty_lib_deps):
436    return list(_FlattenEmptyLibs(deps, empty_lib, empty_lib_deps))
437
438def NonNoneFrom(l):
439    for a in l:
440        if a is not None:
441            return a
442    return None
443
444def MergeListField(target, f, target_by_arch):
445    set_by_arch = {}
446    for a, t in target_by_arch.items():
447        if len(t) == 0:
448            # We only care about enabled archs
449            continue
450        set_by_arch[a] = set(t.get(f, []))
451
452    union = set()
453    for _, s in set_by_arch.items():
454        union |= s
455
456    common = union
457    for a, s in set_by_arch.items():
458        common &= s
459
460    not_common = {a: s - common for a,s in set_by_arch.items()}
461
462    if len(common) > 0:
463        target[f] = list(common)
464    for a, s in not_common.items():
465        if len(s) > 0:
466            target['arch'][a][f] = sorted(list(s))
467
468def Merge(target_by_arch):
469    # The new target shouldn't have the transitive dependencies memoization fields
470    # or have the union of those fields from all 4 input targets.
471    target = {}
472    for f in ['original_name', 'name', 'type']:
473        target[f] = NonNoneFrom([t.get(f) for _,t in target_by_arch.items()])
474
475    target['arch'] = {}
476    for a, t in target_by_arch.items():
477        target['arch'][a] = {}
478        if len(t) == 0:
479            target['arch'][a]['enabled'] = 'false'
480
481    list_fields = ['sources',
482                   'deps',
483                   'cflags',
484                   'cflags_c',
485                   'cflags_cc',
486                   'asmflags']
487    for lf in list_fields:
488        MergeListField(target, lf, target_by_arch)
489
490    # Static libraries should be depended on at the root level and disabled for
491    # the corresponding architectures.
492    for arch in target['arch'].values():
493        if 'deps' not in arch:
494            continue
495        deps = arch['deps']
496        if 'deps' not in target:
497            target['deps'] = []
498        target['deps'] += deps
499        arch.pop('deps')
500    if 'deps' in target:
501        target['deps'] = sorted(target['deps'])
502
503    # Remove empty sets
504    for a in ARCHS:
505        if len(target['arch'][a]) == 0:
506            target['arch'].pop(a)
507    if len(target['arch']) == 0:
508        target.pop('arch')
509
510    return target
511
512def DisabledArchs4Target(target):
513    ret = set()
514    for a in ARCHS:
515        if a not in target.get('arch', {}):
516            continue
517        if target['arch'][a].get('enabled', 'true') == 'false':
518            ret.add(a)
519    return ret
520
521
522def HandleDisabledArchs(targets):
523    for n, t in targets.items():
524        if 'arch' not in t:
525            continue
526        disabledArchs = DisabledArchs4Target(t)
527        if len(disabledArchs) == 0:
528            continue
529        # Fix targets that depend on this one
530        for t in targets.values():
531            if DisabledArchs4Target(t) == disabledArchs:
532                # With the same disabled archs there is no need to move dependencies
533                continue
534            if 'deps' in t and n in t['deps']:
535                # Remove the dependency from the high level list
536                t['deps'] = sorted(set(t['deps']) - {n})
537                if 'arch' not in t:
538                    t['arch'] = {}
539                for a in ARCHS:
540                    if a in disabledArchs:
541                        continue
542                    if a not in t['arch']:
543                        t['arch'][a] = {}
544                    if 'deps' not in t['arch'][a]:
545                        t['arch'][a]['deps'] = []
546                    t['arch'][a]['deps'] += [n]
547
548def MergeAll(targets_by_arch):
549    names = set()
550    for t in targets_by_arch.values():
551        names |= t.keys()
552    targets = {}
553    for name in names:
554        targets[name] = Merge({a: t.get(name, {}) for a,t in targets_by_arch.items()})
555
556    HandleDisabledArchs(targets)
557
558    return targets
559
560def GatherAllFlags(obj):
561    if type(obj) != type({}):
562        # not a dictionary
563        return set()
564    ret = set()
565    for f in FLAGS:
566        ret |= set(obj.get(f, []))
567    for v in obj.values():
568        ret |= GatherAllFlags(v)
569    return ret
570
571def FilterFlagsInUse(flags, directory):
572    unused = []
573    for f in flags:
574        nf = f
575        if nf.startswith("-D"):
576            nf = nf[2:]
577            i = nf.find('=')
578            if i > 0:
579                nf = nf[:i]
580        c = os.system(f"find {directory} -name '*.gn*' | xargs grep -q -s -e '{nf}'")
581        if c != 0:
582            # couldn't find the flag in *.gn or *.gni
583            unused.append(f)
584    return unused
585
586if len(sys.argv) != 2:
587    print('wrong number of arguments', file = sys.stderr)
588    exit(1)
589
590dir = sys.argv[1]
591
592targets_by_arch = {}
593flags = set()
594for arch in ARCHS:
595    path = "{0}/project_{1}.json".format(dir, arch)
596    json_file = open(path, 'r')
597    targets_by_arch[arch] = Preprocess(json.load(json_file))
598    flags |= GatherAllFlags(targets_by_arch[arch])
599
600unusedFlags = FilterFlagsInUse(flags, f"{dir}/..")
601IGNORED_FLAGS = sorted(set(IGNORED_FLAGS) | set(unusedFlags))
602
603PrintHeader()
604
605GenerateDefault(targets_by_arch)
606
607targets = MergeAll(targets_by_arch)
608
609print('\n\n')
610
611for name, target in sorted(targets.items()):
612    typ = target['type']
613    if typ == 'static_library':
614        GenerateStaticLib(target, targets)
615    elif typ == 'group':
616        GenerateGroup(target)
617    else:
618        print('Unknown type: {0} ({1})'.format(typ, target['name']), file = sys.stderr)
619        exit(1)
620    print('\n\n')
621
622webrtc_libs = TransitiveDependencies(FormatName('//:webrtc'), 'static_library', targets)
623print('cc_library_static {')
624print('    name: "libwebrtc",')
625print('    defaults: ["webrtc_defaults"],')
626print('    export_include_dirs: ["."],')
627print('    whole_static_libs: {0},'.format(FormatList(sorted(webrtc_libs['global']) + ['libpffft', 'rnnoise_rnn_vad'])))
628print('    arch: {')
629for a in ARCHS:
630    if len(webrtc_libs[a]) > 0:
631        print('        {0}: {{'.format(ARCH_NAME_MAP[a]))
632        print('            whole_static_libs: {0},'.format(FormatList(sorted(webrtc_libs[a]))))
633        print('        },')
634print('    },')
635print('}')
636
637print('\n\n')
638
639audio_proc_libs = TransitiveDependencies(FormatName('//modules/audio_processing:audio_processing'), 'static_library', targets)
640print('cc_library_static {')
641print('    name: "webrtc_audio_processing",')
642print('    defaults: ["webrtc_defaults"],')
643print('    export_include_dirs: [')
644print('        ".",')
645print('        "modules/include",')
646print('        "modules/audio_processing/include",')
647print('    ],')
648print('    whole_static_libs: {0},'.format(FormatList(sorted(audio_proc_libs['global']) + ['libpffft', 'rnnoise_rnn_vad'])))
649print('    arch: {')
650for a in ARCHS:
651    if len(audio_proc_libs[a]) > 0:
652        print('        {0}: {{'.format(ARCH_NAME_MAP[a]))
653        print('            whole_static_libs: {0},'.format(FormatList(sorted(audio_proc_libs[a]))))
654        print('        },')
655print('    },')
656print('}')
657