From 49d363c487b19adf428f98295d4b205f13987a3d Mon Sep 17 00:00:00 2001 From: yayaws_zk <584363327@qq.com> Date: Sat, 6 Sep 2025 12:34:06 +0800 Subject: [PATCH 1/3] add huawei change --- aosp/art/dex2oat/Android.bp | 303 ++ aosp/art/dexoptanalyzer/Android.bp | 64 + aosp/art/patchoat/Android.bp | 64 + aosp/art/profman/Android.bp | 65 + aosp/art/tools/hiddenapi/Android.bp | 66 + aosp/bionic/libc/seccomp/Android.bp | 35 + aosp/bionic/libc/system_properties/Android.bp | 30 + aosp/bootable/recovery/minui/Android.mk | 88 + aosp/build/make/core/Makefile | 3305 +++++++++++++++++ aosp/build/make/core/main.mk | 1294 +++++++ aosp/build/make/core/product.mk | 359 ++ aosp/build/make/core/product_config.mk | 507 +++ aosp/build/make/core/soong_config.mk | 177 + aosp/build/make/core/version_defaults.mk | 301 ++ aosp/build/make/target/product/core_base.mk | 66 + aosp/build/make/target/product/embedded.mk | 120 + .../target/product/generic_no_telephony.mk | 77 + aosp/build/make/tools/buildinfo.sh | 64 + aosp/build/soong/android/variable.go | 425 +++ aosp/create_monbox_package.sh | 45 + aosp/device/generic/goldfish/audio/Android.mk | 58 + .../device/generic/goldfish/camera/Android.mk | 129 + aosp/external/drm_gralloc/Android.mk | 183 + aosp/external/libdrm/Android.bp | 65 + aosp/external/libdrm/amdgpu/Android.bp | 11 + aosp/external/libdrm/radeon/Android.bp | 11 + aosp/external/libjpeg-turbo/Android.bp | 235 ++ aosp/external/libopus/Android.bp | 331 ++ aosp/external/mesa3d/src/egl/Android.mk | 75 + .../mesa3d/src/gallium/targets/dri/Android.mk | 124 + aosp/external/mesa3d/src/gbm/Android.mk | 43 + aosp/external/mesa3d/src/mapi/Android.mk | 78 + aosp/external/mtpd/Android.bp | 34 + aosp/external/noto-fonts/Android.mk | 348 ++ aosp/external/ppp/pppd/Android.mk | 46 + aosp/external/toybox/Android.mk | 4 +- .../akm/AK8975_FS/libsensors/Android.mk | 45 + .../res/values-zh-rCN/values-zh-rCN.xml | 7 + aosp/system/bt/main/Android.bp | 123 + aosp/system/core/bootstat/Android.bp | 97 + aosp/system/core/debuggerd/crasher/Android.bp | 84 + aosp/system/core/fastboot/Android.mk | 127 + aosp/system/core/init/Android.bp | 258 ++ aosp/system/core/init/Android.mk | 93 + aosp/system/core/init/prepare_filesystem.cpp | 71 + aosp/system/core/libprocessgroup/Android.bp | 13 + aosp/system/core/libsuspend/Android.bp | 27 + aosp/system/core/lmkd/Android.bp | 51 + aosp/system/core/logd/Android.bp | 78 + aosp/system/core/reboot/Android.bp | 11 + .../rootdir/etc/public.libraries.android.txt | 27 + aosp/system/core/rootdir/init.environ.rc.in | 14 + aosp/system/core/rootdir/init.rc | 911 +++++ aosp/system/core/rootdir/init.usb.configfs.rc | 140 + aosp/system/core/rootdir/init.usb.rc | 136 + aosp/system/core/rootdir/init.zygote32.rc | 14 + aosp/system/core/rootdir/init.zygote32_64.rc | 23 + aosp/system/core/rootdir/init.zygote64.rc | 14 + aosp/system/core/rootdir/init.zygote64_32.rc | 23 + aosp/system/core/rootdir/ueventd.rc | 141 + aosp/system/core/storaged/storaged.rc | 8 + aosp/system/hwservicemanager/Android.bp | 47 + aosp/system/libhidl/vintfdata/manifest.xml | 152 + aosp/system/libhwbinder/Android.bp | 108 + aosp/system/netd/server/Android.mk | 234 ++ aosp/system/security/keystore/Android.bp | 290 ++ .../api/26.0/private/service_contexts | 176 + .../27.0/private/compat/26.0/26.0.ignore.cil | 34 + .../api/27.0/private/service_contexts | 177 + .../api/28.0/private/app_neverallows.te | 263 ++ .../28.0/private/compat/26.0/26.0.ignore.cil | 158 + .../28.0/private/compat/27.0/27.0.ignore.cil | 132 + .../prebuilts/api/28.0/private/file_contexts | 560 +++ .../api/28.0/private/service_contexts | 191 + .../prebuilts/api/28.0/public/domain.te | 1403 +++++++ .../prebuilts/api/28.0/public/file.te | 419 +++ .../prebuilts/api/28.0/public/te_macros | 597 +++ .../sepolicy/private/app_neverallows.te | 263 ++ .../private/compat/26.0/26.0.ignore.cil | 158 + .../private/compat/27.0/27.0.ignore.cil | 132 + aosp/system/sepolicy/private/file_contexts | 560 +++ aosp/system/sepolicy/private/service_contexts | 191 + aosp/system/sepolicy/public/domain.te | 1403 +++++++ aosp/system/sepolicy/public/file.te | 419 +++ aosp/system/sepolicy/public/te_macros | 597 +++ 85 files changed, 20428 insertions(+), 2 deletions(-) create mode 100644 aosp/art/dex2oat/Android.bp create mode 100644 aosp/art/dexoptanalyzer/Android.bp create mode 100644 aosp/art/patchoat/Android.bp create mode 100644 aosp/art/profman/Android.bp create mode 100644 aosp/art/tools/hiddenapi/Android.bp create mode 100644 aosp/bionic/libc/seccomp/Android.bp create mode 100644 aosp/bionic/libc/system_properties/Android.bp create mode 100644 aosp/bootable/recovery/minui/Android.mk create mode 100644 aosp/build/make/core/Makefile create mode 100644 aosp/build/make/core/main.mk create mode 100644 aosp/build/make/core/product.mk create mode 100644 aosp/build/make/core/product_config.mk create mode 100644 aosp/build/make/core/soong_config.mk create mode 100644 aosp/build/make/core/version_defaults.mk create mode 100644 aosp/build/make/target/product/core_base.mk create mode 100644 aosp/build/make/target/product/embedded.mk create mode 100644 aosp/build/make/target/product/generic_no_telephony.mk create mode 100755 aosp/build/make/tools/buildinfo.sh create mode 100644 aosp/build/soong/android/variable.go create mode 100755 aosp/create_monbox_package.sh create mode 100644 aosp/device/generic/goldfish/audio/Android.mk create mode 100644 aosp/device/generic/goldfish/camera/Android.mk create mode 100644 aosp/external/drm_gralloc/Android.mk create mode 100644 aosp/external/libdrm/Android.bp create mode 100644 aosp/external/libdrm/amdgpu/Android.bp create mode 100644 aosp/external/libdrm/radeon/Android.bp create mode 100644 aosp/external/libjpeg-turbo/Android.bp create mode 100644 aosp/external/libopus/Android.bp create mode 100644 aosp/external/mesa3d/src/egl/Android.mk create mode 100644 aosp/external/mesa3d/src/gallium/targets/dri/Android.mk create mode 100644 aosp/external/mesa3d/src/gbm/Android.mk create mode 100644 aosp/external/mesa3d/src/mapi/Android.mk create mode 100644 aosp/external/mtpd/Android.bp create mode 100644 aosp/external/noto-fonts/Android.mk create mode 100644 aosp/external/ppp/pppd/Android.mk create mode 100644 aosp/hardware/akm/AK8975_FS/libsensors/Android.mk create mode 100644 aosp/prebuilts/sdk/current/support/v7/preference/res/values-zh-rCN/values-zh-rCN.xml create mode 100644 aosp/system/bt/main/Android.bp create mode 100644 aosp/system/core/bootstat/Android.bp create mode 100644 aosp/system/core/debuggerd/crasher/Android.bp create mode 100644 aosp/system/core/fastboot/Android.mk create mode 100644 aosp/system/core/init/Android.bp create mode 100644 aosp/system/core/init/Android.mk create mode 100644 aosp/system/core/init/prepare_filesystem.cpp create mode 100644 aosp/system/core/libprocessgroup/Android.bp create mode 100644 aosp/system/core/libsuspend/Android.bp create mode 100644 aosp/system/core/lmkd/Android.bp create mode 100644 aosp/system/core/logd/Android.bp create mode 100644 aosp/system/core/reboot/Android.bp create mode 100644 aosp/system/core/rootdir/etc/public.libraries.android.txt create mode 100644 aosp/system/core/rootdir/init.environ.rc.in create mode 100644 aosp/system/core/rootdir/init.rc create mode 100644 aosp/system/core/rootdir/init.usb.configfs.rc create mode 100644 aosp/system/core/rootdir/init.usb.rc create mode 100644 aosp/system/core/rootdir/init.zygote32.rc create mode 100644 aosp/system/core/rootdir/init.zygote32_64.rc create mode 100644 aosp/system/core/rootdir/init.zygote64.rc create mode 100644 aosp/system/core/rootdir/init.zygote64_32.rc create mode 100644 aosp/system/core/rootdir/ueventd.rc create mode 100644 aosp/system/core/storaged/storaged.rc create mode 100644 aosp/system/hwservicemanager/Android.bp create mode 100644 aosp/system/libhidl/vintfdata/manifest.xml create mode 100644 aosp/system/libhwbinder/Android.bp create mode 100644 aosp/system/netd/server/Android.mk create mode 100644 aosp/system/security/keystore/Android.bp create mode 100644 aosp/system/sepolicy/prebuilts/api/26.0/private/service_contexts create mode 100644 aosp/system/sepolicy/prebuilts/api/27.0/private/compat/26.0/26.0.ignore.cil create mode 100644 aosp/system/sepolicy/prebuilts/api/27.0/private/service_contexts create mode 100644 aosp/system/sepolicy/prebuilts/api/28.0/private/app_neverallows.te create mode 100644 aosp/system/sepolicy/prebuilts/api/28.0/private/compat/26.0/26.0.ignore.cil create mode 100644 aosp/system/sepolicy/prebuilts/api/28.0/private/compat/27.0/27.0.ignore.cil create mode 100644 aosp/system/sepolicy/prebuilts/api/28.0/private/file_contexts create mode 100644 aosp/system/sepolicy/prebuilts/api/28.0/private/service_contexts create mode 100644 aosp/system/sepolicy/prebuilts/api/28.0/public/domain.te create mode 100644 aosp/system/sepolicy/prebuilts/api/28.0/public/file.te create mode 100644 aosp/system/sepolicy/prebuilts/api/28.0/public/te_macros create mode 100644 aosp/system/sepolicy/private/app_neverallows.te create mode 100644 aosp/system/sepolicy/private/compat/26.0/26.0.ignore.cil create mode 100644 aosp/system/sepolicy/private/compat/27.0/27.0.ignore.cil create mode 100644 aosp/system/sepolicy/private/file_contexts create mode 100644 aosp/system/sepolicy/private/service_contexts create mode 100644 aosp/system/sepolicy/public/domain.te create mode 100644 aosp/system/sepolicy/public/file.te create mode 100644 aosp/system/sepolicy/public/te_macros diff --git a/aosp/art/dex2oat/Android.bp b/aosp/art/dex2oat/Android.bp new file mode 100644 index 000000000..19556b566 --- /dev/null +++ b/aosp/art/dex2oat/Android.bp @@ -0,0 +1,303 @@ +// +// Copyright (C) 2011 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +art_cc_defaults { + name: "libart-dex2oat-defaults", + defaults: ["art_defaults"], + host_supported: true, + srcs: [ + "linker/elf_writer.cc", + "linker/elf_writer_quick.cc", + "linker/image_writer.cc", + "linker/multi_oat_relative_patcher.cc", + "linker/oat_writer.cc", + ], + target: { + android: { + // For atrace. + shared_libs: ["libcutils"], + }, + }, + generated_sources: ["art_dex2oat_operator_srcs"], + shared_libs: [ + "libbase", + "liblz4", + "liblzma", + ], + include_dirs: [ + "external/lz4/lib", + "external/zlib", + ], + export_include_dirs: ["."], + + // For SHA-1 checksumming of build ID + static: { + whole_static_libs: ["libcrypto"], + }, + shared: { + shared_libs: ["libcrypto"], + }, +} + +gensrcs { + name: "art_dex2oat_operator_srcs", + cmd: "$(location generate_operator_out) art/dex2oat $(in) > $(out)", + tools: ["generate_operator_out"], + srcs: [ + "linker/image_writer.h", + ], + output_extension: "operator_out.cc", +} + +art_cc_static_library { + name: "libart-dex2oat", + defaults: ["libart-dex2oat-defaults"], + shared_libs: [ + "libart-compiler", + "libart-dexlayout", + "libart", + ], +} + +art_cc_static_library { + name: "libartd-dex2oat", + defaults: [ + "art_debug_defaults", + "libart-dex2oat-defaults", + ], + shared_libs: [ + "libartd-compiler", + "libartd-dexlayout", + "libartd", + ], +} + +cc_library_headers { + name: "dex2oat_headers", + host_supported: true, + export_include_dirs: ["include"], +} + +cc_defaults { + name: "dex2oat-defaults", + host_supported: true, + defaults: ["art_defaults"], + srcs: [ + "dex2oat_options.cc", + "dex2oat.cc", + ], + + target: { + android: { + // Use the 32-bit version of dex2oat on devices + compile_multilib: "first", + }, + }, + header_libs: [ + "dex2oat_headers", + "art_cmdlineparser_headers", + ], +} + +cc_defaults { + name: "dex2oat-pgo-defaults", + pgo: { + instrumentation: true, + benchmarks: ["dex2oat"], + }, + target: { + android_arm64: { + pgo: { + profile_file: "art/dex2oat_arm_arm64.profdata", + }, + }, + android_arm: { + pgo: { + profile_file: "art/dex2oat_arm_arm64.profdata", + }, + }, + android_x86_64: { + pgo: { + profile_file: "art/dex2oat_x86_x86_64.profdata", + }, + }, + android_x86: { + pgo: { + profile_file: "art/dex2oat_x86_x86_64.profdata", + }, + }, + android_mips64: { + pgo: { + profile_file: "art/dex2oat_mips_mips64.profdata", + }, + }, + android_mips: { + pgo: { + profile_file: "art/dex2oat_mips_mips64.profdata", + }, + }, + }, +} + +art_cc_binary { + name: "dex2oat", + defaults: [ + "dex2oat-defaults", + "dex2oat-pgo-defaults", + ], + shared_libs: [ + "libart-compiler", + "libart-dexlayout", + "libart", + "libdexfile", + "libbase", + "liblz4", + "libsigchain", + ], + static_libs: [ + "libart-dex2oat", + ], + + pgo: { + // Additional cflags just for dex2oat during PGO instrumentation + cflags: [ + // Ignore frame-size increase resulting from instrumentation. + "-Wno-frame-larger-than=", + "-DART_PGO_INSTRUMENTATION", + ], + }, + target: { + android: { + lto: { + thin: true, + }, + }, + }, +} + +art_cc_binary { + name: "dex2oatd", + defaults: [ + "art_debug_defaults", + "dex2oat-defaults", + ], + shared_libs: [ + "libartd-compiler", + "libartd-dexlayout", + "libartd", + "libdexfiled", + "libbase", + "liblz4", + "libsigchain", + ], + static_libs: [ + "libartd-dex2oat", + ], +} + +art_cc_binary { + name: "dex2oats", + device_supported: false, + static_executable: true, + defaults: ["dex2oat-defaults"], + target: { + darwin: { + enabled: false, + }, + }, + ldflags: [ + // We need this because GC stress mode makes use of + // _Unwind_GetIP and _Unwind_Backtrace and the symbols are also + // defined in libgcc_eh.a(unwind-dw2.o) + // TODO: Having this is not ideal as it might obscure errors. + // Try to get rid of it. + "-z muldefs", + ], + static_libs: [ + "libart-dex2oat", + "libart-compiler", + "libart-dexlayout", + "libart", + "libdexfile", + "libvixl-arm", + "libvixl-arm64", + ] + art_static_dependencies, +} + +art_cc_binary { + name: "dex2oatds", + device_supported: false, + static_executable: true, + defaults: [ + "art_debug_defaults", + "dex2oat-defaults", + ], + target: { + darwin: { + enabled: false, + }, + }, + ldflags: [ + // We need this because GC stress mode makes use of + // _Unwind_GetIP and _Unwind_Backtrace and the symbols are also + // defined in libgcc_eh.a(unwind-dw2.o) + // TODO: Having this is not ideal as it might obscure errors. + // Try to get rid of it. + "-z muldefs", + ], + static_libs: [ + "libartd-dex2oat", + "libartd-compiler", + "libartd-dexlayout", + "libartd", + "libdexfiled", + "libvixld-arm", + "libvixld-arm64", + ] + art_static_dependencies, +} + +art_cc_test { + name: "art_dex2oat_tests", + defaults: [ + "art_gtest_defaults", + ], + srcs: [ + "dex2oat_test.cc", + "dex2oat_vdex_test.cc", + "dex2oat_image_test.cc", + "linker/elf_writer_test.cc", + "linker/image_test.cc", + "linker/image_write_read_test.cc", + "linker/index_bss_mapping_encoder_test.cc", + "linker/multi_oat_relative_patcher_test.cc", + "linker/oat_writer_test.cc", + ], + header_libs: ["dex2oat_headers"], + include_dirs: [ + "external/zlib", + ], + shared_libs: [ + "libartd-compiler", + "libartd-dexlayout", + "libbase", + "liblz4", + "libsigchain", + "libziparchive", + ], + static_libs: [ + "libartd-dex2oat", + ], +} diff --git a/aosp/art/dexoptanalyzer/Android.bp b/aosp/art/dexoptanalyzer/Android.bp new file mode 100644 index 000000000..2b4ef45ef --- /dev/null +++ b/aosp/art/dexoptanalyzer/Android.bp @@ -0,0 +1,64 @@ +// +// Copyright (C) 2017 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +cc_defaults { + name: "dexoptanalyzer-defaults", + host_supported: true, + defaults: ["art_defaults"], + srcs: [ + "dexoptanalyzer.cc", + ], + + target: { + android: { + compile_multilib: "first", + }, + }, + + shared_libs: [ + "libbase", + ], +} + +art_cc_binary { + name: "dexoptanalyzer", + defaults: ["dexoptanalyzer-defaults"], + shared_libs: [ + "libart", + ], +} + +art_cc_binary { + name: "dexoptanalyzerd", + defaults: [ + "art_debug_defaults", + "dexoptanalyzer-defaults", + ], + shared_libs: [ + "libartd", + ], +} + +art_cc_test { + name: "art_dexoptanalyzer_tests", + defaults: [ + "art_gtest_defaults", + ], + shared_libs: [ + "libbacktrace", + ], + srcs: ["dexoptanalyzer_test.cc"], +} diff --git a/aosp/art/patchoat/Android.bp b/aosp/art/patchoat/Android.bp new file mode 100644 index 000000000..09e82b41d --- /dev/null +++ b/aosp/art/patchoat/Android.bp @@ -0,0 +1,64 @@ +// +// Copyright (C) 2014 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +cc_defaults { + name: "patchoat-defaults", + host_supported: true, + defaults: ["art_defaults"], + srcs: ["patchoat.cc"], + target: { + android: { + compile_multilib: "first", + }, + }, + shared_libs: [ + "libbase", + "libcrypto", // For computing the digest of image file + ], +} + +art_cc_binary { + name: "patchoat", + defaults: ["patchoat-defaults"], + shared_libs: [ + "libart", + ], +} + +art_cc_binary { + name: "patchoatd", + defaults: [ + "art_debug_defaults", + "patchoat-defaults", + ], + shared_libs: [ + "libartd", + ], +} + +art_cc_test { + name: "art_patchoat_tests", + defaults: [ + "art_gtest_defaults", + ], + srcs: [ + "patchoat_test.cc", + ], + shared_libs: [ + "libartd", + "libcrypto", // For computing the digest of image file + ], +} diff --git a/aosp/art/profman/Android.bp b/aosp/art/profman/Android.bp new file mode 100644 index 000000000..306ed954e --- /dev/null +++ b/aosp/art/profman/Android.bp @@ -0,0 +1,65 @@ +// +// Copyright (C) 2016 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +cc_defaults { + name: "profman-defaults", + host_supported: true, + defaults: ["art_defaults"], + srcs: [ + "boot_image_profile.cc", + "profman.cc", + "profile_assistant.cc", + ], + + target: { + android: { + compile_multilib: "first", + }, + }, + + shared_libs: [ + "libbase", + ], +} + +art_cc_binary { + name: "profman", + defaults: ["profman-defaults"], + shared_libs: [ + "libart", + "libdexfile", + ], +} + +art_cc_binary { + name: "profmand", + defaults: [ + "art_debug_defaults", + "profman-defaults", + ], + shared_libs: [ + "libartd", + "libdexfiled", + ], +} + +art_cc_test { + name: "art_profman_tests", + defaults: [ + "art_gtest_defaults", + ], + srcs: ["profile_assistant_test.cc"], +} diff --git a/aosp/art/tools/hiddenapi/Android.bp b/aosp/art/tools/hiddenapi/Android.bp new file mode 100644 index 000000000..04d6ae7f3 --- /dev/null +++ b/aosp/art/tools/hiddenapi/Android.bp @@ -0,0 +1,66 @@ +// +// Copyright (C) 2017 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +cc_defaults { + name: "hiddenapi-defaults", + host_supported: true, + device_supported: false, + defaults: ["art_defaults"], + srcs: [ + "hiddenapi.cc", + ], + + target: { + android: { + compile_multilib: "first", + }, + }, + + shared_libs: [ + "libbase", + ], +} + +art_cc_binary { + name: "hiddenapi", + defaults: ["hiddenapi-defaults"], + shared_libs: [ + "libart", + "libdexfile", + ], +} + +art_cc_binary { + name: "hiddenapid", + defaults: [ + "art_debug_defaults", + "hiddenapi-defaults", + ], + shared_libs: [ + "libartd", + "libdexfiled", + ], +} + +art_cc_test { + name: "art_hiddenapi_tests", + host_supported: true, + device_supported: false, + defaults: [ + "art_gtest_defaults", + ], + srcs: ["hiddenapi_test.cc"], +} diff --git a/aosp/bionic/libc/seccomp/Android.bp b/aosp/bionic/libc/seccomp/Android.bp new file mode 100644 index 000000000..eb75d23e4 --- /dev/null +++ b/aosp/bionic/libc/seccomp/Android.bp @@ -0,0 +1,35 @@ +cc_library { + name: "libseccomp_policy_orig", + srcs: [ + "seccomp_policy.cpp", + "arm_app_policy.cpp", + "arm_global_policy.cpp", + "arm_system_policy.cpp", + "arm64_app_policy.cpp", + "arm64_global_policy.cpp", + "arm64_system_policy.cpp", + "x86_app_policy.cpp", + "x86_global_policy.cpp", + "x86_system_policy.cpp", + "x86_64_app_policy.cpp", + "x86_64_global_policy.cpp", + "x86_64_system_policy.cpp", + "mips_app_policy.cpp", + "mips_global_policy.cpp", + "mips_system_policy.cpp", + "mips64_app_policy.cpp", + "mips64_global_policy.cpp", + "mips64_system_policy.cpp", + ], + export_include_dirs: ["include"], + cflags: [ + "-Wall", + "-Werror", + ], + shared: { + shared_libs: ["libbase"], + }, + static: { + static_libs: ["libbase"], + }, +} diff --git a/aosp/bionic/libc/system_properties/Android.bp b/aosp/bionic/libc/system_properties/Android.bp new file mode 100644 index 000000000..df768ff4c --- /dev/null +++ b/aosp/bionic/libc/system_properties/Android.bp @@ -0,0 +1,30 @@ +cc_library_static { + name: "libsystemproperties", + defaults: ["libc_defaults"], + srcs: [ + "context_node.cpp", + "contexts_split.cpp", + "contexts_serialized.cpp", + "prop_area.cpp", + "prop_info.cpp", + "system_properties.cpp", + ], + whole_static_libs: [ + "libpropertyinfoparser", + ], + static_libs: [ + "libasync_safe", + ], + + product_variables: { + large_system_property_node : { + cflags: ["-DLARGE_SYSTEM_PROPERTY_NODE"], + }, + }, + + include_dirs: [ + "bionic/libc", + "bionic/libstdc++/include", + ], + export_include_dirs: ["include"], +} diff --git a/aosp/bootable/recovery/minui/Android.mk b/aosp/bootable/recovery/minui/Android.mk new file mode 100644 index 000000000..0d22ed496 --- /dev/null +++ b/aosp/bootable/recovery/minui/Android.mk @@ -0,0 +1,88 @@ +# Copyright (C) 2007 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +LOCAL_PATH := $(call my-dir) + +# libminui (static library) +# =============================== +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := \ + events.cpp \ + graphics.cpp \ + graphics_adf.cpp \ + graphics_drm.cpp \ + graphics_fbdev.cpp \ + resources.cpp \ + +LOCAL_WHOLE_STATIC_LIBRARIES := \ + libadf \ + libsync_recovery + +LOCAL_STATIC_LIBRARIES := \ + libpng \ + libbase + +LOCAL_SHARED_LIBRARIES := libdrm + +LOCAL_CFLAGS := -Wall -Werror +LOCAL_C_INCLUDES := $(LOCAL_PATH)/include \ + $(TOP)/external/libdrm \ + $(TOP)/external/libdrm/include/drm +LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include + +LOCAL_MODULE := libminui + +# This used to compare against values in double-quotes (which are just +# ordinary characters in this context). Strip double-quotes from the +# value so that either will work. + +ifeq ($(subst ",,$(TARGET_RECOVERY_PIXEL_FORMAT)),ABGR_8888) + LOCAL_CFLAGS += -DRECOVERY_ABGR +endif +ifeq ($(subst ",,$(TARGET_RECOVERY_PIXEL_FORMAT)),RGBX_8888) + LOCAL_CFLAGS += -DRECOVERY_RGBX +endif +ifeq ($(subst ",,$(TARGET_RECOVERY_PIXEL_FORMAT)),BGRA_8888) + LOCAL_CFLAGS += -DRECOVERY_BGRA +endif + +ifneq ($(TARGET_RECOVERY_OVERSCAN_PERCENT),) + LOCAL_CFLAGS += -DOVERSCAN_PERCENT=$(TARGET_RECOVERY_OVERSCAN_PERCENT) +else + LOCAL_CFLAGS += -DOVERSCAN_PERCENT=0 +endif + +ifneq ($(TARGET_RECOVERY_DEFAULT_ROTATION),) + LOCAL_CFLAGS += -DDEFAULT_ROTATION=$(TARGET_RECOVERY_DEFAULT_ROTATION) +else + LOCAL_CFLAGS += -DDEFAULT_ROTATION=ROTATION_NONE +endif + +include $(BUILD_STATIC_LIBRARY) + +# libminui (shared library) +# =============================== +# Used by OEMs for factory test images. +include $(CLEAR_VARS) +LOCAL_MODULE := libminui +LOCAL_WHOLE_STATIC_LIBRARIES += libminui +LOCAL_SHARED_LIBRARIES := \ + libpng \ + libbase + +LOCAL_CFLAGS := -Wall -Werror +LOCAL_C_INCLUDES := $(LOCAL_PATH)/include +LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include +include $(BUILD_SHARED_LIBRARY) diff --git a/aosp/build/make/core/Makefile b/aosp/build/make/core/Makefile new file mode 100644 index 000000000..dace79b8f --- /dev/null +++ b/aosp/build/make/core/Makefile @@ -0,0 +1,3305 @@ +# Put some miscellaneous rules here + +# HACK: clear LOCAL_PATH from including last build target before calling +# intermedites-dir-for +LOCAL_PATH := $(BUILD_SYSTEM) + +# ----------------------------------------------------------------- +# Define rules to copy PRODUCT_COPY_FILES defined by the product. +# PRODUCT_COPY_FILES contains words like :[:]. +# is relative to $(PRODUCT_OUT), so it should look like, +# e.g., "system/etc/file.xml". +# The filter part means "only eval the copy-one-file rule if this +# src:dest pair is the first one to match the same dest" +#$(1): the src:dest pair +#$(2): the dest +# filter out the duplicate : pairs. +unique_product_copy_files_pairs := +$(foreach cf,$(PRODUCT_COPY_FILES), \ + $(if $(filter $(unique_product_copy_files_pairs),$(cf)),,\ + $(eval unique_product_copy_files_pairs += $(cf)))) +unique_product_copy_files_destinations := +product_copy_files_ignored := +$(foreach cf,$(unique_product_copy_files_pairs), \ + $(eval _src := $(call word-colon,1,$(cf))) \ + $(eval _dest := $(call word-colon,2,$(cf))) \ + $(call check-product-copy-files,$(cf),$(_dest)) \ + $(if $(filter $(unique_product_copy_files_destinations),$(_dest)), \ + $(eval product_copy_files_ignored += $(cf)), \ + $(eval _fulldest := $(call append-path,$(PRODUCT_OUT),$(_dest))) \ + $(if $(filter %.xml,$(_dest)),\ + $(eval $(call copy-xml-file-checked,$(_src),$(_fulldest))),\ + $(if $(and $(filter %.jar,$(_dest)),$(filter $(basename $(notdir $(_dest))),$(PRODUCT_LOADED_BY_PRIVILEGED_MODULES))),\ + $(eval $(call copy-and-uncompress-dexs,$(_src),$(_fulldest))), \ + $(eval $(call copy-one-file,$(_src),$(_fulldest))))) \ + $(eval ALL_DEFAULT_INSTALLED_MODULES += $(_fulldest)) \ + $(eval unique_product_copy_files_destinations += $(_dest)))) + +# Dump a list of overriden (and ignored PRODUCT_COPY_FILES entries) +$(file >$(PRODUCT_OUT)/product_copy_files_ignored.txt,$(subst $(space),$(newline),$(strip $(product_copy_files_ignored)))) +ifdef dist_goal +$(file >$(DIST_DIR)/logs/product_copy_files_ignored.txt,$(subst $(space),$(newline),$(strip $(product_copy_files_ignored)))) +endif + +product_copy_files_ignored := +unique_product_copy_files_pairs := +unique_product_copy_files_destinations := + +# ----------------------------------------------------------------- +# Returns the max allowed size for an image suitable for hash verification +# (e.g., boot.img, recovery.img, etc). +# The value 69632 derives from MAX_VBMETA_SIZE + MAX_FOOTER_SIZE in $(AVBTOOL). +# $(1): partition size to flash the image +define get-hash-image-max-size +$(if $(1), \ + $(if $(filter true,$(BOARD_AVB_ENABLE)), \ + $(eval _hash_meta_size := 69632), \ + $(eval _hash_meta_size := 0)) \ + $(1)-$(_hash_meta_size)) +endef + +# ----------------------------------------------------------------- +# Define rules to copy headers defined in copy_headers.mk +# If more than one makefile declared a header, print a warning, +# then copy the last one defined. This matches the previous make +# behavior. +$(foreach dest,$(ALL_COPIED_HEADERS), \ + $(eval _srcs := $(ALL_COPIED_HEADERS.$(dest).SRC)) \ + $(eval _src := $(word $(words $(_srcs)),$(_srcs))) \ + $(if $(call streq,$(_src),$(_srcs)),, \ + $(warning Duplicate header copy: $(dest)) \ + $(warning Defined in: $(ALL_COPIED_HEADERS.$(dest).MAKEFILE))) \ + $(eval $(call copy-one-header,$(_src),$(dest)))) +all_copied_headers: $(ALL_COPIED_HEADERS) + +# ----------------------------------------------------------------- +# docs/index.html +ifeq (,$(TARGET_BUILD_APPS)) +gen := $(OUT_DOCS)/index.html +ALL_DOCS += $(gen) +$(gen): frameworks/base/docs/docs-redirect-index.html + @mkdir -p $(dir $@) + @cp -f $< $@ +endif + +ndk_doxygen_out := $(OUT_NDK_DOCS) +ndk_headers := $(SOONG_OUT_DIR)/ndk/sysroot/usr/include +ndk_docs_src_dir := frameworks/native/docs +ndk_doxyfile := $(ndk_docs_src_dir)/Doxyfile +ifneq ($(wildcard $(ndk_docs_src_dir)),) +ndk_docs_srcs := $(addprefix $(ndk_docs_src_dir)/,\ + $(call find-files-in-subdirs,$(ndk_docs_src_dir),"*",.)) +$(ndk_doxygen_out)/index.html: $(ndk_docs_srcs) $(SOONG_OUT_DIR)/ndk.timestamp + @mkdir -p $(ndk_doxygen_out) + @echo "Generating NDK docs to $(ndk_doxygen_out)" + @( cat $(ndk_doxyfile); \ + echo "INPUT=$(ndk_headers)"; \ + echo "HTML_OUTPUT=$(ndk_doxygen_out)" \ + ) | doxygen - + +# Note: Not a part of the docs target because we don't have doxygen available. +# You can run this target locally if you have doxygen installed. +ndk-docs: $(ndk_doxygen_out)/index.html +.PHONY: ndk-docs +endif + +# ----------------------------------------------------------------- +# property_overrides_split_enabled +property_overrides_split_enabled := +ifeq ($(BOARD_PROPERTY_OVERRIDES_SPLIT_ENABLED), true) + property_overrides_split_enabled := true +endif + +# ----------------------------------------------------------------- +# FINAL_VENDOR_DEFAULT_PROPERTIES will be installed in vendor/default.prop if +# property_overrides_split_enabled is true. Otherwise it will be installed in +# ROOT/default.prop. +ifdef BOARD_VNDK_VERSION + ifeq ($(BOARD_VNDK_VERSION),current) + FINAL_VENDOR_DEFAULT_PROPERTIES := ro.vndk.version=$(PLATFORM_VNDK_VERSION) + else + FINAL_VENDOR_DEFAULT_PROPERTIES := ro.vndk.version=$(BOARD_VNDK_VERSION) + endif + ifdef BOARD_VNDK_RUNTIME_DISABLE + FINAL_VENDOR_DEFAULT_PROPERTIES += ro.vndk.lite=true + endif +else + FINAL_VENDOR_DEFAULT_PROPERTIES := ro.vndk.version=$(PLATFORM_VNDK_VERSION) + FINAL_VENDOR_DEFAULT_PROPERTIES += ro.vndk.lite=true +endif +FINAL_VENDOR_DEFAULT_PROPERTIES += \ + $(call collapse-pairs, $(PRODUCT_DEFAULT_PROPERTY_OVERRIDES)) +FINAL_VENDOR_DEFAULT_PROPERTIES := $(call uniq-pairs-by-first-component, \ + $(FINAL_VENDOR_DEFAULT_PROPERTIES),=) + +# ----------------------------------------------------------------- +# prop.default +ifdef property_overrides_split_enabled +INSTALLED_DEFAULT_PROP_TARGET := $(TARGET_OUT)/etc/prop.default +INSTALLED_DEFAULT_PROP_OLD_TARGET := $(TARGET_ROOT_OUT)/default.prop +ALL_DEFAULT_INSTALLED_MODULES += $(INSTALLED_DEFAULT_PROP_OLD_TARGET) +$(INSTALLED_DEFAULT_PROP_OLD_TARGET): $(INSTALLED_DEFAULT_PROP_TARGET) +else +# legacy path +INSTALLED_DEFAULT_PROP_TARGET := $(TARGET_ROOT_OUT)/default.prop +endif +ALL_DEFAULT_INSTALLED_MODULES += $(INSTALLED_DEFAULT_PROP_TARGET) +FINAL_DEFAULT_PROPERTIES := \ + $(call collapse-pairs, $(ADDITIONAL_DEFAULT_PROPERTIES)) \ + $(call collapse-pairs, $(PRODUCT_SYSTEM_DEFAULT_PROPERTIES)) +ifndef property_overrides_split_enabled + FINAL_DEFAULT_PROPERTIES += \ + $(call collapse-pairs, $(FINAL_VENDOR_DEFAULT_PROPERTIES)) +endif +FINAL_DEFAULT_PROPERTIES := $(call uniq-pairs-by-first-component, \ + $(FINAL_DEFAULT_PROPERTIES),=) + +intermediate_system_build_prop := $(call intermediates-dir-for,ETC,system_build_prop)/build.prop + +$(INSTALLED_DEFAULT_PROP_TARGET): $(intermediate_system_build_prop) + @echo Target buildinfo: $@ + @mkdir -p $(dir $@) + @rm -f $@ + $(hide) echo "#" > $@; \ + echo "# ADDITIONAL_DEFAULT_PROPERTIES" >> $@; \ + echo "#" >> $@; + $(hide) $(foreach line,$(FINAL_DEFAULT_PROPERTIES), \ + echo "$(line)" >> $@;) + $(hide) echo "#" >> $@; \ + echo "# BOOTIMAGE_BUILD_PROPERTIES" >> $@; \ + echo "#" >> $@; + $(hide) echo ro.bootimage.build.date=`$(DATE_FROM_FILE)`>>$@ + $(hide) echo ro.bootimage.build.date.utc=`$(DATE_FROM_FILE) +%s`>>$@ + $(hide) echo ro.bootimage.build.fingerprint="$(BUILD_FINGERPRINT_FROM_FILE)">>$@ + $(hide) echo com.cph.wifi.rssi=-30>>$@ + $(hide) echo ro.build.id="$(BUILD_ID)">>$@ + $(hide) echo ro.build.display.id="$(BUILD_ID)">>$@ + $(hide) echo ro.build.version.incremental="$(BUILD_NUMBER)">>$@ + $(hide) echo ro.build.date=`$(DATE_FROM_FILE)`>>$@ + $(hide) echo ro.build.date.utc=`$(DATE_FROM_FILE) +%s`>>$@ + $(hide) echo gsm.version.baseband="CBP8.2,21.258.08.00.030">>$@ + $(hide) echo ro.board.platform="$(BUILD_HARDWARE)">>$@ + $(hide) echo ro.hardware="$(BUILD_HARDWARE)">>$@ + $(hide) echo ro.sf.lcd_density="320">>$@ + $(hide) build/make/tools/post_process_props.py $@ +ifdef property_overrides_split_enabled + $(hide) mkdir -p $(TARGET_ROOT_OUT) + $(hide) ln -sf system/etc/prop.default $(INSTALLED_DEFAULT_PROP_OLD_TARGET) +endif + +# ----------------------------------------------------------------- +# vendor default.prop +INSTALLED_VENDOR_DEFAULT_PROP_TARGET := +ifdef property_overrides_split_enabled +INSTALLED_VENDOR_DEFAULT_PROP_TARGET := $(TARGET_OUT_VENDOR)/default.prop +ALL_DEFAULT_INSTALLED_MODULES += $(INSTALLED_VENDOR_DEFAULT_PROP_TARGET) + +$(INSTALLED_VENDOR_DEFAULT_PROP_TARGET): $(INSTALLED_DEFAULT_PROP_TARGET) + @echo Target buildinfo: $@ + @mkdir -p $(dir $@) + $(hide) echo "#" > $@; \ + echo "# ADDITIONAL VENDOR DEFAULT PROPERTIES" >> $@; \ + echo "#" >> $@; + $(hide) $(foreach line,$(FINAL_VENDOR_DEFAULT_PROPERTIES), \ + echo "$(line)" >> $@;) + $(hide) build/make/tools/post_process_props.py $@ + +endif # property_overrides_split_enabled + +# ----------------------------------------------------------------- +# build.prop +INSTALLED_BUILD_PROP_TARGET := $(TARGET_OUT)/build.prop +ALL_DEFAULT_INSTALLED_MODULES += $(INSTALLED_BUILD_PROP_TARGET) +FINAL_BUILD_PROPERTIES := \ + $(call collapse-pairs, $(ADDITIONAL_BUILD_PROPERTIES)) +FINAL_BUILD_PROPERTIES := $(call uniq-pairs-by-first-component, \ + $(FINAL_BUILD_PROPERTIES),=) + +# A list of arbitrary tags describing the build configuration. +# Force ":=" so we can use += +BUILD_VERSION_TAGS := $(BUILD_VERSION_TAGS) +ifeq ($(TARGET_BUILD_TYPE),debug) + BUILD_VERSION_TAGS += debug +endif +# The "test-keys" tag marks builds signed with the old test keys, +# which are available in the SDK. "dev-keys" marks builds signed with +# non-default dev keys (usually private keys from a vendor directory). +# Both of these tags will be removed and replaced with "release-keys" +# when the target-files is signed in a post-build step. +# ifeq ($(DEFAULT_SYSTEM_DEV_CERTIFICATE),build/target/product/security/testkey) +# BUILD_KEYS := test-keys +# else +# BUILD_KEYS := dev-keys +# endif +BUILD_KEYS := release-keys +BUILD_VERSION_TAGS += $(BUILD_KEYS) +BUILD_VERSION_TAGS := $(subst $(space),$(comma),$(sort $(BUILD_VERSION_TAGS))) +GMS_PRODUCT_BRAND := HUAWEI +GMS_TARGET_PRODUCT := NXT-AL10 +GMS_TARGET_DEVICE := HWNXT + +# A human-readable string that descibes this build in detail. +build_desc := $(TARGET_PRODUCT)-$(TARGET_BUILD_VARIANT) $(PLATFORM_VERSION) $(BUILD_ID) $(BUILD_NUMBER_FROM_FILE) $(BUILD_VERSION_TAGS) +$(intermediate_system_build_prop): PRIVATE_BUILD_DESC := $(build_desc) + +# The string used to uniquely identify the combined build and product; used by the OTA server. +ifeq (,$(strip $(BUILD_FINGERPRINT))) + ifeq ($(strip $(HAS_BUILD_NUMBER)),false) + BF_BUILD_NUMBER := $(USER)$$($(DATE_FROM_FILE) +%m%d%H%M) + else + BF_BUILD_NUMBER := $(file <$(BUILD_NUMBER_FILE)) + endif + + ifeq ($(strip $(IS_GMS_LUNCH)), true) + BUILD_FINGERPRINT := $(GMS_PRODUCT_BRAND)/$(GMS_TARGET_PRODUCT)/$(GMS_TARGET_DEVICE):$(PLATFORM_VERSION)/$(BUILD_ID)/$(BF_BUILD_NUMBER):$(TARGET_BUILD_VARIANT)/$(BUILD_VERSION_TAGS) + else + BUILD_FINGERPRINT := $(PRODUCT_BRAND)/$(TARGET_PRODUCT)/$(TARGET_DEVICE):$(PLATFORM_VERSION)/$(BUILD_ID)/$(BF_BUILD_NUMBER):$(TARGET_BUILD_VARIANT)/$(BUILD_VERSION_TAGS) + endif +endif +# unset it for safety. +BF_BUILD_NUMBER := + +BUILD_FINGERPRINT_FILE := $(PRODUCT_OUT)/build_fingerprint.txt +ifneq (,$(shell mkdir -p $(PRODUCT_OUT) && echo $(BUILD_FINGERPRINT) >$(BUILD_FINGERPRINT_FILE) && grep " " $(BUILD_FINGERPRINT_FILE))) + $(error BUILD_FINGERPRINT cannot contain spaces: "$(file <$(BUILD_FINGERPRINT_FILE))") +endif +BUILD_FINGERPRINT_FROM_FILE := $$(cat $(BUILD_FINGERPRINT_FILE)) +# unset it for safety. +BUILD_FINGERPRINT := + +# The string used to uniquely identify the system build; used by the OTA server. +# This purposefully excludes any product-specific variables. +ifeq (,$(strip $(BUILD_THUMBPRINT))) + BUILD_THUMBPRINT := $(PLATFORM_VERSION)/$(BUILD_ID)/$(BUILD_NUMBER_FROM_FILE):$(TARGET_BUILD_VARIANT)/$(BUILD_VERSION_TAGS) +endif + +BUILD_THUMBPRINT_FILE := $(PRODUCT_OUT)/build_thumbprint.txt +ifneq (,$(shell mkdir -p $(PRODUCT_OUT) && echo $(BUILD_THUMBPRINT) >$(BUILD_THUMBPRINT_FILE) && grep " " $(BUILD_THUMBPRINT_FILE))) + $(error BUILD_THUMBPRINT cannot contain spaces: "$(file <$(BUILD_THUMBPRINT_FILE))") +endif +BUILD_THUMBPRINT_FROM_FILE := $$(cat $(BUILD_THUMBPRINT_FILE)) +# unset it for safety. +BUILD_THUMBPRINT := + +KNOWN_OEM_THUMBPRINT_PROPERTIES := \ + ro.product.brand \ + ro.product.name \ + ro.product.device +OEM_THUMBPRINT_PROPERTIES := $(filter $(KNOWN_OEM_THUMBPRINT_PROPERTIES),\ + $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_OEM_PROPERTIES)) + +# Display parameters shown under Settings -> About Phone +ifeq ($(TARGET_BUILD_VARIANT),user) + # User builds should show: + # release build number or branch.buld_number non-release builds + + # Dev. branches should have DISPLAY_BUILD_NUMBER set + ifeq (true,$(DISPLAY_BUILD_NUMBER)) + BUILD_DISPLAY_ID := $(BUILD_ID).$(BUILD_NUMBER_FROM_FILE) $(BUILD_KEYS) + else + BUILD_DISPLAY_ID := $(BUILD_ID) $(BUILD_KEYS) + endif +else + # Non-user builds should show detailed build information + BUILD_DISPLAY_ID := $(build_desc) +endif + +# Accepts a whitespace separated list of product locales such as +# (en_US en_AU en_GB...) and returns the first locale in the list with +# underscores replaced with hyphens. In the example above, this will +# return "en-US". +define get-default-product-locale +$(strip $(subst _,-, $(firstword $(1)))) +endef + +BUILDINFO_SH := build/make/tools/buildinfo.sh +VENDOR_BUILDINFO_SH := build/make/tools/vendor_buildinfo.sh + +# TARGET_BUILD_FLAVOR and ro.build.flavor are used only by the test +# harness to distinguish builds. Only add _asan for a sanitized build +# if it isn't already a part of the flavor (via a dedicated lunch +# config for example). +TARGET_BUILD_FLAVOR := $(TARGET_PRODUCT)-$(TARGET_BUILD_VARIANT) +ifneq (, $(filter address, $(SANITIZE_TARGET))) +ifeq (,$(findstring _asan,$(TARGET_BUILD_FLAVOR))) +TARGET_BUILD_FLAVOR := $(TARGET_BUILD_FLAVOR)_asan +endif +endif + +ifdef TARGET_SYSTEM_PROP +system_prop_file := $(TARGET_SYSTEM_PROP) +else +system_prop_file := $(wildcard $(TARGET_DEVICE_DIR)/system.prop) +endif +$(intermediate_system_build_prop): $(BUILDINFO_SH) $(INTERNAL_BUILD_ID_MAKEFILE) $(BUILD_SYSTEM)/version_defaults.mk $(system_prop_file) $(INSTALLED_ANDROID_INFO_TXT_TARGET) + @echo Target buildinfo: $@ + @mkdir -p $(dir $@) + $(hide) echo > $@ +ifneq ($(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_OEM_PROPERTIES),) + $(hide) echo "#" >> $@; \ + echo "# PRODUCT_OEM_PROPERTIES" >> $@; \ + echo "#" >> $@; + $(hide) $(foreach prop,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_OEM_PROPERTIES), \ + echo "import /oem/oem.prop $(prop)" >> $@;) +endif + $(hide) TARGET_BUILD_TYPE="$(TARGET_BUILD_VARIANT)" \ + TARGET_BUILD_FLAVOR="$(TARGET_BUILD_FLAVOR)" \ + TARGET_DEVICE="$(TARGET_DEVICE)" \ + PRODUCT_NAME="$(TARGET_PRODUCT)" \ + PRODUCT_BRAND="$(PRODUCT_BRAND)" \ + PRODUCT_DEFAULT_LOCALE="$(call get-default-product-locale,$(PRODUCT_LOCALES))" \ + PRODUCT_DEFAULT_WIFI_CHANNELS="$(PRODUCT_DEFAULT_WIFI_CHANNELS)" \ + PRODUCT_MODEL="$(PRODUCT_MODEL)" \ + PRODUCT_MANUFACTURER="$(PRODUCT_MANUFACTURER)" \ + PRIVATE_BUILD_DESC="$(PRIVATE_BUILD_DESC)" \ + BUILD_ID="$(BUILD_ID)" \ + BUILD_DISPLAY_ID="$(BUILD_DISPLAY_ID)" \ + DATE="$(DATE_FROM_FILE)" \ + BUILD_NUMBER="$(BUILD_NUMBER_FROM_FILE)" \ + BOARD_BUILD_SYSTEM_ROOT_IMAGE="$(BOARD_BUILD_SYSTEM_ROOT_IMAGE)" \ + AB_OTA_UPDATER="$(AB_OTA_UPDATER)" \ + PLATFORM_VERSION="$(PLATFORM_VERSION)" \ + PLATFORM_SECURITY_PATCH="$(PLATFORM_SECURITY_PATCH)" \ + PLATFORM_BASE_OS="$(PLATFORM_BASE_OS)" \ + PLATFORM_SDK_VERSION="$(PLATFORM_SDK_VERSION)" \ + PLATFORM_PREVIEW_SDK_VERSION="$(PLATFORM_PREVIEW_SDK_VERSION)" \ + PLATFORM_VERSION_CODENAME="$(PLATFORM_VERSION_CODENAME)" \ + PLATFORM_VERSION_ALL_CODENAMES="$(PLATFORM_VERSION_ALL_CODENAMES)" \ + PLATFORM_MIN_SUPPORTED_TARGET_SDK_VERSION="$(PLATFORM_MIN_SUPPORTED_TARGET_SDK_VERSION)" \ + BUILD_VERSION_TAGS="$(BUILD_VERSION_TAGS)" \ + BUILD_FINGERPRINT="$(BUILD_FINGERPRINT_FROM_FILE)" \ + $(if $(OEM_THUMBPRINT_PROPERTIES),BUILD_THUMBPRINT="$(BUILD_THUMBPRINT_FROM_FILE)") \ + TARGET_CPU_ABI_LIST="$(TARGET_CPU_ABI_LIST)" \ + TARGET_CPU_ABI_LIST_32_BIT="$(TARGET_CPU_ABI_LIST_32_BIT)" \ + TARGET_CPU_ABI_LIST_64_BIT="$(TARGET_CPU_ABI_LIST_64_BIT)" \ + TARGET_CPU_ABI="$(TARGET_CPU_ABI)" \ + TARGET_CPU_ABI2="$(TARGET_CPU_ABI2)" \ + TARGET_AAPT_CHARACTERISTICS="$(TARGET_AAPT_CHARACTERISTICS)" \ + bash $(BUILDINFO_SH) >> $@ + $(hide) $(foreach file,$(system_prop_file), \ + if [ -f "$(file)" ]; then \ + echo "#" >> $@; \ + echo Target buildinfo from: "$(file)"; \ + echo "# from $(file)" >> $@; \ + echo "#" >> $@; \ + cat $(file) >> $@; \ + fi;) + $(if $(FINAL_BUILD_PROPERTIES), \ + $(hide) echo >> $@; \ + echo "#" >> $@; \ + echo "# ADDITIONAL_BUILD_PROPERTIES" >> $@; \ + echo "#" >> $@; ) + $(hide) $(foreach line,$(FINAL_BUILD_PROPERTIES), \ + echo "$(line)" >> $@;) + $(hide) cat $(INSTALLED_ANDROID_INFO_TXT_TARGET) | grep 'require version-' | sed -e 's/require version-/ro.build.expect./g' >> $@ + $(hide) build/make/tools/post_process_props.py $@ $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_PROPERTY_BLACKLIST) + +build_desc := + +ifeq (,$(filter true, $(TARGET_NO_KERNEL) $(TARGET_NO_RECOVERY))) +INSTALLED_RECOVERYIMAGE_TARGET := $(PRODUCT_OUT)/recovery.img +else +INSTALLED_RECOVERYIMAGE_TARGET := +endif + +$(INSTALLED_BUILD_PROP_TARGET): $(intermediate_system_build_prop) $(INSTALLED_RECOVERYIMAGE_TARGET) + @echo "Target build info: $@" + $(hide) grep -v 'ro.product.first_api_level' $(intermediate_system_build_prop) > $@ +ifdef INSTALLED_RECOVERYIMAGE_TARGET + $(hide) echo ro.expect.recovery_id=`cat $(RECOVERYIMAGE_ID_FILE)` >> $@ +endif + +# ----------------------------------------------------------------- +# vendor build.prop +# +# For verifying that the vendor build is what we think it is +INSTALLED_VENDOR_BUILD_PROP_TARGET := $(TARGET_OUT_VENDOR)/build.prop +ALL_DEFAULT_INSTALLED_MODULES += $(INSTALLED_VENDOR_BUILD_PROP_TARGET) + +ifdef property_overrides_split_enabled +FINAL_VENDOR_BUILD_PROPERTIES += \ + $(call collapse-pairs, $(PRODUCT_PROPERTY_OVERRIDES)) +FINAL_VENDOR_BUILD_PROPERTIES := $(call uniq-pairs-by-first-component, \ + $(FINAL_VENDOR_BUILD_PROPERTIES),=) +endif # property_overrides_split_enabled + +$(INSTALLED_VENDOR_BUILD_PROP_TARGET): $(VENDOR_BUILDINFO_SH) $(intermediate_system_build_prop) + @echo Target vendor buildinfo: $@ + @mkdir -p $(dir $@) + $(hide) echo > $@ + $(hide) grep 'ro.product.first_api_level' $(intermediate_system_build_prop) >> $@ || true + $(hide) echo ro.vendor.build.date=`$(DATE_FROM_FILE)`>>$@ + $(hide) echo ro.vendor.build.date.utc=`$(DATE_FROM_FILE) +%s`>>$@ + $(hide) echo ro.vendor.build.fingerprint="$(BUILD_FINGERPRINT_FROM_FILE)">>$@ + $(hide) echo ro.vendor.build.security_patch="$(VENDOR_SECURITY_PATCH)">>$@ + $(hide) echo ro.vendor.product.cpu.abilist="$(TARGET_CPU_ABI_LIST)">>$@ + $(hide) echo ro.vendor.product.cpu.abilist32="$(TARGET_CPU_ABI_LIST_32_BIT)">>$@ + $(hide) echo ro.vendor.product.cpu.abilist64="$(TARGET_CPU_ABI_LIST_64_BIT)">>$@ + $(hide) TARGET_DEVICE="$(TARGET_DEVICE)" \ + PRODUCT_NAME="$(TARGET_PRODUCT)" \ + PRODUCT_BRAND="$(PRODUCT_BRAND)" \ + PRODUCT_MODEL="$(PRODUCT_MODEL)" \ + PRODUCT_MANUFACTURER="$(PRODUCT_MANUFACTURER)" \ + TARGET_BOOTLOADER_BOARD_NAME="$(TARGET_BOOTLOADER_BOARD_NAME)" \ + TARGET_BOARD_PLATFORM="$(TARGET_BOARD_PLATFORM)" \ + bash $(VENDOR_BUILDINFO_SH) >> $@ +ifdef property_overrides_split_enabled + $(hide) echo "#" >> $@; \ + echo "# ADDITIONAL VENDOR BUILD PROPERTIES" >> $@; \ + echo "#" >> $@; + $(hide) $(foreach line,$(FINAL_VENDOR_BUILD_PROPERTIES), \ + echo "$(line)" >> $@;) +endif # property_overrides_split_enabled + $(hide) build/make/tools/post_process_props.py $@ $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_PROPERTY_BLACKLIST) + +# ----------------------------------------------------------------- +# product build.prop +INSTALLED_PRODUCT_BUILD_PROP_TARGET := $(TARGET_OUT_PRODUCT)/build.prop +ALL_DEFAULT_INSTALLED_MODULES += $(INSTALLED_PRODUCT_BUILD_PROP_TARGET) + +FINAL_PRODUCT_PROPERTIES += \ + $(call collapse-pairs, $(PRODUCT_PRODUCT_PROPERTIES)) +FINAL_PRODUCT_PROPERTIES := $(call uniq-pairs-by-first-component, \ + $(FINAL_PRODUCT_PROPERTIES),=) + +$(INSTALLED_PRODUCT_BUILD_PROP_TARGET): + @echo Target product buildinfo: $@ + @mkdir -p $(dir $@) + $(hide) echo > $@ +ifdef BOARD_USES_PRODUCTIMAGE + $(hide) echo ro.product.build.date=`$(DATE_FROM_FILE)`>>$@ + $(hide) echo ro.product.build.date.utc=`$(DATE_FROM_FILE) +%s`>>$@ + $(hide) echo ro.product.build.fingerprint="$(BUILD_FINGERPRINT_FROM_FILE)">>$@ +endif # BOARD_USES_PRODUCTIMAGE + $(hide) echo "#" >> $@; \ + echo "# ADDITIONAL PRODUCT PROPERTIES" >> $@; \ + echo "#" >> $@; + $(hide) $(foreach line,$(FINAL_PRODUCT_PROPERTIES), \ + echo "$(line)" >> $@;) + $(hide) build/make/tools/post_process_props.py $@ + +# ---------------------------------------------------------------- + +# ----------------------------------------------------------------- +# sdk-build.prop +# +# There are certain things in build.prop that we don't want to +# ship with the sdk; remove them. + +# This must be a list of entire property keys followed by +# "=" characters, without any internal spaces. +sdk_build_prop_remove := \ + ro.build.user= \ + ro.build.host= \ + ro.product.brand= \ + ro.product.manufacturer= \ + ro.product.device= +# TODO: Remove this soon-to-be obsolete property +sdk_build_prop_remove += ro.build.product= +INSTALLED_SDK_BUILD_PROP_TARGET := $(PRODUCT_OUT)/sdk/sdk-build.prop +$(INSTALLED_SDK_BUILD_PROP_TARGET): $(INSTALLED_BUILD_PROP_TARGET) + @echo SDK buildinfo: $@ + @mkdir -p $(dir $@) + $(hide) grep -v "$(subst $(space),\|,$(strip \ + $(sdk_build_prop_remove)))" $< > $@.tmp + $(hide) for x in $(sdk_build_prop_remove); do \ + echo "$$x"generic >> $@.tmp; done + $(hide) mv $@.tmp $@ + +# ----------------------------------------------------------------- +# package stats +PACKAGE_STATS_FILE := $(PRODUCT_OUT)/package-stats.txt +PACKAGES_TO_STAT := \ + $(sort $(filter $(TARGET_OUT)/% $(TARGET_OUT_DATA)/%, \ + $(filter %.jar %.apk, $(ALL_DEFAULT_INSTALLED_MODULES)))) +$(PACKAGE_STATS_FILE): $(PACKAGES_TO_STAT) + @echo Package stats: $@ + @mkdir -p $(dir $@) + $(hide) rm -f $@ +ifeq ($(PACKAGES_TO_STAT),) +# Create empty package stats file if target builds no jar(s) or apk(s). + $(hide) touch $@ +else + $(hide) build/make/tools/dump-package-stats $^ > $@ +endif + +.PHONY: package-stats +package-stats: $(PACKAGE_STATS_FILE) + +# ----------------------------------------------------------------- +# Cert-to-package mapping. Used by the post-build signing tools. +# Use a macro to add newline to each echo command +define _apkcerts_write_line +$(hide) echo -n 'name="$(1).apk" certificate="$2" private_key="$3"' >> $5 +$(if $(4), $(hide) echo -n ' compressed="$4"' >> $5) +$(hide) echo '' >> $5 + +endef + +name := $(TARGET_PRODUCT) +ifeq ($(TARGET_BUILD_TYPE),debug) + name := $(name)_debug +endif +name := $(name)-apkcerts-$(FILE_NAME_TAG) +intermediates := \ + $(call intermediates-dir-for,PACKAGING,apkcerts) +APKCERTS_FILE := $(intermediates)/$(name).txt +# We don't need to really build all the modules. +# TODO: rebuild APKCERTS_FILE if any app change its cert. +$(APKCERTS_FILE): + @echo APK certs list: $@ + @mkdir -p $(dir $@) + @rm -f $@ + $(foreach p,$(PACKAGES),\ + $(if $(PACKAGES.$(p).EXTERNAL_KEY),\ + $(call _apkcerts_write_line,$(p),"EXTERNAL","",$(PACKAGES.$(p).COMPRESSED),$@),\ + $(call _apkcerts_write_line,$(p),$(PACKAGES.$(p).CERTIFICATE),$(PACKAGES.$(p).PRIVATE_KEY),$(PACKAGES.$(p).COMPRESSED),$@))) + # In case value of PACKAGES is empty. + $(hide) touch $@ + +.PHONY: apkcerts-list +apkcerts-list: $(APKCERTS_FILE) + +ifneq (,$(TARGET_BUILD_APPS)) + $(call dist-for-goals, apps_only, $(APKCERTS_FILE):apkcerts.txt) +endif + +# ----------------------------------------------------------------- +# build system stats +BUILD_SYSTEM_STATS := $(PRODUCT_OUT)/build_system_stats.txt +$(BUILD_SYSTEM_STATS): + @rm -f $@ + @$(foreach s,$(STATS.MODULE_TYPE),echo "modules_type_make,$(s),$(words $(STATS.MODULE_TYPE.$(s)))" >>$@;) + @$(foreach s,$(STATS.SOONG_MODULE_TYPE),echo "modules_type_soong,$(s),$(STATS.SOONG_MODULE_TYPE.$(s))" >>$@;) +$(call dist-for-goals,droidcore,$(BUILD_SYSTEM_STATS)) + +# ----------------------------------------------------------------- +# Modules ready to be converted to Soong, ordered by how many +# modules depend on them. +SOONG_CONV := $(sort $(SOONG_CONV)) +SOONG_CONV_DATA := $(call intermediates-dir-for,PACKAGING,soong_conversion)/soong_conv_data +$(SOONG_CONV_DATA): + @rm -f $@ + @$(foreach s,$(SOONG_CONV),echo "$(s),$(SOONG_CONV.$(s).TYPE),$(sort $(SOONG_CONV.$(s).PROBLEMS)),$(sort $(filter-out $(SOONG_ALREADY_CONV),$(SOONG_CONV.$(s).DEPS)))" >>$@;) + +SOONG_TO_CONVERT_SCRIPT := build/make/tools/soong_to_convert.py +SOONG_TO_CONVERT := $(PRODUCT_OUT)/soong_to_convert.txt +$(SOONG_TO_CONVERT): $(SOONG_CONV_DATA) $(SOONG_TO_CONVERT_SCRIPT) + @rm -f $@ + $(hide) $(SOONG_TO_CONVERT_SCRIPT) $< >$@ +$(call dist-for-goals,droidcore,$(SOONG_TO_CONVERT)) + +# ----------------------------------------------------------------- +# Modules use -Wno-error, or added default -Wall -Werror +WALL_WERROR := $(PRODUCT_OUT)/wall_werror.txt +$(WALL_WERROR): + @rm -f $@ + echo "# Modules using -Wno-error" >> $@ + for m in $(sort $(SOONG_MODULES_USING_WNO_ERROR) $(MODULES_USING_WNO_ERROR)); do echo $$m >> $@; done + echo "# Modules added default -Wall" >> $@ + for m in $(sort $(SOONG_MODULES_ADDED_WALL) $(MODULES_ADDED_WALL)); do echo $$m >> $@; done + +$(call dist-for-goals,droidcore,$(WALL_WERROR)) + +# ----------------------------------------------------------------- +# Modules missing profile files +PGO_PROFILE_MISSING := $(PRODUCT_OUT)/pgo_profile_file_missing.txt +$(PGO_PROFILE_MISSING): + @rm -f $@ + echo "# Modules missing PGO profile files" >> $@ + for m in $(SOONG_MODULES_MISSING_PGO_PROFILE_FILE); do echo $$m >> $@; done + +$(call dist-for-goals,droidcore,$(PGO_PROFILE_MISSING)) + +# ----------------------------------------------------------------- +# The dev key is used to sign this package, and as the key required +# for future OTA packages installed by this system. Actual product +# deliverables will be re-signed by hand. We expect this file to +# exist with the suffixes ".x509.pem" and ".pk8". +DEFAULT_KEY_CERT_PAIR := $(DEFAULT_SYSTEM_DEV_CERTIFICATE) + + +# Rules that need to be present for the all targets, even +# if they don't do anything. +.PHONY: systemimage +systemimage: + +# ----------------------------------------------------------------- + +.PHONY: event-log-tags + +# Produce an event logs tag file for everything we know about, in order +# to properly allocate numbers. Then produce a file that's filtered +# for what's going to be installed. + +all_event_log_tags_file := $(TARGET_OUT_COMMON_INTERMEDIATES)/all-event-log-tags.txt + +event_log_tags_file := $(TARGET_OUT)/etc/event-log-tags + +# Include tags from all packages that we know about +all_event_log_tags_src := \ + $(sort $(foreach m, $(ALL_MODULES), $(ALL_MODULES.$(m).EVENT_LOG_TAGS))) + +# PDK builds will already have a full list of tags that needs to get merged +# in with the ones from source +pdk_fusion_log_tags_file := $(patsubst $(PRODUCT_OUT)/%,$(_pdk_fusion_intermediates)/%,$(filter $(event_log_tags_file),$(ALL_PDK_FUSION_FILES))) + +$(all_event_log_tags_file): PRIVATE_SRC_FILES := $(all_event_log_tags_src) $(pdk_fusion_log_tags_file) +$(all_event_log_tags_file): $(all_event_log_tags_src) $(pdk_fusion_log_tags_file) $(MERGETAGS) build/make/tools/event_log_tags.py + $(hide) mkdir -p $(dir $@) + $(hide) $(MERGETAGS) -o $@ $(PRIVATE_SRC_FILES) + +# Include tags from all packages included in this product, plus all +# tags that are part of the system (ie, not in a vendor/ or device/ +# directory). +event_log_tags_src := \ + $(sort $(foreach m,\ + $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES) \ + $(call module-names-for-tag-list,user), \ + $(ALL_MODULES.$(m).EVENT_LOG_TAGS)) \ + $(filter-out vendor/% device/% out/%,$(all_event_log_tags_src))) + +$(event_log_tags_file): PRIVATE_SRC_FILES := $(event_log_tags_src) $(pdk_fusion_log_tags_file) +$(event_log_tags_file): PRIVATE_MERGED_FILE := $(all_event_log_tags_file) +$(event_log_tags_file): $(event_log_tags_src) $(all_event_log_tags_file) $(pdk_fusion_log_tags_file) $(MERGETAGS) build/make/tools/event_log_tags.py + $(hide) mkdir -p $(dir $@) + $(hide) $(MERGETAGS) -o $@ -m $(PRIVATE_MERGED_FILE) $(PRIVATE_SRC_FILES) + +event-log-tags: $(event_log_tags_file) + +ALL_DEFAULT_INSTALLED_MODULES += $(event_log_tags_file) + + +# ################################################################# +# Targets for boot/OS images +# ################################################################# +ifneq ($(strip $(TARGET_NO_BOOTLOADER)),true) + INSTALLED_BOOTLOADER_MODULE := $(PRODUCT_OUT)/bootloader + ifeq ($(strip $(TARGET_BOOTLOADER_IS_2ND)),true) + INSTALLED_2NDBOOTLOADER_TARGET := $(PRODUCT_OUT)/2ndbootloader + else + INSTALLED_2NDBOOTLOADER_TARGET := + endif +else + INSTALLED_BOOTLOADER_MODULE := + INSTALLED_2NDBOOTLOADER_TARGET := +endif # TARGET_NO_BOOTLOADER +ifneq ($(strip $(TARGET_NO_KERNEL)),true) + INSTALLED_KERNEL_TARGET := $(PRODUCT_OUT)/kernel +else + INSTALLED_KERNEL_TARGET := +endif + +# ----------------------------------------------------------------- +# the ramdisk +INTERNAL_RAMDISK_FILES := $(filter $(TARGET_ROOT_OUT)/%, \ + $(ALL_GENERATED_SOURCES) \ + $(ALL_DEFAULT_INSTALLED_MODULES)) + +BUILT_RAMDISK_TARGET := $(PRODUCT_OUT)/ramdisk.img + +# We just build this directly to the install location. +INSTALLED_RAMDISK_TARGET := $(BUILT_RAMDISK_TARGET) +$(INSTALLED_RAMDISK_TARGET): $(MKBOOTFS) $(INTERNAL_RAMDISK_FILES) | $(MINIGZIP) + $(call pretty,"Target ram disk: $@") + $(hide) $(MKBOOTFS) -d $(TARGET_OUT) $(TARGET_ROOT_OUT) | $(MINIGZIP) > $@ + +.PHONY: ramdisk-nodeps +ramdisk-nodeps: $(MKBOOTFS) | $(MINIGZIP) + @echo "make $@: ignoring dependencies" + $(hide) $(MKBOOTFS) -d $(TARGET_OUT) $(TARGET_ROOT_OUT) | $(MINIGZIP) > $(INSTALLED_RAMDISK_TARGET) + +INSTALLED_BOOTIMAGE_TARGET := $(PRODUCT_OUT)/boot.img + +ifneq ($(strip $(TARGET_NO_KERNEL)),true) + +# ----------------------------------------------------------------- +# the boot image, which is a collection of other images. +INTERNAL_BOOTIMAGE_ARGS := \ + $(addprefix --second ,$(INSTALLED_2NDBOOTLOADER_TARGET)) \ + --kernel $(INSTALLED_KERNEL_TARGET) + +ifneq ($(BOARD_BUILD_SYSTEM_ROOT_IMAGE),true) +INTERNAL_BOOTIMAGE_ARGS += --ramdisk $(INSTALLED_RAMDISK_TARGET) +endif + +INTERNAL_BOOTIMAGE_FILES := $(filter-out --%,$(INTERNAL_BOOTIMAGE_ARGS)) + +ifdef BOARD_KERNEL_BASE + INTERNAL_BOOTIMAGE_ARGS += --base $(BOARD_KERNEL_BASE) +endif + +ifdef BOARD_KERNEL_PAGESIZE + INTERNAL_BOOTIMAGE_ARGS += --pagesize $(BOARD_KERNEL_PAGESIZE) +endif + +ifeq ($(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY),true) +ifeq ($(BOARD_BUILD_SYSTEM_ROOT_IMAGE),true) +VERITY_KEYID := veritykeyid=id:`openssl x509 -in $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).x509.pem -text \ + | grep keyid | sed 's/://g' | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]' | sed 's/keyid//g'` +endif +endif + +INTERNAL_KERNEL_CMDLINE := $(strip $(BOARD_KERNEL_CMDLINE) buildvariant=$(TARGET_BUILD_VARIANT) $(VERITY_KEYID)) +ifdef INTERNAL_KERNEL_CMDLINE +INTERNAL_BOOTIMAGE_ARGS += --cmdline "$(INTERNAL_KERNEL_CMDLINE)" +endif + +INTERNAL_MKBOOTIMG_VERSION_ARGS := \ + --os_version $(PLATFORM_VERSION) \ + --os_patch_level $(PLATFORM_SECURITY_PATCH) + +# BOARD_USES_RECOVERY_AS_BOOT = true must have BOARD_BUILD_SYSTEM_ROOT_IMAGE = true. +ifeq ($(BOARD_USES_RECOVERY_AS_BOOT),true) +ifneq ($(BOARD_BUILD_SYSTEM_ROOT_IMAGE),true) + $(error BOARD_BUILD_SYSTEM_ROOT_IMAGE must be enabled for BOARD_USES_RECOVERY_AS_BOOT.) +endif +endif + +# We build recovery as boot image if BOARD_USES_RECOVERY_AS_BOOT is true. +ifneq ($(BOARD_USES_RECOVERY_AS_BOOT),true) +ifeq ($(TARGET_BOOTIMAGE_USE_EXT2),true) +$(error TARGET_BOOTIMAGE_USE_EXT2 is not supported anymore) + +else ifeq (true,$(BOARD_AVB_ENABLE)) # TARGET_BOOTIMAGE_USE_EXT2 != true + +$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(AVBTOOL) $(INTERNAL_BOOTIMAGE_FILES) $(BOARD_AVB_BOOT_KEY_PATH) + $(call pretty,"Target boot image: $@") + $(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(INTERNAL_MKBOOTIMG_VERSION_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $@ + $(hide) $(call assert-max-image-size,$@,$(call get-hash-image-max-size,$(BOARD_BOOTIMAGE_PARTITION_SIZE))) + $(hide) $(AVBTOOL) add_hash_footer \ + --image $@ \ + --partition_size $(BOARD_BOOTIMAGE_PARTITION_SIZE) \ + --partition_name boot $(INTERNAL_AVB_BOOT_SIGNING_ARGS) \ + $(BOARD_AVB_BOOT_ADD_HASH_FOOTER_ARGS) + +.PHONY: bootimage-nodeps +bootimage-nodeps: $(MKBOOTIMG) $(AVBTOOL) $(BOARD_AVB_BOOT_KEY_PATH) + @echo "make $@: ignoring dependencies" + $(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(INTERNAL_MKBOOTIMG_VERSION_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $(INSTALLED_BOOTIMAGE_TARGET) + $(hide) $(call assert-max-image-size,$(INSTALLED_BOOTIMAGE_TARGET),$(call get-hash-image-max-size,$(BOARD_BOOTIMAGE_PARTITION_SIZE))) + $(hide) $(AVBTOOL) add_hash_footer \ + --image $(INSTALLED_BOOTIMAGE_TARGET) \ + --partition_size $(BOARD_BOOTIMAGE_PARTITION_SIZE) \ + --partition_name boot $(INTERNAL_AVB_BOOT_SIGNING_ARGS) \ + $(BOARD_AVB_BOOT_ADD_HASH_FOOTER_ARGS) + +else ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_BOOT_SIGNER)) # BOARD_AVB_ENABLE != true + +$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES) $(BOOT_SIGNER) + $(call pretty,"Target boot image: $@") + $(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(INTERNAL_MKBOOTIMG_VERSION_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $@ + $(BOOT_SIGNER) /boot $@ $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).pk8 $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).x509.pem $@ + $(hide) $(call assert-max-image-size,$@,$(BOARD_BOOTIMAGE_PARTITION_SIZE)) + +.PHONY: bootimage-nodeps +bootimage-nodeps: $(MKBOOTIMG) $(BOOT_SIGNER) + @echo "make $@: ignoring dependencies" + $(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(INTERNAL_MKBOOTIMG_VERSION_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $(INSTALLED_BOOTIMAGE_TARGET) + $(BOOT_SIGNER) /boot $(INSTALLED_BOOTIMAGE_TARGET) $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).pk8 $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).x509.pem $(INSTALLED_BOOTIMAGE_TARGET) + $(hide) $(call assert-max-image-size,$(INSTALLED_BOOTIMAGE_TARGET),$(BOARD_BOOTIMAGE_PARTITION_SIZE)) + +else ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT)) # PRODUCT_SUPPORTS_BOOT_SIGNER != true + +$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES) $(VBOOT_SIGNER) $(FUTILITY) + $(call pretty,"Target boot image: $@") + $(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(INTERNAL_MKBOOTIMG_VERSION_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $@.unsigned + $(VBOOT_SIGNER) $(FUTILITY) $@.unsigned $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_KEY).vbpubk $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_KEY).vbprivk $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_SUBKEY).vbprivk $@.keyblock $@ + $(hide) $(call assert-max-image-size,$@,$(BOARD_BOOTIMAGE_PARTITION_SIZE)) + +.PHONY: bootimage-nodeps +bootimage-nodeps: $(MKBOOTIMG) $(VBOOT_SIGNER) $(FUTILITY) + @echo "make $@: ignoring dependencies" + $(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(INTERNAL_MKBOOTIMG_VERSION_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $(INSTALLED_BOOTIMAGE_TARGET).unsigned + $(VBOOT_SIGNER) $(FUTILITY) $(INSTALLED_BOOTIMAGE_TARGET).unsigned $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_KEY).vbpubk $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_KEY).vbprivk $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_SUBKEY).vbprivk $(INSTALLED_BOOTIMAGE_TARGET).keyblock $(INSTALLED_BOOTIMAGE_TARGET) + $(hide) $(call assert-max-image-size,$(INSTALLED_BOOTIMAGE_TARGET),$(BOARD_BOOTIMAGE_PARTITION_SIZE)) + +else # PRODUCT_SUPPORTS_VBOOT != true + +$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_FILES) + $(call pretty,"Target boot image: $@") + $(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(INTERNAL_MKBOOTIMG_VERSION_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $@ + $(hide) $(call assert-max-image-size,$@,$(BOARD_BOOTIMAGE_PARTITION_SIZE)) + +.PHONY: bootimage-nodeps +bootimage-nodeps: $(MKBOOTIMG) + @echo "make $@: ignoring dependencies" + $(hide) $(MKBOOTIMG) $(INTERNAL_BOOTIMAGE_ARGS) $(INTERNAL_MKBOOTIMG_VERSION_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $(INSTALLED_BOOTIMAGE_TARGET) + $(hide) $(call assert-max-image-size,$(INSTALLED_BOOTIMAGE_TARGET),$(BOARD_BOOTIMAGE_PARTITION_SIZE)) + +endif # TARGET_BOOTIMAGE_USE_EXT2 +endif # BOARD_USES_RECOVERY_AS_BOOT + +else # TARGET_NO_KERNEL +ifdef BOARD_PREBUILT_BOOTIMAGE +ifneq ($(BOARD_BUILD_SYSTEM_ROOT_IMAGE),true) +# Remove when b/63676296 is resolved. +$(error Prebuilt bootimage is only supported for AB targets) +endif +$(eval $(call copy-one-file,$(BOARD_PREBUILT_BOOTIMAGE),$(INSTALLED_BOOTIMAGE_TARGET))) +else +INTERNAL_KERNEL_CMDLINE := $(strip $(BOARD_KERNEL_CMDLINE)) +# HACK: The top-level targets depend on the bootimage. Not all targets +# can produce a bootimage, though, and emulator targets need the ramdisk +# instead. Fake it out by calling the ramdisk the bootimage. +# TODO: make the emulator use bootimages, and make mkbootimg accept +# kernel-less inputs. +INSTALLED_BOOTIMAGE_TARGET := $(INSTALLED_RAMDISK_TARGET) +endif +endif + +# ----------------------------------------------------------------- +# NOTICE files +# +# We are required to publish the licenses for all code under BSD, GPL and +# Apache licenses (and possibly other more exotic ones as well). We err on the +# side of caution, so the licenses for other third-party code are included here +# too. +# +# This needs to be before the systemimage rules, because it adds to +# ALL_DEFAULT_INSTALLED_MODULES, which those use to pick which files +# go into the systemimage. + +.PHONY: notice_files + +# Create the rule to combine the files into text and html/xml forms +# $(1) - xml_excluded_vendor|xml_vendor|html +# $(2) - Plain text output file +# $(3) - HTML/XML output file +# $(4) - File title +# $(5) - Directory to use. Notice files are all $(4)/src. Other +# directories in there will be used for scratch +# $(6) - Dependencies for the output files +# +# The algorithm here is that we go collect a hash for each of the notice +# files and write the names of the files that match that hash. Then +# to generate the real files, we go print out all of the files and their +# hashes. +# +# These rules are fairly complex, so they depend on this makefile so if +# it changes, they'll run again. +# +# TODO: We could clean this up so that we just record the locations of the +# original notice files instead of making rules to copy them somwehere. +# Then we could traverse that without quite as much bash drama. +define combine-notice-files +$(2) $(3): PRIVATE_MESSAGE := $(4) +$(2) $(3): PRIVATE_DIR := $(5) +$(2) : $(3) +$(3) : $(6) $(BUILD_SYSTEM)/Makefile build/make/tools/generate-notice-files.py + build/make/tools/generate-notice-files.py --text-output $(2) \ + $(if $(filter $(1),xml_excluded_vendor),-e vendor --xml-output, \ + $(if $(filter $(1),xml_vendor),-i vendor --xml-output, \ + --html-output)) $(3) \ + -t $$(PRIVATE_MESSAGE) -s $$(PRIVATE_DIR)/src +notice_files: $(2) $(3) +endef + +# TODO These intermediate NOTICE.txt/NOTICE.html files should go into +# TARGET_OUT_NOTICE_FILES now that the notice files are gathered from +# the src subdirectory. + +target_notice_file_txt := $(TARGET_OUT_INTERMEDIATES)/NOTICE.txt +target_notice_file_html_or_xml := $(TARGET_OUT_INTERMEDIATES)/NOTICE.html +target_notice_file_html_or_xml_gz := $(TARGET_OUT_INTERMEDIATES)/NOTICE.html.gz +installed_notice_html_or_xml_gz := $(TARGET_OUT)/etc/NOTICE.html.gz +tools_notice_file_txt := $(HOST_OUT_INTERMEDIATES)/NOTICE.txt +tools_notice_file_html := $(HOST_OUT_INTERMEDIATES)/NOTICE.html + +# TODO(b/69865032): Make PRODUCT_NOTICE_SPLIT the default behavior. +ifeq ($(PRODUCT_NOTICE_SPLIT),true) +target_notice_file_html_or_xml := $(TARGET_OUT_INTERMEDIATES)/NOTICE.xml +target_notice_file_html_or_xml_gz := $(TARGET_OUT_INTERMEDIATES)/NOTICE.xml.gz +installed_notice_html_or_xml_gz := $(TARGET_OUT)/etc/NOTICE.xml.gz + +target_vendor_notice_file_txt := $(TARGET_OUT_INTERMEDIATES)/NOTICE_VENDOR.txt +target_vendor_notice_file_xml := $(TARGET_OUT_INTERMEDIATES)/NOTICE_VENDOR.xml +target_vendor_notice_file_xml_gz := $(TARGET_OUT_INTERMEDIATES)/NOTICE_VENDOR.xml.gz +installed_vendor_notice_xml_gz := $(TARGET_OUT_VENDOR)/etc/NOTICE.xml.gz +endif + +ifndef TARGET_BUILD_APPS +kernel_notice_file := $(TARGET_OUT_NOTICE_FILES)/src/kernel.txt +winpthreads_notice_file := $(TARGET_OUT_NOTICE_FILES)/src/winpthreads.txt +pdk_fusion_notice_files := $(filter $(TARGET_OUT_NOTICE_FILES)/%, $(ALL_PDK_FUSION_FILES)) + +ifdef target_vendor_notice_file_xml_gz +$(eval $(call combine-notice-files, xml_excluded_vendor, \ + $(target_notice_file_txt), \ + $(target_notice_file_html_or_xml), \ + "Notices for files contained in the filesystem images in this directory:", \ + $(TARGET_OUT_NOTICE_FILES), \ + $(ALL_DEFAULT_INSTALLED_MODULES) $(kernel_notice_file) $(pdk_fusion_notice_files))) +$(eval $(call combine-notice-files, xml_vendor, \ + $(target_vendor_notice_file_txt), \ + $(target_vendor_notice_file_xml), \ + "Notices for files contained in the vendor filesystem image in this directory:", \ + $(TARGET_OUT_NOTICE_FILES), \ + $(target_notice_file_html_or_xml))) +else +$(eval $(call combine-notice-files, html, \ + $(target_notice_file_txt), \ + $(target_notice_file_html_or_xml), \ + "Notices for files contained in the filesystem images in this directory:", \ + $(TARGET_OUT_NOTICE_FILES), \ + $(ALL_DEFAULT_INSTALLED_MODULES) $(kernel_notice_file) $(pdk_fusion_notice_files))) +endif + +$(eval $(call combine-notice-files, html, \ + $(tools_notice_file_txt), \ + $(tools_notice_file_html), \ + "Notices for files contained in the tools directory:", \ + $(HOST_OUT_NOTICE_FILES), \ + $(ALL_DEFAULT_INSTALLED_MODULES) \ + $(winpthreads_notice_file))) + +# Install the html file at /system/etc/NOTICE.html.gz. +# This is not ideal, but this is very late in the game, after a lot of +# the module processing has already been done -- in fact, we used the +# fact that all that has been done to get the list of modules that we +# need notice files for. +$(target_notice_file_html_or_xml_gz): $(target_notice_file_html_or_xml) | $(MINIGZIP) + $(hide) $(MINIGZIP) -9 < $< > $@ +$(installed_notice_html_or_xml_gz): $(target_notice_file_html_or_xml_gz) + $(copy-file-to-target) + +ifdef target_vendor_notice_file_xml_gz +# Install the vendor html file at /vendor/etc/NOTICE.xml.gz. +$(target_vendor_notice_file_xml_gz): $(target_vendor_notice_file_xml) | $(MINIGZIP) + $(hide) $(MINIGZIP) -9 < $< > $@ +$(installed_vendor_notice_xml_gz): $(target_vendor_notice_file_xml_gz) + $(copy-file-to-target) +endif + +# if we've been run my mm, mmm, etc, don't reinstall this every time +ifeq ($(ONE_SHOT_MAKEFILE),) + ALL_DEFAULT_INSTALLED_MODULES += $(installed_notice_html_or_xml_gz) + ifdef target_vendor_notice_file_xml_gz + ALL_DEFAULT_INSTALLED_MODULES += $(installed_vendor_notice_xml_gz) + endif +endif +endif # TARGET_BUILD_APPS + +# The kernel isn't really a module, so to get its module file in there, we +# make the target NOTICE files depend on this particular file too, which will +# then be in the right directory for the find in combine-notice-files to work. +$(kernel_notice_file): \ + $(BUILD_SYSTEM)/LINUX_KERNEL_COPYING \ + | $(ACP) + @echo Copying: $@ + $(hide) mkdir -p $(dir $@) + $(hide) $(ACP) $< $@ + +$(winpthreads_notice_file): \ + $(BUILD_SYSTEM)/WINPTHREADS_COPYING \ + | $(ACP) + @echo Copying: $@ + $(hide) mkdir -p $(dir $@) + $(hide) $(ACP) $< $@ + +# ----------------------------------------------------------------- +# Build a keystore with the authorized keys in it, used to verify the +# authenticity of downloaded OTA packages. +# +# This rule adds to ALL_DEFAULT_INSTALLED_MODULES, so it needs to come +# before the rules that use that variable to build the image. +ALL_DEFAULT_INSTALLED_MODULES += $(TARGET_OUT_ETC)/security/otacerts.zip +$(TARGET_OUT_ETC)/security/otacerts.zip: KEY_CERT_PAIR := $(DEFAULT_KEY_CERT_PAIR) +$(TARGET_OUT_ETC)/security/otacerts.zip: $(addsuffix .x509.pem,$(DEFAULT_KEY_CERT_PAIR)) | $(ZIPTIME) + $(hide) rm -f $@ + $(hide) mkdir -p $(dir $@) + $(hide) zip -qjX $@ $< + $(remove-timestamps-from-package) + +# Carry the public key for update_engine if it's a non-IoT target that +# uses the AB updater. We use the same key as otacerts but in RSA public key +# format. +ifeq ($(AB_OTA_UPDATER),true) +ifneq ($(PRODUCT_IOT),true) +ALL_DEFAULT_INSTALLED_MODULES += $(TARGET_OUT_ETC)/update_engine/update-payload-key.pub.pem +$(TARGET_OUT_ETC)/update_engine/update-payload-key.pub.pem: $(addsuffix .x509.pem,$(DEFAULT_KEY_CERT_PAIR)) + $(hide) rm -f $@ + $(hide) mkdir -p $(dir $@) + $(hide) openssl x509 -pubkey -noout -in $< > $@ + +ALL_DEFAULT_INSTALLED_MODULES += $(TARGET_RECOVERY_ROOT_OUT)/etc/update_engine/update-payload-key.pub.pem +$(TARGET_RECOVERY_ROOT_OUT)/etc/update_engine/update-payload-key.pub.pem: $(TARGET_OUT_ETC)/update_engine/update-payload-key.pub.pem + $(hide) cp -f $< $@ +endif +endif + +.PHONY: otacerts +otacerts: $(TARGET_OUT_ETC)/security/otacerts.zip + + +# ################################################################# +# Targets for user images +# ################################################################# + +INTERNAL_USERIMAGES_EXT_VARIANT := +ifeq ($(TARGET_USERIMAGES_USE_EXT2),true) +INTERNAL_USERIMAGES_USE_EXT := true +INTERNAL_USERIMAGES_EXT_VARIANT := ext2 +else +ifeq ($(TARGET_USERIMAGES_USE_EXT3),true) +INTERNAL_USERIMAGES_USE_EXT := true +INTERNAL_USERIMAGES_EXT_VARIANT := ext3 +else +ifeq ($(TARGET_USERIMAGES_USE_EXT4),true) +INTERNAL_USERIMAGES_USE_EXT := true +INTERNAL_USERIMAGES_EXT_VARIANT := ext4 +endif +endif +endif + +# These options tell the recovery updater/installer how to mount the partitions writebale. +# =[|]... +# fstype_opts := [,]... +# opt := [=] +# The following worked on Nexus devices with Kernel 3.1, 3.4, 3.10 +DEFAULT_TARGET_RECOVERY_FSTYPE_MOUNT_OPTIONS := ext4=max_batch_time=0,commit=1,data=ordered,barrier=1,errors=panic,nodelalloc + +ifneq (true,$(TARGET_USERIMAGES_SPARSE_EXT_DISABLED)) + INTERNAL_USERIMAGES_SPARSE_EXT_FLAG := -s +endif + +ifeq ($(INTERNAL_USERIMAGES_USE_EXT),true) +INTERNAL_USERIMAGES_DEPS := $(SIMG2IMG) +INTERNAL_USERIMAGES_DEPS += $(MKEXTUSERIMG) $(MAKE_EXT4FS) $(E2FSCK) +ifeq ($(TARGET_USERIMAGES_USE_F2FS),true) +INTERNAL_USERIMAGES_DEPS += $(MKF2FSUSERIMG) $(MAKE_F2FS) +endif +endif + +ifeq ($(BOARD_AVB_ENABLE),true) +INTERNAL_USERIMAGES_DEPS += $(AVBTOOL) +endif + +ifneq (true,$(TARGET_USERIMAGES_SPARSE_SQUASHFS_DISABLED)) + INTERNAL_USERIMAGES_SPARSE_SQUASHFS_FLAG := -s +endif +ifneq ($(filter $(BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE) $(BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE) $(BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE),squashfs),) +INTERNAL_USERIMAGES_DEPS += $(MAKE_SQUASHFS) $(MKSQUASHFSUSERIMG) $(IMG2SIMG) +endif + +INTERNAL_USERIMAGES_BINARY_PATHS := $(sort $(dir $(INTERNAL_USERIMAGES_DEPS))) + +ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY)) +INTERNAL_USERIMAGES_DEPS += $(BUILD_VERITY_TREE) $(APPEND2SIMG) $(VERITY_SIGNER) +ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY_FEC)) +INTERNAL_USERIMAGES_DEPS += $(FEC) +endif +endif + +SELINUX_FC := $(call intermediates-dir-for,ETC,file_contexts.bin)/file_contexts.bin +INTERNAL_USERIMAGES_DEPS += $(SELINUX_FC) + +INTERNAL_USERIMAGES_DEPS += $(BLK_ALLOC_TO_BASE_FS) + +ifeq ($(INTERNAL_USERIMAGES_USE_EXT),true) +INTERNAL_USERIMAGES_DEPS += $(MKE2FS_CONF) +endif + +# $(1): the path of the output dictionary file +# $(2): additional "key=value" pairs to append to the dictionary file. +define generate-userimage-prop-dictionary +$(hide) echo "ext_mkuserimg=$(notdir $(MKEXTUSERIMG))" >> $(1) +$(if $(INTERNAL_USERIMAGES_EXT_VARIANT),$(hide) echo "fs_type=$(INTERNAL_USERIMAGES_EXT_VARIANT)" >> $(1)) +$(if $(BOARD_SYSTEMIMAGE_PARTITION_SIZE),$(hide) echo "system_size=$(BOARD_SYSTEMIMAGE_PARTITION_SIZE)" >> $(1)) +$(if $(BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE),$(hide) echo "system_fs_type=$(BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE)" >> $(1)) +$(if $(BOARD_SYSTEMIMAGE_EXTFS_INODE_COUNT),$(hide) echo "system_extfs_inode_count=$(BOARD_SYSTEMIMAGE_EXTFS_INODE_COUNT)" >> $(1)) +$(if $(BOARD_SYSTEMIMAGE_EXTFS_RSV_PCT),$(hide) echo "system_extfs_rsv_pct=$(BOARD_SYSTEMIMAGE_EXTFS_RSV_PCT)" >> $(1)) +$(if $(BOARD_SYSTEMIMAGE_JOURNAL_SIZE),$(hide) echo "system_journal_size=$(BOARD_SYSTEMIMAGE_JOURNAL_SIZE)" >> $(1)) +$(if $(BOARD_EXT4_SHARE_DUP_BLOCKS),$(hide) echo "ext4_share_dup_blocks=$(BOARD_EXT4_SHARE_DUP_BLOCKS)" >> $(1)) +$(if $(BOARD_SYSTEMIMAGE_SQUASHFS_COMPRESSOR),$(hide) echo "system_squashfs_compressor=$(BOARD_SYSTEMIMAGE_SQUASHFS_COMPRESSOR)" >> $(1)) +$(if $(BOARD_SYSTEMIMAGE_SQUASHFS_COMPRESSOR_OPT),$(hide) echo "system_squashfs_compressor_opt=$(BOARD_SYSTEMIMAGE_SQUASHFS_COMPRESSOR_OPT)" >> $(1)) +$(if $(BOARD_SYSTEMIMAGE_SQUASHFS_BLOCK_SIZE),$(hide) echo "system_squashfs_block_size=$(BOARD_SYSTEMIMAGE_SQUASHFS_BLOCK_SIZE)" >> $(1)) +$(if $(BOARD_SYSTEMIMAGE_SQUASHFS_DISABLE_4K_ALIGN),$(hide) echo "system_squashfs_disable_4k_align=$(BOARD_SYSTEMIMAGE_SQUASHFS_DISABLE_4K_ALIGN)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_BASE_FS_PATH),$(hide) echo "system_base_fs_file=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_BASE_FS_PATH)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_HEADROOM),$(hide) echo "system_headroom=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_HEADROOM)" >> $(1)) +$(if $(BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE),$(hide) echo "userdata_fs_type=$(BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE)" >> $(1)) +$(if $(BOARD_USERDATAIMAGE_PARTITION_SIZE),$(hide) echo "userdata_size=$(BOARD_USERDATAIMAGE_PARTITION_SIZE)" >> $(1)) +$(if $(BOARD_FLASH_LOGICAL_BLOCK_SIZE), $(hide) echo "flash_logical_block_size=$(BOARD_FLASH_LOGICAL_BLOCK_SIZE)" >> $(1)) +$(if $(BOARD_FLASH_ERASE_BLOCK_SIZE), $(hide) echo "flash_erase_block_size=$(BOARD_FLASH_ERASE_BLOCK_SIZE)" >> $(1)) +$(if $(BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE),$(hide) echo "cache_fs_type=$(BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE)" >> $(1)) +$(if $(BOARD_CACHEIMAGE_PARTITION_SIZE),$(hide) echo "cache_size=$(BOARD_CACHEIMAGE_PARTITION_SIZE)" >> $(1)) +$(if $(BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE),$(hide) echo "vendor_fs_type=$(BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE)" >> $(1)) +$(if $(BOARD_VENDORIMAGE_EXTFS_INODE_COUNT),$(hide) echo "vendor_extfs_inode_count=$(BOARD_VENDORIMAGE_EXTFS_INODE_COUNT)" >> $(1)) +$(if $(BOARD_VENDORIMAGE_EXTFS_RSV_PCT),$(hide) echo "vendor_extfs_rsv_pct=$(BOARD_VENDORIMAGE_EXTFS_RSV_PCT)" >> $(1)) +$(if $(BOARD_VENDORIMAGE_PARTITION_SIZE),$(hide) echo "vendor_size=$(BOARD_VENDORIMAGE_PARTITION_SIZE)" >> $(1)) +$(if $(BOARD_VENDORIMAGE_JOURNAL_SIZE),$(hide) echo "vendor_journal_size=$(BOARD_VENDORIMAGE_JOURNAL_SIZE)" >> $(1)) +$(if $(BOARD_VENDORIMAGE_SQUASHFS_COMPRESSOR),$(hide) echo "vendor_squashfs_compressor=$(BOARD_VENDORIMAGE_SQUASHFS_COMPRESSOR)" >> $(1)) +$(if $(BOARD_VENDORIMAGE_SQUASHFS_COMPRESSOR_OPT),$(hide) echo "vendor_squashfs_compressor_opt=$(BOARD_VENDORIMAGE_SQUASHFS_COMPRESSOR_OPT)" >> $(1)) +$(if $(BOARD_VENDORIMAGE_SQUASHFS_BLOCK_SIZE),$(hide) echo "vendor_squashfs_block_size=$(BOARD_VENDORIMAGE_SQUASHFS_BLOCK_SIZE)" >> $(1)) +$(if $(BOARD_VENDORIMAGE_SQUASHFS_DISABLE_4K_ALIGN),$(hide) echo "vendor_squashfs_disable_4k_align=$(BOARD_VENDORIMAGE_SQUASHFS_DISABLE_4K_ALIGN)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_BASE_FS_PATH),$(hide) echo "vendor_base_fs_file=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_BASE_FS_PATH)" >> $(1)) +$(if $(BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE),$(hide) echo "product_fs_type=$(BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE)" >> $(1)) +$(if $(BOARD_PRODUCTIMAGE_EXTFS_INODE_COUNT),$(hide) echo "product_extfs_inode_count=$(BOARD_PRODUCTIMAGE_EXTFS_INODE_COUNT)" >> $(1)) +$(if $(BOARD_PRODUCTIMAGE_EXTFS_RSV_PCT),$(hide) echo "product_extfs_rsv_pct=$(BOARD_PRODUCTIMAGE_EXTFS_RSV_PCT)" >> $(1)) +$(if $(BOARD_PRODUCTIMAGE_PARTITION_SIZE),$(hide) echo "product_size=$(BOARD_PRODUCTIMAGE_PARTITION_SIZE)" >> $(1)) +$(if $(BOARD_PRODUCTIMAGE_JOURNAL_SIZE),$(hide) echo "product_journal_size=$(BOARD_PRODUCTIMAGE_JOURNAL_SIZE)" >> $(1)) +$(if $(BOARD_PRODUCTIMAGE_SQUASHFS_COMPRESSOR),$(hide) echo "product_squashfs_compressor=$(BOARD_PRODUCTIMAGE_SQUASHFS_COMPRESSOR)" >> $(1)) +$(if $(BOARD_PRODUCTIMAGE_SQUASHFS_COMPRESSOR_OPT),$(hide) echo "product_squashfs_compressor_opt=$(BOARD_PRODUCTIMAGE_SQUASHFS_COMPRESSOR_OPT)" >> $(1)) +$(if $(BOARD_PRODUCTIMAGE_SQUASHFS_BLOCK_SIZE),$(hide) echo "product_squashfs_block_size=$(BOARD_PRODUCTIMAGE_SQUASHFS_BLOCK_SIZE)" >> $(1)) +$(if $(BOARD_PRODUCTIMAGE_SQUASHFS_DISABLE_4K_ALIGN),$(hide) echo "product_squashfs_disable_4k_align=$(BOARD_PRODUCTIMAGE_SQUASHFS_DISABLE_4K_ALIGN)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_BASE_FS_PATH),$(hide) echo "product_base_fs_file=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_BASE_FS_PATH)" >> $(1)) +$(if $(BOARD_OEMIMAGE_PARTITION_SIZE),$(hide) echo "oem_size=$(BOARD_OEMIMAGE_PARTITION_SIZE)" >> $(1)) +$(if $(BOARD_OEMIMAGE_JOURNAL_SIZE),$(hide) echo "oem_journal_size=$(BOARD_OEMIMAGE_JOURNAL_SIZE)" >> $(1)) +$(if $(BOARD_OEMIMAGE_EXTFS_INODE_COUNT),$(hide) echo "oem_extfs_inode_count=$(BOARD_OEMIMAGE_EXTFS_INODE_COUNT)" >> $(1)) +$(if $(BOARD_OEMIMAGE_EXTFS_RSV_PCT),$(hide) echo "oem_extfs_rsv_pct=$(BOARD_OEMIMAGE_EXTFS_RSV_PCT)" >> $(1)) +$(if $(INTERNAL_USERIMAGES_SPARSE_EXT_FLAG),$(hide) echo "extfs_sparse_flag=$(INTERNAL_USERIMAGES_SPARSE_EXT_FLAG)" >> $(1)) +$(if $(INTERNAL_USERIMAGES_SPARSE_SQUASHFS_FLAG),$(hide) echo "squashfs_sparse_flag=$(INTERNAL_USERIMAGES_SPARSE_SQUASHFS_FLAG)" >> $(1)) +$(hide) echo "selinux_fc=$(SELINUX_FC)" >> $(1) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_BOOT_SIGNER),$(hide) echo "boot_signer=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_BOOT_SIGNER)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY),$(hide) echo "verity=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY),$(hide) echo "verity_key=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY),$(hide) echo "verity_signer_cmd=$(notdir $(VERITY_SIGNER))" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY_FEC),$(hide) echo "verity_fec=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VERITY_FEC)" >> $(1)) +$(if $(filter eng, $(TARGET_BUILD_VARIANT)),$(hide) echo "verity_disable=true" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_VERITY_PARTITION),$(hide) echo "system_verity_block_device=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_VERITY_PARTITION)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_VERITY_PARTITION),$(hide) echo "vendor_verity_block_device=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_VERITY_PARTITION)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_VERITY_PARTITION),$(hide) echo "product_verity_block_device=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_VERITY_PARTITION)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT),$(hide) echo "vboot=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT),$(hide) echo "vboot_key=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_KEY)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT),$(hide) echo "vboot_subkey=$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_SUBKEY)" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT),$(hide) echo "futility=$(notdir $(FUTILITY))" >> $(1)) +$(if $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT),$(hide) echo "vboot_signer_cmd=$(VBOOT_SIGNER)" >> $(1)) +$(if $(BOARD_AVB_ENABLE),$(hide) echo "avb_avbtool=$(notdir $(AVBTOOL))" >> $(1)) +$(if $(BOARD_AVB_ENABLE),$(hide) echo "avb_system_hashtree_enable=$(BOARD_AVB_ENABLE)" >> $(1)) +$(if $(BOARD_AVB_ENABLE),$(hide) echo "avb_system_add_hashtree_footer_args=$(BOARD_AVB_SYSTEM_ADD_HASHTREE_FOOTER_ARGS)" >> $(1)) +$(if $(BOARD_AVB_ENABLE),\ + $(if $(BOARD_AVB_SYSTEM_KEY_PATH),\ + $(hide) echo "avb_system_key_path=$(BOARD_AVB_SYSTEM_KEY_PATH)" >> $(1) + $(hide) echo "avb_system_algorithm=$(BOARD_AVB_SYSTEM_ALGORITHM)" >> $(1) + $(hide) echo "avb_system_rollback_index_location=$(BOARD_AVB_SYSTEM_ROLLBACK_INDEX_LOCATION)" >> $(1))) +$(if $(BOARD_AVB_ENABLE),$(hide) echo "avb_vendor_hashtree_enable=$(BOARD_AVB_ENABLE)" >> $(1)) +$(if $(BOARD_AVB_ENABLE),$(hide) echo "avb_vendor_add_hashtree_footer_args=$(BOARD_AVB_VENDOR_ADD_HASHTREE_FOOTER_ARGS)" >> $(1)) +$(if $(BOARD_AVB_ENABLE),\ + $(if $(BOARD_AVB_VENDOR_KEY_PATH),\ + $(hide) echo "avb_vendor_key_path=$(BOARD_AVB_VENDOR_KEY_PATH)" >> $(1) + $(hide) echo "avb_vendor_algorithm=$(BOARD_AVB_VENDOR_ALGORITHM)" >> $(1) + $(hide) echo "avb_vendor_rollback_index_location=$(BOARD_AVB_VENDOR_ROLLBACK_INDEX_LOCATION)" >> $(1))) +$(if $(BOARD_AVB_ENABLE),$(hide) echo "avb_product_hashtree_enable=$(BOARD_AVB_ENABLE)" >> $(1)) +$(if $(BOARD_AVB_ENABLE),$(hide) echo "avb_product_add_hashtree_footer_args=$(BOARD_AVB_PRODUCT_ADD_HASHTREE_FOOTER_ARGS)" >> $(1)) +$(if $(BOARD_AVB_ENABLE),\ + $(if $(BOARD_AVB_PRODUCT_KEY_PATH),\ + $(hide) echo "avb_product_key_path=$(BOARD_AVB_PRODUCT_KEY_PATH)" >> $(1) + $(hide) echo "avb_product_algorithm=$(BOARD_AVB_PRODUCT_ALGORITHM)" >> $(1) + $(hide) echo "avb_product_rollback_index_location=$(BOARD_AVB_PRODUCT_ROLLBACK_INDEX_LOCATION)" >> $(1))) +$(if $(filter true,$(BOARD_USES_RECOVERY_AS_BOOT)),\ + $(hide) echo "recovery_as_boot=true" >> $(1)) +$(if $(filter true,$(BOARD_BUILD_SYSTEM_ROOT_IMAGE)),\ + $(hide) echo "system_root_image=true" >> $(1);\ + echo "ramdisk_dir=$(TARGET_ROOT_OUT)" >> $(1)) +$(if $(2),$(hide) $(foreach kv,$(2),echo "$(kv)" >> $(1);)) +endef + +# $(1): modules list +# $(2): output dir +# $(3): mount point +# $(4): staging dir +# Depmod requires a well-formed kernel version so 0.0 is used as a placeholder. +define build-image-kernel-modules + $(hide) rm -rf $(2)/lib/modules + $(hide) mkdir -p $(2)/lib/modules + $(hide) cp $(1) $(2)/lib/modules/ + $(hide) rm -rf $(4) + $(hide) mkdir -p $(4)/lib/modules/0.0/$(3)lib/modules + $(hide) cp $(1) $(4)/lib/modules/0.0/$(3)lib/modules + $(hide) $(DEPMOD) -b $(4) 0.0 + $(hide) sed -e 's/\(.*modules.*\):/\/\1:/g' -e 's/ \([^ ]*modules[^ ]*\)/ \/\1/g' $(4)/lib/modules/0.0/modules.dep > $(2)/lib/modules/modules.dep + $(hide) cp $(4)/lib/modules/0.0/modules.alias $(2)/lib/modules +endef + +# ----------------------------------------------------------------- +# Recovery image + +# Recovery image exists if we are building recovery, or building recovery as boot. +ifneq (,$(INSTALLED_RECOVERYIMAGE_TARGET)$(filter true,$(BOARD_USES_RECOVERY_AS_BOOT))) + +INTERNAL_RECOVERYIMAGE_FILES := $(filter $(TARGET_RECOVERY_OUT)/%, \ + $(ALL_DEFAULT_INSTALLED_MODULES)) + +recovery_initrc := $(call include-path-for, recovery)/etc/init.rc +recovery_sepolicy := \ + $(TARGET_RECOVERY_ROOT_OUT)/sepolicy \ + $(TARGET_RECOVERY_ROOT_OUT)/plat_file_contexts \ + $(TARGET_RECOVERY_ROOT_OUT)/vendor_file_contexts \ + $(TARGET_RECOVERY_ROOT_OUT)/plat_property_contexts \ + $(TARGET_RECOVERY_ROOT_OUT)/vendor_property_contexts + +ifdef BOARD_ODM_SEPOLICY_DIRS +recovery_sepolicy += \ + $(TARGET_RECOVERY_ROOT_OUT)/odm_file_contexts \ + $(TARGET_RECOVERY_ROOT_OUT)/odm_property_contexts +endif + +# Passed into rsync from non-recovery root to recovery root, to avoid overwriting recovery-specific +# SELinux files +IGNORE_RECOVERY_SEPOLICY := $(patsubst $(TARGET_RECOVERY_OUT)/%,--exclude=/%,$(recovery_sepolicy)) + +recovery_kernel := $(INSTALLED_KERNEL_TARGET) # same as a non-recovery system +recovery_ramdisk := $(PRODUCT_OUT)/ramdisk-recovery.img +recovery_build_props := $(intermediate_system_build_prop) +ifdef property_overrides_split_enabled +recovery_build_props += $(INSTALLED_VENDOR_BUILD_PROP_TARGET) +endif +ifdef BOARD_USES_PRODUCTIMAGE +recovery_build_props += $(INSTALLED_PRODUCT_BUILD_PROP_TARGET) +endif +recovery_resources_common := $(call include-path-for, recovery)/res + +# Set recovery_density to the density bucket of the device. +recovery_density := unknown +ifneq (,$(PRODUCT_AAPT_PREF_CONFIG)) +# If PRODUCT_AAPT_PREF_CONFIG includes a dpi bucket, then use that value. +recovery_density := $(filter %dpi,$(PRODUCT_AAPT_PREF_CONFIG)) +else +# Otherwise, use the default medium density. +recovery_densities := mdpi +endif + +ifneq (,$(wildcard $(recovery_resources_common)-$(recovery_density))) +recovery_resources_common := $(recovery_resources_common)-$(recovery_density) +else +recovery_resources_common := $(recovery_resources_common)-xhdpi +endif + +# Select the 18x32 font on high-density devices (xhdpi and up); and +# the 12x22 font on other devices. Note that the font selected here +# can be overridden for a particular device by putting a font.png in +# its private recovery resources. + +ifneq (,$(filter xxxhdpi 560dpi xxhdpi 400dpi xhdpi,$(recovery_density))) +recovery_font := $(call include-path-for, recovery)/fonts/18x32.png +else +recovery_font := $(call include-path-for, recovery)/fonts/12x22.png +endif + +ifndef TARGET_PRIVATE_RES_DIRS +TARGET_PRIVATE_RES_DIRS := $(wildcard $(TARGET_DEVICE_DIR)/recovery/res) +endif +recovery_resource_deps := $(shell find $(recovery_resources_common) \ + $(TARGET_PRIVATE_RES_DIRS) -type f) +ifdef TARGET_RECOVERY_FSTAB +recovery_fstab := $(TARGET_RECOVERY_FSTAB) +else +recovery_fstab := $(strip $(wildcard $(TARGET_DEVICE_DIR)/recovery.fstab)) +endif +ifdef TARGET_RECOVERY_WIPE +recovery_wipe := $(TARGET_RECOVERY_WIPE) +else +recovery_wipe := +endif + +# Traditionally with non-A/B OTA we have: +# boot.img + recovery-from-boot.p + recovery-resource.dat = recovery.img. +# recovery-resource.dat is needed only if we carry an imgdiff patch of the boot and recovery images +# and invoke install-recovery.sh on the first boot post an OTA update. +# +# We no longer need that if one of the following conditions holds: +# a) We carry a full copy of the recovery image - no patching needed +# (BOARD_USES_FULL_RECOVERY_IMAGE = true); +# b) We build a single image that contains boot and recovery both - no recovery image to install +# (BOARD_USES_RECOVERY_AS_BOOT = true); +# c) We build the root into system image - not needing the resource file as we do bsdiff +# (BOARD_BUILD_SYSTEM_ROOT_IMAGE = true). +# d) We include the recovery DTBO image within recovery - not needing the resource file as we +# do bsdiff because boot and recovery will contain different number of entries +# (BOARD_INCLUDE_RECOVERY_DTBO = true). +# Note that condition b) implies condition c), because of the earlier check in this file: +# "BOARD_USES_RECOVERY_AS_BOOT = true must have BOARD_BUILD_SYSTEM_ROOT_IMAGE = true" (not vice +# versa though). + +ifeq (,$(filter true, $(BOARD_USES_FULL_RECOVERY_IMAGE) $(BOARD_BUILD_SYSTEM_ROOT_IMAGE) \ + $(BOARD_INCLUDE_RECOVERY_DTBO))) +# Named '.dat' so we don't attempt to use imgdiff for patching it. +RECOVERY_RESOURCE_ZIP := $(TARGET_OUT)/etc/recovery-resource.dat +else +RECOVERY_RESOURCE_ZIP := +endif + +INTERNAL_RECOVERYIMAGE_ARGS := \ + $(addprefix --second ,$(INSTALLED_2NDBOOTLOADER_TARGET)) \ + --kernel $(recovery_kernel) \ + --ramdisk $(recovery_ramdisk) + +# Assumes this has already been stripped +ifdef INTERNAL_KERNEL_CMDLINE + INTERNAL_RECOVERYIMAGE_ARGS += --cmdline "$(INTERNAL_KERNEL_CMDLINE)" +endif +ifdef BOARD_KERNEL_BASE + INTERNAL_RECOVERYIMAGE_ARGS += --base $(BOARD_KERNEL_BASE) +endif +ifdef BOARD_KERNEL_PAGESIZE + INTERNAL_RECOVERYIMAGE_ARGS += --pagesize $(BOARD_KERNEL_PAGESIZE) +endif +ifdef BOARD_INCLUDE_RECOVERY_DTBO + INTERNAL_RECOVERYIMAGE_ARGS += --recovery_dtbo $(BOARD_PREBUILT_DTBOIMAGE) +endif + +# Keys authorized to sign OTA packages this build will accept. The +# build always uses dev-keys for this; release packaging tools will +# substitute other keys for this one. +OTA_PUBLIC_KEYS := $(DEFAULT_SYSTEM_DEV_CERTIFICATE).x509.pem + +# Generate a file containing the keys that will be read by the +# recovery binary. +RECOVERY_INSTALL_OTA_KEYS := \ + $(call intermediates-dir-for,PACKAGING,ota_keys)/keys +DUMPKEY_JAR := $(HOST_OUT_JAVA_LIBRARIES)/dumpkey.jar +$(RECOVERY_INSTALL_OTA_KEYS): PRIVATE_OTA_PUBLIC_KEYS := $(OTA_PUBLIC_KEYS) +$(RECOVERY_INSTALL_OTA_KEYS): extra_keys := $(patsubst %,%.x509.pem,$(PRODUCT_EXTRA_RECOVERY_KEYS)) +$(RECOVERY_INSTALL_OTA_KEYS): $(OTA_PUBLIC_KEYS) $(DUMPKEY_JAR) $(extra_keys) + @echo "DumpPublicKey: $@ <= $(PRIVATE_OTA_PUBLIC_KEYS) $(extra_keys)" + @rm -rf $@ + @mkdir -p $(dir $@) + $(JAVA) -jar $(DUMPKEY_JAR) $(PRIVATE_OTA_PUBLIC_KEYS) $(extra_keys) > $@ + +RECOVERYIMAGE_ID_FILE := $(PRODUCT_OUT)/recovery.id + +# $(1): output file +define build-recoveryimage-target + # Making recovery image + $(hide) mkdir -p $(TARGET_RECOVERY_OUT) + $(hide) mkdir -p $(TARGET_RECOVERY_ROOT_OUT)/etc $(TARGET_RECOVERY_ROOT_OUT)/sdcard $(TARGET_RECOVERY_ROOT_OUT)/tmp + # Copying baseline ramdisk... + # Use rsync because "cp -Rf" fails to overwrite broken symlinks on Mac. + $(hide) rsync -a --exclude=etc --exclude=sdcard $(IGNORE_RECOVERY_SEPOLICY) $(IGNORE_CACHE_LINK) $(TARGET_ROOT_OUT) $(TARGET_RECOVERY_OUT) + # Copy adbd from system/bin to recovery/root/sbin + $(hide) cp -f $(TARGET_OUT_EXECUTABLES)/watchdogd $(TARGET_RECOVERY_ROOT_OUT)/sbin/watchdogd + # Modifying ramdisk contents... + $(if $(BOARD_RECOVERY_KERNEL_MODULES), \ + $(call build-image-kernel-modules,$(BOARD_RECOVERY_KERNEL_MODULES),$(TARGET_RECOVERY_ROOT_OUT),,$(call intermediates-dir-for,PACKAGING,depmod_recovery))) + # Removes $(TARGET_RECOVERY_ROOT_OUT)/init*.rc EXCEPT init.recovery*.rc. + $(hide) find $(TARGET_RECOVERY_ROOT_OUT) -maxdepth 1 -name 'init*.rc' -type f -not -name "init.recovery.*.rc" | xargs rm -f + $(hide) cp -f $(recovery_initrc) $(TARGET_RECOVERY_ROOT_OUT)/ + $(hide) cp $(TARGET_ROOT_OUT)/init.recovery.*.rc $(TARGET_RECOVERY_ROOT_OUT)/ || true # Ignore error when the src file doesn't exist. + $(hide) mkdir -p $(TARGET_RECOVERY_ROOT_OUT)/res + $(hide) rm -rf $(TARGET_RECOVERY_ROOT_OUT)/res/* + $(hide) cp -rf $(recovery_resources_common)/* $(TARGET_RECOVERY_ROOT_OUT)/res + $(hide) cp -f $(recovery_font) $(TARGET_RECOVERY_ROOT_OUT)/res/images/font.png + $(hide) $(foreach item,$(TARGET_PRIVATE_RES_DIRS), \ + cp -rf $(item) $(TARGET_RECOVERY_ROOT_OUT)/$(newline)) + $(hide) $(foreach item,$(recovery_fstab), \ + cp -f $(item) $(TARGET_RECOVERY_ROOT_OUT)/etc/recovery.fstab) + $(if $(strip $(recovery_wipe)), \ + $(hide) cp -f $(recovery_wipe) $(TARGET_RECOVERY_ROOT_OUT)/etc/recovery.wipe) + $(hide) cp $(RECOVERY_INSTALL_OTA_KEYS) $(TARGET_RECOVERY_ROOT_OUT)/res/keys + $(hide) cat $(INSTALLED_DEFAULT_PROP_TARGET) \ + > $(TARGET_RECOVERY_ROOT_OUT)/prop.default + $(if $(INSTALLED_VENDOR_DEFAULT_PROP_TARGET), \ + $(hide) cat $(INSTALLED_VENDOR_DEFAULT_PROP_TARGET) \ + >> $(TARGET_RECOVERY_ROOT_OUT)/prop.default) + $(hide) cat $(recovery_build_props) \ + >> $(TARGET_RECOVERY_ROOT_OUT)/prop.default + $(hide) ln -sf prop.default $(TARGET_RECOVERY_ROOT_OUT)/default.prop + $(BOARD_RECOVERY_IMAGE_PREPARE) + $(if $(filter true,$(BOARD_BUILD_SYSTEM_ROOT_IMAGE)), \ + $(hide) mkdir -p $(TARGET_RECOVERY_ROOT_OUT)/system_root; \ + rm -rf $(TARGET_RECOVERY_ROOT_OUT)/system; \ + ln -sf /system_root/system $(TARGET_RECOVERY_ROOT_OUT)/system) # Mount the system_root_image to /system_root and symlink /system. + $(hide) $(MKBOOTFS) -d $(TARGET_OUT) $(TARGET_RECOVERY_ROOT_OUT) | $(MINIGZIP) > $(recovery_ramdisk) + $(if $(filter true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT)), \ + $(hide) $(MKBOOTIMG) $(INTERNAL_RECOVERYIMAGE_ARGS) $(INTERNAL_MKBOOTIMG_VERSION_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $(1).unsigned, \ + $(hide) $(MKBOOTIMG) $(INTERNAL_RECOVERYIMAGE_ARGS) $(INTERNAL_MKBOOTIMG_VERSION_ARGS) $(BOARD_MKBOOTIMG_ARGS) --output $(1) --id > $(RECOVERYIMAGE_ID_FILE)) + $(if $(filter true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_BOOT_SIGNER)),\ + $(if $(filter true,$(BOARD_USES_RECOVERY_AS_BOOT)),\ + $(BOOT_SIGNER) /boot $(1) $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).pk8 $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).x509.pem $(1),\ + $(BOOT_SIGNER) /recovery $(1) $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).pk8 $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VERITY_SIGNING_KEY).x509.pem $(1)\ + )\ + ) + $(if $(filter true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT)), \ + $(VBOOT_SIGNER) $(FUTILITY) $(1).unsigned $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_KEY).vbpubk $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_KEY).vbprivk $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VBOOT_SIGNING_SUBKEY).vbprivk $(1).keyblock $(1)) + $(if $(filter true,$(BOARD_USES_RECOVERY_AS_BOOT)), \ + $(hide) $(call assert-max-image-size,$(1),$(call get-hash-image-max-size,$(BOARD_BOOTIMAGE_PARTITION_SIZE))), \ + $(hide) $(call assert-max-image-size,$(1),$(call get-hash-image-max-size,$(BOARD_RECOVERYIMAGE_PARTITION_SIZE)))) + $(if $(filter true,$(BOARD_AVB_ENABLE)), \ + $(if $(filter true,$(BOARD_USES_RECOVERY_AS_BOOT)), \ + $(hide) $(AVBTOOL) add_hash_footer --image $(1) --partition_size $(BOARD_BOOTIMAGE_PARTITION_SIZE) --partition_name boot $(INTERNAL_AVB_BOOT_SIGNING_ARGS) $(BOARD_AVB_BOOT_ADD_HASH_FOOTER_ARGS),\ + $(hide) $(AVBTOOL) add_hash_footer --image $(1) --partition_size $(BOARD_RECOVERYIMAGE_PARTITION_SIZE) --partition_name recovery $(INTERNAL_AVB_RECOVERY_SIGNING_ARGS) $(BOARD_AVB_RECOVERY_ADD_HASH_FOOTER_ARGS))) +endef + +ADBD := $(TARGET_OUT_EXECUTABLES)/watchdogd + +ifeq ($(BOARD_USES_RECOVERY_AS_BOOT),true) +ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_BOOT_SIGNER)) +$(INSTALLED_BOOTIMAGE_TARGET) : $(BOOT_SIGNER) +endif +ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT)) +$(INSTALLED_BOOTIMAGE_TARGET) : $(VBOOT_SIGNER) +endif +ifeq (true,$(BOARD_AVB_ENABLE)) +$(INSTALLED_BOOTIMAGE_TARGET) : $(AVBTOOL) $(BOARD_AVB_BOOT_KEY_PATH) +endif +$(INSTALLED_BOOTIMAGE_TARGET): $(MKBOOTFS) $(MKBOOTIMG) $(MINIGZIP) $(ADBD) \ + $(INSTALLED_RAMDISK_TARGET) \ + $(INTERNAL_RECOVERYIMAGE_FILES) \ + $(recovery_initrc) $(recovery_sepolicy) $(recovery_kernel) \ + $(INSTALLED_2NDBOOTLOADER_TARGET) \ + $(recovery_build_props) $(recovery_resource_deps) \ + $(recovery_fstab) \ + $(RECOVERY_INSTALL_OTA_KEYS) \ + $(INSTALLED_VENDOR_DEFAULT_PROP_TARGET) \ + $(BOARD_RECOVERY_KERNEL_MODULES) \ + $(DEPMOD) + $(call pretty,"Target boot image from recovery: $@") + $(call build-recoveryimage-target, $@) +endif + +$(INSTALLED_RECOVERYIMAGE_TARGET): $(MKBOOTFS) $(MKBOOTIMG) $(MINIGZIP) $(ADBD) \ + $(INSTALLED_RAMDISK_TARGET) \ + $(INSTALLED_BOOTIMAGE_TARGET) \ + $(INTERNAL_RECOVERYIMAGE_FILES) \ + $(recovery_initrc) $(recovery_sepolicy) $(recovery_kernel) \ + $(INSTALLED_2NDBOOTLOADER_TARGET) \ + $(recovery_build_props) $(recovery_resource_deps) \ + $(recovery_fstab) \ + $(RECOVERY_INSTALL_OTA_KEYS) \ + $(INSTALLED_VENDOR_DEFAULT_PROP_TARGET) \ + $(BOARD_RECOVERY_KERNEL_MODULES) \ + $(DEPMOD) + $(call build-recoveryimage-target, $@) + +ifdef RECOVERY_RESOURCE_ZIP +$(RECOVERY_RESOURCE_ZIP): $(INSTALLED_RECOVERYIMAGE_TARGET) | $(ZIPTIME) + $(hide) mkdir -p $(dir $@) + $(hide) find $(TARGET_RECOVERY_ROOT_OUT)/res -type f | sort | zip -0qrjX $@ -@ + $(remove-timestamps-from-package) +endif + +.PHONY: recoveryimage-nodeps +recoveryimage-nodeps: + @echo "make $@: ignoring dependencies" + $(call build-recoveryimage-target, $(INSTALLED_RECOVERYIMAGE_TARGET)) + +else # INSTALLED_RECOVERYIMAGE_TARGET not defined +RECOVERY_RESOURCE_ZIP := +endif + +.PHONY: recoveryimage +recoveryimage: $(INSTALLED_RECOVERYIMAGE_TARGET) $(RECOVERY_RESOURCE_ZIP) + +ifneq ($(BOARD_NAND_PAGE_SIZE),) +$(error MTD device is no longer supported and thus BOARD_NAND_PAGE_SIZE is deprecated.) +endif + +ifneq ($(BOARD_NAND_SPARE_SIZE),) +$(error MTD device is no longer supported and thus BOARD_NAND_SPARE_SIZE is deprecated.) +endif + +# ----------------------------------------------------------------- +# system image +# +# Remove overridden packages from $(ALL_PDK_FUSION_FILES) +PDK_FUSION_SYSIMG_FILES := \ + $(filter-out $(foreach p,$(overridden_packages),$(p) %/$(p).apk), \ + $(ALL_PDK_FUSION_FILES)) + +INTERNAL_SYSTEMIMAGE_FILES := $(filter $(TARGET_OUT)/%, \ + $(ALL_GENERATED_SOURCES) \ + $(ALL_DEFAULT_INSTALLED_MODULES) \ + $(PDK_FUSION_SYSIMG_FILES) \ + $(RECOVERY_RESOURCE_ZIP)) \ + $(PDK_FUSION_SYMLINK_STAMP) + +FULL_SYSTEMIMAGE_DEPS := $(INTERNAL_SYSTEMIMAGE_FILES) $(INTERNAL_USERIMAGES_DEPS) + +# ASAN libraries in the system image - add dependency. +ASAN_IN_SYSTEM_INSTALLED := $(TARGET_OUT)/asan.tar.bz2 +ifneq (,$(SANITIZE_TARGET)) + ifeq (true,$(SANITIZE_TARGET_SYSTEM)) + FULL_SYSTEMIMAGE_DEPS += $(ASAN_IN_SYSTEM_INSTALLED) + endif +endif + +# ----------------------------------------------------------------- +# installed file list +# Depending on anything that $(BUILT_SYSTEMIMAGE) depends on. +# We put installed-files.txt ahead of image itself in the dependency graph +# so that we can get the size stat even if the build fails due to too large +# system image. +INSTALLED_FILES_FILE := $(PRODUCT_OUT)/installed-files.txt +$(INSTALLED_FILES_FILE): $(FULL_SYSTEMIMAGE_DEPS) $(FILESLIST) + @echo Installed file list: $@ + @mkdir -p $(dir $@) + @rm -f $@ + $(hide) $(FILESLIST) $(TARGET_OUT) > $(@:.txt=.json) + $(hide) build/make/tools/fileslist_util.py -c $(@:.txt=.json) > $@ + +.PHONY: installed-file-list +installed-file-list: $(INSTALLED_FILES_FILE) + +$(call dist-for-goals, sdk win_sdk sdk_addon, $(INSTALLED_FILES_FILE)) + +systemimage_intermediates := \ + $(call intermediates-dir-for,PACKAGING,systemimage) +BUILT_SYSTEMIMAGE := $(systemimage_intermediates)/system.img + +# Create symlink /system/vendor to /vendor if necessary. +ifdef BOARD_USES_VENDORIMAGE +define create-system-vendor-symlink +$(hide) if [ -d $(TARGET_OUT)/vendor ] && [ ! -h $(TARGET_OUT)/vendor ]; then \ + echo 'Non-symlink $(TARGET_OUT)/vendor detected!' 1>&2; \ + echo 'You cannot install files to $(TARGET_OUT)/vendor while building a separate vendor.img!' 1>&2; \ + exit 1; \ +fi +$(hide) ln -sf /vendor $(TARGET_OUT)/vendor +endef +else +define create-system-vendor-symlink +endef +endif + +# Create symlink /system/product to /product if necessary. +ifdef BOARD_USES_PRODUCTIMAGE +define create-system-product-symlink +$(hide) if [ -d $(TARGET_OUT)/product ] && [ ! -h $(TARGET_OUT)/product ]; then \ + echo 'Non-symlink $(TARGET_OUT)/product detected!' 1>&2; \ + echo 'You cannot install files to $(TARGET_OUT)/product while building a separate product.img!' 1>&2; \ + exit 1; \ +fi +$(hide) ln -sf /product $(TARGET_OUT)/product +endef +else +define create-system-product-symlink +endef +endif + +# $(1): output file +define build-systemimage-target + @echo "Target system fs image: $(1)" + $(call create-system-vendor-symlink) + $(call create-system-product-symlink) + @mkdir -p $(dir $(1)) $(systemimage_intermediates) && rm -rf $(systemimage_intermediates)/system_image_info.txt + $(call generate-userimage-prop-dictionary, $(systemimage_intermediates)/system_image_info.txt, \ + skip_fsck=true) + $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \ + build/make/tools/releasetools/build_image.py \ + $(TARGET_OUT) $(systemimage_intermediates)/system_image_info.txt $(1) $(TARGET_OUT) \ + || ( echo "Out of space? the tree size of $(TARGET_OUT) is (MB): " 1>&2 ;\ + du -sm $(TARGET_OUT) 1>&2;\ + if [ "$(INTERNAL_USERIMAGES_EXT_VARIANT)" == "ext4" ]; then \ + maxsize=$(BOARD_SYSTEMIMAGE_PARTITION_SIZE); \ + echo "The max is $$(( maxsize / 1048576 )) MB." 1>&2 ;\ + else \ + echo "The max is $$(( $(BOARD_SYSTEMIMAGE_PARTITION_SIZE) / 1048576 )) MB." 1>&2 ;\ + fi; \ + mkdir -p $(DIST_DIR); cp $(INSTALLED_FILES_FILE) $(DIST_DIR)/installed-files-rescued.txt; \ + exit 1 ) +endef + +$(BUILT_SYSTEMIMAGE): $(FULL_SYSTEMIMAGE_DEPS) $(INSTALLED_FILES_FILE) $(BUILD_IMAGE_SRCS) + $(call build-systemimage-target,$@) + +INSTALLED_SYSTEMIMAGE := $(PRODUCT_OUT)/system.img +SYSTEMIMAGE_SOURCE_DIR := $(TARGET_OUT) + +# The system partition needs room for the recovery image as well. We +# now store the recovery image as a binary patch using the boot image +# as the source (since they are very similar). Generate the patch so +# we can see how big it's going to be, and include that in the system +# image size check calculation. +ifneq ($(INSTALLED_RECOVERYIMAGE_TARGET),) +ifneq ($(BOARD_USES_FULL_RECOVERY_IMAGE),true) +ifneq (,$(filter true, $(BOARD_BUILD_SYSTEM_ROOT_IMAGE) $(BOARD_INCLUDE_RECOVERY_DTBO))) +diff_tool := $(HOST_OUT_EXECUTABLES)/bsdiff +else +diff_tool := $(HOST_OUT_EXECUTABLES)/imgdiff +endif +intermediates := $(call intermediates-dir-for,PACKAGING,recovery_patch) +RECOVERY_FROM_BOOT_PATCH := $(intermediates)/recovery_from_boot.p +$(RECOVERY_FROM_BOOT_PATCH): PRIVATE_DIFF_TOOL := $(diff_tool) +$(RECOVERY_FROM_BOOT_PATCH): \ + $(INSTALLED_RECOVERYIMAGE_TARGET) \ + $(INSTALLED_BOOTIMAGE_TARGET) \ + $(diff_tool) + @echo "Construct recovery from boot" + mkdir -p $(dir $@) + $(PRIVATE_DIFF_TOOL) $(INSTALLED_BOOTIMAGE_TARGET) $(INSTALLED_RECOVERYIMAGE_TARGET) $@ +else # $(BOARD_USES_FULL_RECOVERY_IMAGE) == true +RECOVERY_FROM_BOOT_PATCH := $(INSTALLED_RECOVERYIMAGE_TARGET) +endif +endif + + +$(INSTALLED_SYSTEMIMAGE): $(BUILT_SYSTEMIMAGE) $(RECOVERY_FROM_BOOT_PATCH) + @echo "Install system fs image: $@" + $(copy-file-to-target) + $(hide) $(call assert-max-image-size,$@ $(RECOVERY_FROM_BOOT_PATCH),$(BOARD_SYSTEMIMAGE_PARTITION_SIZE)) + +systemimage: $(INSTALLED_SYSTEMIMAGE) + +.PHONY: systemimage-nodeps snod +systemimage-nodeps snod: $(filter-out systemimage-nodeps snod,$(MAKECMDGOALS)) \ + | $(INTERNAL_USERIMAGES_DEPS) + @echo "make $@: ignoring dependencies" + $(call build-systemimage-target,$(INSTALLED_SYSTEMIMAGE)) + $(hide) $(call assert-max-image-size,$(INSTALLED_SYSTEMIMAGE),$(BOARD_SYSTEMIMAGE_PARTITION_SIZE)) + +ifneq (,$(filter systemimage-nodeps snod, $(MAKECMDGOALS))) +ifeq (true,$(WITH_DEXPREOPT)) +$(warning Warning: with dexpreopt enabled, you may need a full rebuild.) +endif +endif + +.PHONY: sync +sync: $(INTERNAL_SYSTEMIMAGE_FILES) + +####### +## system tarball +define build-systemtarball-target + $(call pretty,"Target system fs tarball: $(INSTALLED_SYSTEMTARBALL_TARGET)") + $(call create-system-vendor-symlink) + $(call create-system-product-symlink) + $(MKTARBALL) $(FS_GET_STATS) \ + $(PRODUCT_OUT) system $(PRIVATE_SYSTEM_TAR) \ + $(INSTALLED_SYSTEMTARBALL_TARGET) $(TARGET_OUT) +endef + +ifndef SYSTEM_TARBALL_FORMAT + SYSTEM_TARBALL_FORMAT := bz2 +endif + +system_tar := $(PRODUCT_OUT)/system.tar +INSTALLED_SYSTEMTARBALL_TARGET := $(system_tar).$(SYSTEM_TARBALL_FORMAT) +$(INSTALLED_SYSTEMTARBALL_TARGET): PRIVATE_SYSTEM_TAR := $(system_tar) +$(INSTALLED_SYSTEMTARBALL_TARGET): $(FS_GET_STATS) $(INTERNAL_SYSTEMIMAGE_FILES) + $(build-systemtarball-target) + +.PHONY: systemtarball-nodeps +systemtarball-nodeps: $(FS_GET_STATS) \ + $(filter-out systemtarball-nodeps stnod,$(MAKECMDGOALS)) + $(build-systemtarball-target) + +.PHONY: stnod +stnod: systemtarball-nodeps + +# ----------------------------------------------------------------- +## platform.zip: system, plus other files to be used in PDK fusion build, +## in a zip file +## +## PDK_PLATFORM_ZIP_PRODUCT_BINARIES is used to store specified files to platform.zip. +## The variable will be typically set from BoardConfig.mk. +## Files under out dir will be rejected to prevent possible conflicts with other rules. +pdk_odex_javalibs := $(strip $(foreach m,$(DEXPREOPT.MODULES.JAVA_LIBRARIES),\ + $(if $(filter $(DEXPREOPT.$(m).INSTALLED),$(ALL_DEFAULT_INSTALLED_MODULES)),$(m)))) +pdk_odex_apps := $(strip $(foreach m,$(DEXPREOPT.MODULES.APPS),\ + $(if $(filter $(DEXPREOPT.$(m).INSTALLED),$(ALL_DEFAULT_INSTALLED_MODULES)),$(m)))) +pdk_classes_dex := $(strip \ + $(foreach m,$(pdk_odex_javalibs),$(call intermediates-dir-for,JAVA_LIBRARIES,$(m),,COMMON)/javalib.jar) \ + $(foreach m,$(pdk_odex_apps),$(call intermediates-dir-for,APPS,$(m))/package.dex.apk)) + +pdk_odex_config_mk := $(PRODUCT_OUT)/pdk_dexpreopt_config.mk +$(pdk_odex_config_mk): PRIVATE_JAVA_LIBRARIES := $(pdk_odex_javalibs) +$(pdk_odex_config_mk): PRIVATE_APPS := $(pdk_odex_apps) +$(pdk_odex_config_mk) : + @echo "PDK odex config makefile: $@" + $(hide) mkdir -p $(dir $@) + $(hide) echo "# Auto-generated. Do not modify." > $@ + $(hide) echo "PDK.DEXPREOPT.JAVA_LIBRARIES:=$(PRIVATE_JAVA_LIBRARIES)" >> $@ + $(hide) echo "PDK.DEXPREOPT.APPS:=$(PRIVATE_APPS)" >> $@ + $(foreach m,$(PRIVATE_JAVA_LIBRARIES),\ + $(hide) echo "PDK.DEXPREOPT.$(m).SRC:=$(patsubst $(OUT_DIR)/%,%,$(call intermediates-dir-for,JAVA_LIBRARIES,$(m),,COMMON)/javalib.jar)" >> $@$(newline)\ + $(hide) echo "PDK.DEXPREOPT.$(m).DEX_PREOPT:=$(DEXPREOPT.$(m).DEX_PREOPT)" >> $@$(newline)\ + $(hide) echo "PDK.DEXPREOPT.$(m).MULTILIB:=$(DEXPREOPT.$(m).MULTILIB)" >> $@$(newline)\ + $(hide) echo "PDK.DEXPREOPT.$(m).DEX_PREOPT_FLAGS:=$(DEXPREOPT.$(m).DEX_PREOPT_FLAGS)" >> $@$(newline)\ + ) + $(foreach m,$(PRIVATE_APPS),\ + $(hide) echo "PDK.DEXPREOPT.$(m).SRC:=$(patsubst $(OUT_DIR)/%,%,$(call intermediates-dir-for,APPS,$(m))/package.dex.apk)" >> $@$(newline)\ + $(hide) echo "PDK.DEXPREOPT.$(m).DEX_PREOPT:=$(DEXPREOPT.$(m).DEX_PREOPT)" >> $@$(newline)\ + $(hide) echo "PDK.DEXPREOPT.$(m).MULTILIB:=$(DEXPREOPT.$(m).MULTILIB)" >> $@$(newline)\ + $(hide) echo "PDK.DEXPREOPT.$(m).DEX_PREOPT_FLAGS:=$(DEXPREOPT.$(m).DEX_PREOPT_FLAGS)" >> $@$(newline)\ + $(hide) echo "PDK.DEXPREOPT.$(m).PRIVILEGED_MODULE:=$(DEXPREOPT.$(m).PRIVILEGED_MODULE)" >> $@$(newline)\ + $(hide) echo "PDK.DEXPREOPT.$(m).VENDOR_MODULE:=$(DEXPREOPT.$(m).VENDOR_MODULE)" >> $@$(newline)\ + $(hide) echo "PDK.DEXPREOPT.$(m).TARGET_ARCH:=$(DEXPREOPT.$(m).TARGET_ARCH)" >> $@$(newline)\ + $(hide) echo "PDK.DEXPREOPT.$(m).STRIPPED_SRC:=$(patsubst $(PRODUCT_OUT)/%,%,$(DEXPREOPT.$(m).INSTALLED_STRIPPED))" >> $@$(newline)\ + ) + +PDK_PLATFORM_ZIP_PRODUCT_BINARIES := $(filter-out $(OUT_DIR)/%,$(PDK_PLATFORM_ZIP_PRODUCT_BINARIES)) +INSTALLED_PLATFORM_ZIP := $(PRODUCT_OUT)/platform.zip + +$(INSTALLED_PLATFORM_ZIP): PRIVATE_DEX_FILES := $(pdk_classes_dex) +$(INSTALLED_PLATFORM_ZIP): PRIVATE_ODEX_CONFIG := $(pdk_odex_config_mk) +$(INSTALLED_PLATFORM_ZIP) : $(INTERNAL_SYSTEMIMAGE_FILES) $(pdk_odex_config_mk) + $(call pretty,"Platform zip package: $(INSTALLED_PLATFORM_ZIP)") + $(hide) rm -f $@ + $(hide) cd $(dir $@) && zip -qryX $(notdir $@) \ + $(TARGET_COPY_OUT_SYSTEM) \ + $(patsubst $(PRODUCT_OUT)/%, %, $(TARGET_OUT_NOTICE_FILES)) \ + $(addprefix symbols/,$(PDK_SYMBOL_FILES_LIST)) +ifdef BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE + $(hide) cd $(dir $@) && zip -qryX $(notdir $@) \ + $(TARGET_COPY_OUT_VENDOR) +endif +ifdef BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE + $(hide) cd $(dir $@) && zip -qryX $(notdir $@) \ + $(TARGET_COPY_OUT_PRODUCT) +endif +ifneq ($(PDK_PLATFORM_JAVA_ZIP_CONTENTS),) + $(hide) cd $(OUT_DIR) && zip -qryX $(patsubst $(OUT_DIR)/%,%,$@) $(PDK_PLATFORM_JAVA_ZIP_CONTENTS) +endif +ifneq ($(PDK_PLATFORM_ZIP_PRODUCT_BINARIES),) + $(hide) zip -qryX $@ $(PDK_PLATFORM_ZIP_PRODUCT_BINARIES) +endif + @# Add dex-preopt files and config. + $(if $(PRIVATE_DEX_FILES),$(hide) cd $(OUT_DIR) && zip -qryX $(patsubst $(OUT_DIR)/%,%,$@ $(PRIVATE_DEX_FILES))) + $(hide) touch $(PRODUCT_OUT)/pdk.mk + $(hide) zip -qryXj $@ $(PRIVATE_ODEX_CONFIG) $(PRODUCT_OUT)/pdk.mk + +.PHONY: platform +platform: $(INSTALLED_PLATFORM_ZIP) + +.PHONY: platform-java +platform-java: platform + +# Dist the platform.zip +ifneq (,$(filter platform platform-java, $(MAKECMDGOALS))) +$(call dist-for-goals, platform platform-java, $(INSTALLED_PLATFORM_ZIP)) +endif + +# ----------------------------------------------------------------- +## boot tarball +define build-boottarball-target + $(hide) echo "Target boot fs tarball: $(INSTALLED_BOOTTARBALL_TARGET)" + $(hide) mkdir -p $(PRODUCT_OUT)/boot + $(hide) cp -f $(INTERNAL_BOOTIMAGE_FILES) $(PRODUCT_OUT)/boot/. + $(hide) echo $(INTERNAL_KERNEL_CMDLINE) > $(PRODUCT_OUT)/boot/cmdline + $(hide) $(MKTARBALL) $(FS_GET_STATS) \ + $(PRODUCT_OUT) boot $(PRIVATE_BOOT_TAR) \ + $(INSTALLED_BOOTTARBALL_TARGET) $(TARGET_OUT) +endef + +ifndef BOOT_TARBALL_FORMAT + BOOT_TARBALL_FORMAT := bz2 +endif + +boot_tar := $(PRODUCT_OUT)/boot.tar +INSTALLED_BOOTTARBALL_TARGET := $(boot_tar).$(BOOT_TARBALL_FORMAT) +$(INSTALLED_BOOTTARBALL_TARGET): PRIVATE_BOOT_TAR := $(boot_tar) +$(INSTALLED_BOOTTARBALL_TARGET): $(FS_GET_STATS) $(INTERNAL_BOOTIMAGE_FILES) + $(build-boottarball-target) + +.PHONY: boottarball-nodeps btnod +boottarball-nodeps btnod: $(FS_GET_STATS) \ + $(filter-out boottarball-nodeps btnod,$(MAKECMDGOALS)) + $(build-boottarball-target) + + +# ----------------------------------------------------------------- +# data partition image +INTERNAL_USERDATAIMAGE_FILES := \ + $(filter $(TARGET_OUT_DATA)/%,$(ALL_DEFAULT_INSTALLED_MODULES)) + +# Don't build userdata.img if it's extfs but no partition size +skip_userdata.img := +ifdef INTERNAL_USERIMAGES_EXT_VARIANT +ifndef BOARD_USERDATAIMAGE_PARTITION_SIZE +skip_userdata.img := true +endif +endif + +ifneq ($(skip_userdata.img),true) +userdataimage_intermediates := \ + $(call intermediates-dir-for,PACKAGING,userdata) +BUILT_USERDATAIMAGE_TARGET := $(PRODUCT_OUT)/userdata.img + +define build-userdataimage-target + $(call pretty,"Target userdata fs image: $(INSTALLED_USERDATAIMAGE_TARGET)") + @mkdir -p $(TARGET_OUT_DATA) + @mkdir -p $(userdataimage_intermediates) && rm -rf $(userdataimage_intermediates)/userdata_image_info.txt + $(call generate-userimage-prop-dictionary, $(userdataimage_intermediates)/userdata_image_info.txt, skip_fsck=true) + $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \ + build/make/tools/releasetools/build_image.py \ + $(TARGET_OUT_DATA) $(userdataimage_intermediates)/userdata_image_info.txt $(INSTALLED_USERDATAIMAGE_TARGET) $(TARGET_OUT) + $(hide) $(call assert-max-image-size,$(INSTALLED_USERDATAIMAGE_TARGET),$(BOARD_USERDATAIMAGE_PARTITION_SIZE)) +endef + +# We just build this directly to the install location. +INSTALLED_USERDATAIMAGE_TARGET := $(BUILT_USERDATAIMAGE_TARGET) +INSTALLED_USERDATAIMAGE_TARGET_DEPS := \ + $(INTERNAL_USERIMAGES_DEPS) \ + $(INTERNAL_USERDATAIMAGE_FILES) \ + $(BUILD_IMAGE_SRCS) +$(INSTALLED_USERDATAIMAGE_TARGET): $(INSTALLED_USERDATAIMAGE_TARGET_DEPS) + $(build-userdataimage-target) + +.PHONY: userdataimage-nodeps +userdataimage-nodeps: | $(INTERNAL_USERIMAGES_DEPS) + $(build-userdataimage-target) + +endif # not skip_userdata.img +skip_userdata.img := + +# ASAN libraries in the system image - build rule. +ASAN_OUT_DIRS_FOR_SYSTEM_INSTALL := $(sort $(patsubst $(PRODUCT_OUT)/%,%,\ + $(TARGET_OUT_SHARED_LIBRARIES) \ + $(2ND_TARGET_OUT_SHARED_LIBRARIES) \ + $(TARGET_OUT_VENDOR_SHARED_LIBRARIES) \ + $(2ND_TARGET_OUT_VENDOR_SHARED_LIBRARIES))) +# Extra options: Enforce the system user for the files to avoid having to change ownership. +ASAN_SYSTEM_INSTALL_OPTIONS := --owner=1000 --group=1000 +# Note: experimentally, it seems not worth it to try to get "best" compression. We don't save +# enough space. +$(ASAN_IN_SYSTEM_INSTALLED): $(INSTALLED_USERDATAIMAGE_TARGET_DEPS) + tar cfj $(ASAN_IN_SYSTEM_INSTALLED) $(ASAN_SYSTEM_INSTALL_OPTIONS) -C $(TARGET_OUT_DATA)/.. $(ASAN_OUT_DIRS_FOR_SYSTEM_INSTALL) >/dev/null + +####### +## data partition tarball +define build-userdatatarball-target + $(call pretty,"Target userdata fs tarball: " \ + "$(INSTALLED_USERDATATARBALL_TARGET)") + $(MKTARBALL) $(FS_GET_STATS) \ + $(PRODUCT_OUT) data $(PRIVATE_USERDATA_TAR) \ + $(INSTALLED_USERDATATARBALL_TARGET) $(TARGET_OUT) +endef + +userdata_tar := $(PRODUCT_OUT)/userdata.tar +INSTALLED_USERDATATARBALL_TARGET := $(userdata_tar).bz2 +$(INSTALLED_USERDATATARBALL_TARGET): PRIVATE_USERDATA_TAR := $(userdata_tar) +$(INSTALLED_USERDATATARBALL_TARGET): $(FS_GET_STATS) $(INTERNAL_USERDATAIMAGE_FILES) + $(build-userdatatarball-target) + +$(call dist-for-goals,userdatatarball,$(INSTALLED_USERDATATARBALL_TARGET)) + +.PHONY: userdatatarball-nodeps +userdatatarball-nodeps: $(FS_GET_STATS) + $(build-userdatatarball-target) + + +# ----------------------------------------------------------------- +# partition table image +ifdef BOARD_BPT_INPUT_FILES + +BUILT_BPTIMAGE_TARGET := $(PRODUCT_OUT)/partition-table.img +BUILT_BPTJSON_TARGET := $(PRODUCT_OUT)/partition-table.bpt + +INTERNAL_BVBTOOL_MAKE_TABLE_ARGS := \ + --output_gpt $(BUILT_BPTIMAGE_TARGET) \ + --output_json $(BUILT_BPTJSON_TARGET) \ + $(foreach file, $(BOARD_BPT_INPUT_FILES), --input $(file)) + +ifdef BOARD_BPT_DISK_SIZE +INTERNAL_BVBTOOL_MAKE_TABLE_ARGS += --disk_size $(BOARD_BPT_DISK_SIZE) +endif + +define build-bptimage-target + $(call pretty,"Target partition table image: $(INSTALLED_BPTIMAGE_TARGET)") + $(hide) $(BPTTOOL) make_table $(INTERNAL_BVBTOOL_MAKE_TABLE_ARGS) $(BOARD_BPT_MAKE_TABLE_ARGS) +endef + +INSTALLED_BPTIMAGE_TARGET := $(BUILT_BPTIMAGE_TARGET) +$(BUILT_BPTJSON_TARGET): $(INSTALLED_BPTIMAGE_TARGET) + $(hide) touch -c $(BUILT_BPTJSON_TARGET) + +$(INSTALLED_BPTIMAGE_TARGET): $(BPTTOOL) $(BOARD_BPT_INPUT_FILES) + $(build-bptimage-target) + +.PHONY: bptimage-nodeps +bptimage-nodeps: + $(build-bptimage-target) + +endif # BOARD_BPT_INPUT_FILES + +# ----------------------------------------------------------------- +# cache partition image +ifdef BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE +INTERNAL_CACHEIMAGE_FILES := \ + $(filter $(TARGET_OUT_CACHE)/%,$(ALL_DEFAULT_INSTALLED_MODULES)) + +cacheimage_intermediates := \ + $(call intermediates-dir-for,PACKAGING,cache) +BUILT_CACHEIMAGE_TARGET := $(PRODUCT_OUT)/cache.img + +define build-cacheimage-target + $(call pretty,"Target cache fs image: $(INSTALLED_CACHEIMAGE_TARGET)") + @mkdir -p $(TARGET_OUT_CACHE) + @mkdir -p $(cacheimage_intermediates) && rm -rf $(cacheimage_intermediates)/cache_image_info.txt + $(call generate-userimage-prop-dictionary, $(cacheimage_intermediates)/cache_image_info.txt, skip_fsck=true) + $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \ + build/make/tools/releasetools/build_image.py \ + $(TARGET_OUT_CACHE) $(cacheimage_intermediates)/cache_image_info.txt $(INSTALLED_CACHEIMAGE_TARGET) $(TARGET_OUT) + $(hide) $(call assert-max-image-size,$(INSTALLED_CACHEIMAGE_TARGET),$(BOARD_CACHEIMAGE_PARTITION_SIZE)) +endef + +# We just build this directly to the install location. +INSTALLED_CACHEIMAGE_TARGET := $(BUILT_CACHEIMAGE_TARGET) +$(INSTALLED_CACHEIMAGE_TARGET): $(INTERNAL_USERIMAGES_DEPS) $(INTERNAL_CACHEIMAGE_FILES) $(BUILD_IMAGE_SRCS) + $(build-cacheimage-target) + +.PHONY: cacheimage-nodeps +cacheimage-nodeps: | $(INTERNAL_USERIMAGES_DEPS) + $(build-cacheimage-target) + +else # BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE +# we need to ignore the broken cache link when doing the rsync +IGNORE_CACHE_LINK := --exclude=cache +endif # BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE + +# ----------------------------------------------------------------- +# system_other partition image +ifeq ($(BOARD_USES_SYSTEM_OTHER_ODEX),true) +BOARD_USES_SYSTEM_OTHER := true + +# Marker file to identify that odex files are installed +INSTALLED_SYSTEM_OTHER_ODEX_MARKER := $(TARGET_OUT_SYSTEM_OTHER)/system-other-odex-marker +ALL_DEFAULT_INSTALLED_MODULES += $(INSTALLED_SYSTEM_OTHER_ODEX_MARKER) +$(INSTALLED_SYSTEM_OTHER_ODEX_MARKER): + $(hide) touch $@ +endif + +ifdef BOARD_USES_SYSTEM_OTHER +INTERNAL_SYSTEMOTHERIMAGE_FILES := \ + $(filter $(TARGET_OUT_SYSTEM_OTHER)/%,\ + $(ALL_DEFAULT_INSTALLED_MODULES)\ + $(ALL_PDK_FUSION_FILES)) \ + $(PDK_FUSION_SYMLINK_STAMP) + +INSTALLED_FILES_FILE_SYSTEMOTHER := $(PRODUCT_OUT)/installed-files-system-other.txt +$(INSTALLED_FILES_FILE_SYSTEMOTHER) : $(INTERNAL_SYSTEMOTHERIMAGE_FILES) $(FILESLIST) + @echo Installed file list: $@ + @mkdir -p $(dir $@) + @rm -f $@ + $(hide) $(FILESLIST) $(TARGET_OUT_SYSTEM_OTHER) > $(@:.txt=.json) + $(hide) build/make/tools/fileslist_util.py -c $(@:.txt=.json) > $@ + +systemotherimage_intermediates := \ + $(call intermediates-dir-for,PACKAGING,system_other) +BUILT_SYSTEMOTHERIMAGE_TARGET := $(PRODUCT_OUT)/system_other.img + +# Note that we assert the size is SYSTEMIMAGE_PARTITION_SIZE since this is the 'b' system image. +define build-systemotherimage-target + $(call pretty,"Target system_other fs image: $(INSTALLED_SYSTEMOTHERIMAGE_TARGET)") + @mkdir -p $(TARGET_OUT_SYSTEM_OTHER) + @mkdir -p $(systemotherimage_intermediates) && rm -rf $(systemotherimage_intermediates)/system_other_image_info.txt + $(call generate-userimage-prop-dictionary, $(systemotherimage_intermediates)/system_other_image_info.txt, skip_fsck=true) + $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \ + build/make/tools/releasetools/build_image.py \ + $(TARGET_OUT_SYSTEM_OTHER) $(systemotherimage_intermediates)/system_other_image_info.txt $(INSTALLED_SYSTEMOTHERIMAGE_TARGET) $(TARGET_OUT) + $(hide) $(call assert-max-image-size,$(INSTALLED_SYSTEMOTHERIMAGE_TARGET),$(BOARD_SYSTEMIMAGE_PARTITION_SIZE)) +endef + +# We just build this directly to the install location. +INSTALLED_SYSTEMOTHERIMAGE_TARGET := $(BUILT_SYSTEMOTHERIMAGE_TARGET) +ifneq (true,$(SANITIZE_LITE)) +# Only create system_other when not building the second stage of a SANITIZE_LITE build. +$(INSTALLED_SYSTEMOTHERIMAGE_TARGET): $(INTERNAL_USERIMAGES_DEPS) $(INTERNAL_SYSTEMOTHERIMAGE_FILES) $(INSTALLED_FILES_FILE_SYSTEMOTHER) + $(build-systemotherimage-target) +endif + +.PHONY: systemotherimage-nodeps +systemotherimage-nodeps: | $(INTERNAL_USERIMAGES_DEPS) + $(build-systemotherimage-target) + +endif # BOARD_USES_SYSTEM_OTHER + + +# ----------------------------------------------------------------- +# vendor partition image +ifdef BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE +INTERNAL_VENDORIMAGE_FILES := \ + $(filter $(TARGET_OUT_VENDOR)/%,\ + $(ALL_DEFAULT_INSTALLED_MODULES)\ + $(ALL_PDK_FUSION_FILES)) \ + $(PDK_FUSION_SYMLINK_STAMP) + +# platform.zip depends on $(INTERNAL_VENDORIMAGE_FILES). +$(INSTALLED_PLATFORM_ZIP) : $(INTERNAL_VENDORIMAGE_FILES) + +INSTALLED_FILES_FILE_VENDOR := $(PRODUCT_OUT)/installed-files-vendor.txt +$(INSTALLED_FILES_FILE_VENDOR) : $(INTERNAL_VENDORIMAGE_FILES) $(FILESLIST) + @echo Installed file list: $@ + @mkdir -p $(dir $@) + @rm -f $@ + $(hide) $(FILESLIST) $(TARGET_OUT_VENDOR) > $(@:.txt=.json) + $(hide) build/make/tools/fileslist_util.py -c $(@:.txt=.json) > $@ + +vendorimage_intermediates := \ + $(call intermediates-dir-for,PACKAGING,vendor) +BUILT_VENDORIMAGE_TARGET := $(PRODUCT_OUT)/vendor.img +define build-vendorimage-target + $(call pretty,"Target vendor fs image: $(INSTALLED_VENDORIMAGE_TARGET)") + @mkdir -p $(TARGET_OUT_VENDOR) + @mkdir -p $(vendorimage_intermediates) && rm -rf $(vendorimage_intermediates)/vendor_image_info.txt + $(call generate-userimage-prop-dictionary, $(vendorimage_intermediates)/vendor_image_info.txt, skip_fsck=true) + $(if $(BOARD_VENDOR_KERNEL_MODULES), \ + $(call build-image-kernel-modules,$(BOARD_VENDOR_KERNEL_MODULES),$(TARGET_OUT_VENDOR),vendor/,$(call intermediates-dir-for,PACKAGING,depmod_vendor))) + $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \ + build/make/tools/releasetools/build_image.py \ + $(TARGET_OUT_VENDOR) $(vendorimage_intermediates)/vendor_image_info.txt $(INSTALLED_VENDORIMAGE_TARGET) $(TARGET_OUT) + $(hide) $(call assert-max-image-size,$(INSTALLED_VENDORIMAGE_TARGET),$(BOARD_VENDORIMAGE_PARTITION_SIZE)) +endef + +# We just build this directly to the install location. +INSTALLED_VENDORIMAGE_TARGET := $(BUILT_VENDORIMAGE_TARGET) +$(INSTALLED_VENDORIMAGE_TARGET): $(INTERNAL_USERIMAGES_DEPS) $(INTERNAL_VENDORIMAGE_FILES) $(INSTALLED_FILES_FILE_VENDOR) $(BUILD_IMAGE_SRCS) $(DEPMOD) $(BOARD_VENDOR_KERNEL_MODULES) + $(build-vendorimage-target) + +.PHONY: vendorimage-nodeps vnod +vendorimage-nodeps vnod: | $(INTERNAL_USERIMAGES_DEPS) $(DEPMOD) + $(build-vendorimage-target) + +sync: $(INTERNAL_VENDORIMAGE_FILES) + +else ifdef BOARD_PREBUILT_VENDORIMAGE +INSTALLED_VENDORIMAGE_TARGET := $(PRODUCT_OUT)/vendor.img +$(eval $(call copy-one-file,$(BOARD_PREBUILT_VENDORIMAGE),$(INSTALLED_VENDORIMAGE_TARGET))) +endif + +# ----------------------------------------------------------------- +# product partition image +ifdef BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE +INTERNAL_PRODUCTIMAGE_FILES := \ + $(filter $(TARGET_OUT_PRODUCT)/%,\ + $(ALL_DEFAULT_INSTALLED_MODULES)\ + $(ALL_PDK_FUSION_FILES)) \ + $(PDK_FUSION_SYMLINK_STAMP) + +# platform.zip depends on $(INTERNAL_PRODUCTIMAGE_FILES). +$(INSTALLED_PLATFORM_ZIP) : $(INTERNAL_PRODUCTIMAGE_FILES) + +INSTALLED_FILES_FILE_PRODUCT := $(PRODUCT_OUT)/installed-files-product.txt +$(INSTALLED_FILES_FILE_PRODUCT) : $(INTERNAL_PRODUCTIMAGE_FILES) $(FILESLIST) + @echo Installed file list: $@ + @mkdir -p $(dir $@) + @rm -f $@ + $(hide) $(FILESLIST) $(TARGET_OUT_PRODUCT) > $(@:.txt=.json) + $(hide) build/tools/fileslist_util.py -c $(@:.txt=.json) > $@ + +productimage_intermediates := \ + $(call intermediates-dir-for,PACKAGING,product) +BUILT_PRODUCTIMAGE_TARGET := $(PRODUCT_OUT)/product.img +define build-productimage-target + $(call pretty,"Target product fs image: $(INSTALLED_PRODUCTIMAGE_TARGET)") + @mkdir -p $(TARGET_OUT_PRODUCT) + @mkdir -p $(productimage_intermediates) && rm -rf $(productimage_intermediates)/product_image_info.txt + $(call generate-userimage-prop-dictionary, $(productimage_intermediates)/product_image_info.txt, skip_fsck=true) + $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH \ + ./build/tools/releasetools/build_image.py \ + $(TARGET_OUT_PRODUCT) $(productimage_intermediates)/product_image_info.txt $(INSTALLED_PRODUCTIMAGE_TARGET) $(TARGET_OUT) + $(hide) $(call assert-max-image-size,$(INSTALLED_PRODUCTIMAGE_TARGET),$(BOARD_PRODUCTIMAGE_PARTITION_SIZE)) +endef + +# We just build this directly to the install location. +INSTALLED_PRODUCTIMAGE_TARGET := $(BUILT_PRODUCTIMAGE_TARGET) +$(INSTALLED_PRODUCTIMAGE_TARGET): $(INTERNAL_USERIMAGES_DEPS) $(INTERNAL_PRODUCTIMAGE_FILES) $(INSTALLED_FILES_FILE_PRODUCT) $(BUILD_IMAGE_SRCS) + $(build-productimage-target) + +.PHONY: productimage-nodeps pnod +productimage-nodeps pnod: | $(INTERNAL_USERIMAGES_DEPS) + $(build-productimage-target) + +sync: $(INTERNAL_PRODUCTIMAGE_FILES) + +else ifdef BOARD_PREBUILT_PRODUCTIMAGE +INSTALLED_PRODUCTIMAGE_TARGET := $(PRODUCT_OUT)/product.img +$(eval $(call copy-one-file,$(BOARD_PREBUILT_PRODUCTIMAGE),$(INSTALLED_PRODUCTIMAGE_TARGET))) +endif + +# ----------------------------------------------------------------- +# dtbo image +ifdef BOARD_PREBUILT_DTBOIMAGE +INSTALLED_DTBOIMAGE_TARGET := $(PRODUCT_OUT)/dtbo.img + +ifeq ($(BOARD_AVB_ENABLE),true) +$(INSTALLED_DTBOIMAGE_TARGET): $(BOARD_PREBUILT_DTBOIMAGE) $(AVBTOOL) $(BOARD_AVB_DTBO_KEY_PATH) + cp $(BOARD_PREBUILT_DTBOIMAGE) $@ + $(AVBTOOL) add_hash_footer \ + --image $@ \ + --partition_size $(BOARD_DTBOIMG_PARTITION_SIZE) \ + --partition_name dtbo $(INTERNAL_AVB_DTBO_SIGNING_ARGS) \ + $(BOARD_AVB_DTBO_ADD_HASH_FOOTER_ARGS) +else +$(INSTALLED_DTBOIMAGE_TARGET): $(BOARD_PREBUILT_DTBOIMAGE) + cp $(BOARD_PREBUILT_DTBOIMAGE) $@ +endif + +endif + +# ----------------------------------------------------------------- +# vbmeta image +ifeq ($(BOARD_AVB_ENABLE),true) + +BUILT_VBMETAIMAGE_TARGET := $(PRODUCT_OUT)/vbmeta.img +AVB_CHAIN_KEY_DIR := $(TARGET_OUT_INTERMEDIATES)/avb_chain_keys + +ifdef BOARD_AVB_KEY_PATH +$(if $(BOARD_AVB_ALGORITHM),,$(error BOARD_AVB_ALGORITHM is not defined)) +else +# If key path isn't specified, use the 4096-bit test key. +BOARD_AVB_ALGORITHM := SHA256_RSA4096 +BOARD_AVB_KEY_PATH := external/avb/test/data/testkey_rsa4096.pem +endif + +INTERNAL_AVB_SIGNING_ARGS := \ + --algorithm $(BOARD_AVB_ALGORITHM) --key $(BOARD_AVB_KEY_PATH) + +BOOT_FOOTER_ARGS := BOARD_AVB_BOOT_ADD_HASH_FOOTER_ARGS +DTBO_FOOTER_ARGS := BOARD_AVB_DTBO_ADD_HASH_FOOTER_ARGS +SYSTEM_FOOTER_ARGS := BOARD_AVB_SYSTEM_ADD_HASHTREE_FOOTER_ARGS +VENDOR_FOOTER_ARGS := BOARD_AVB_VENDOR_ADD_HASHTREE_FOOTER_ARGS +RECOVERY_FOOTER_ARGS := BOARD_AVB_RECOVERY_ADD_HASH_FOOTER_ARGS +PRODUCT_FOOTER_ARGS := BOARD_AVB_PRODUCT_ADD_HASHTREE_FOOTER_ARGS + +# Check and set required build variables for a chain partition. +# $(1): the partition to enable AVB chain, e.g., BOOT or SYSTEM. +define check-and-set-avb-chain-args +$(eval PART := $(1)) +$(eval part=$(call to-lower,$(PART))) + +$(eval _key_path := BOARD_AVB_$(PART)_KEY_PATH) +$(eval _signing_algorithm := BOARD_AVB_$(PART)_ALGORITHM) +$(eval _rollback_index := BOARD_AVB_$(PART)_ROLLBACK_INDEX) +$(eval _rollback_index_location := BOARD_AVB_$(PART)_ROLLBACK_INDEX_LOCATION) +$(if $($(_key_path)),,$(error $(_key_path) is not defined)) +$(if $($(_signing_algorithm)),,$(error $(_signing_algorithm) is not defined)) +$(if $($(_rollback_index)),,$(error $(_rollback_index) is not defined)) +$(if $($(_rollback_index_location)),,$(error $(_rollback_index_location) is not defined)) + +# Set INTERNAL_AVB_(PART)_SIGNING_ARGS +$(eval _signing_args := INTERNAL_AVB_$(PART)_SIGNING_ARGS) +$(eval $(_signing_args) := \ + --algorithm $($(_signing_algorithm)) --key $($(_key_path))) + +$(eval INTERNAL_AVB_MAKE_VBMETA_IMAGE_ARGS += \ + --chain_partition $(part):$($(_rollback_index_location)):$(AVB_CHAIN_KEY_DIR)/$(part).avbpubkey) + +# Set rollback_index via footer args +$(eval _footer_args := $(PART)_FOOTER_ARGS) +$(eval $($(_footer_args)) += --rollback_index $($(_rollback_index))) +endef + +ifdef BOARD_AVB_BOOT_KEY_PATH +$(eval $(call check-and-set-avb-chain-args,BOOT)) +else +INTERNAL_AVB_MAKE_VBMETA_IMAGE_ARGS += \ + --include_descriptors_from_image $(INSTALLED_BOOTIMAGE_TARGET) +endif + +ifdef BOARD_AVB_SYSTEM_KEY_PATH +$(eval $(call check-and-set-avb-chain-args,SYSTEM)) +else +INTERNAL_AVB_MAKE_VBMETA_IMAGE_ARGS += \ + --include_descriptors_from_image $(INSTALLED_SYSTEMIMAGE) +endif + +ifdef INSTALLED_VENDORIMAGE_TARGET +ifdef BOARD_AVB_VENDOR_KEY_PATH +$(eval $(call check-and-set-avb-chain-args,VENDOR)) +else +INTERNAL_AVB_MAKE_VBMETA_IMAGE_ARGS += \ + --include_descriptors_from_image $(INSTALLED_VENDORIMAGE_TARGET) +endif +endif + +ifdef INSTALLED_PRODUCTIMAGE_TARGET +ifdef BOARD_AVB_PRODUCT_KEY_PATH +$(eval $(call check-and-set-avb-chain-args,PRODUCT)) +else +INTERNAL_AVB_MAKE_VBMETA_IMAGE_ARGS += \ + --include_descriptors_from_image $(INSTALLED_PRODUCTIMAGE_TARGET) +endif +endif + +ifdef INSTALLED_DTBOIMAGE_TARGET +ifdef BOARD_AVB_DTBO_KEY_PATH +$(eval $(call check-and-set-avb-chain-args,DTBO)) +else +INTERNAL_AVB_MAKE_VBMETA_IMAGE_ARGS += \ + --include_descriptors_from_image $(INSTALLED_DTBOIMAGE_TARGET) +endif +endif + +ifdef INSTALLED_RECOVERYIMAGE_TARGET +ifdef BOARD_AVB_RECOVERY_KEY_PATH +$(eval $(call check-and-set-avb-chain-args,RECOVERY)) +else +INTERNAL_AVB_MAKE_VBMETA_IMAGE_ARGS += \ + --include_descriptors_from_image $(INSTALLED_RECOVERYIMAGE_TARGET) +endif +endif + +BOARD_AVB_MAKE_VBMETA_IMAGE_ARGS += --padding_size 4096 + +# Add kernel cmdline descriptor for kernel to mount system.img as root with +# dm-verity. This works when system.img is either chained or not-chained: +# - chained: The --setup_as_rootfs_from_kernel option will add dm-verity kernel +# cmdline descriptor to system.img +# - not-chained: The --include_descriptors_from_image option for make_vbmeta_image +# will include the kernel cmdline descriptor from system.img into vbmeta.img +ifeq ($(BOARD_BUILD_SYSTEM_ROOT_IMAGE),true) +BOARD_AVB_SYSTEM_ADD_HASHTREE_FOOTER_ARGS += --setup_as_rootfs_from_kernel +endif + +ifdef BOARD_AVB_ROLLBACK_INDEX +BOARD_AVB_MAKE_VBMETA_IMAGE_ARGS += --rollback_index $(BOARD_AVB_ROLLBACK_INDEX) +endif + +ifndef BOARD_BOOTIMAGE_PARTITION_SIZE + $(error BOARD_BOOTIMAGE_PARTITION_SIZE must be set for BOARD_AVB_ENABLE) +endif + +ifndef BOARD_SYSTEMIMAGE_PARTITION_SIZE + $(error BOARD_SYSTEMIMAGE_PARTITION_SIZE must be set for BOARD_AVB_ENABLE) +endif + +# $(1): the directory to extract public keys to +define extract-avb-chain-public-keys + $(if $(BOARD_AVB_BOOT_KEY_PATH),\ + $(hide) $(AVBTOOL) extract_public_key --key $(BOARD_AVB_BOOT_KEY_PATH) \ + --output $(1)/boot.avbpubkey) + $(if $(BOARD_AVB_SYSTEM_KEY_PATH),\ + $(hide) $(AVBTOOL) extract_public_key --key $(BOARD_AVB_SYSTEM_KEY_PATH) \ + --output $(1)/system.avbpubkey) + $(if $(BOARD_AVB_VENDOR_KEY_PATH),\ + $(hide) $(AVBTOOL) extract_public_key --key $(BOARD_AVB_VENDOR_KEY_PATH) \ + --output $(1)/vendor.avbpubkey) + $(if $(BOARD_AVB_PRODUCT_KEY_PATH),\ + $(hide) $(AVBTOOL) extract_public_key --key $(BOARD_AVB_PRODUCT_KEY_PATH) \ + --output $(1)/product.avbpubkey) + $(if $(BOARD_AVB_DTBO_KEY_PATH),\ + $(hide) $(AVBTOOL) extract_public_key --key $(BOARD_AVB_DTBO_KEY_PATH) \ + --output $(1)/dtbo.avbpubkey) + $(if $(BOARD_AVB_RECOVERY_KEY_PATH),\ + $(hide) $(AVBTOOL) extract_public_key --key $(BOARD_AVB_RECOVERY_KEY_PATH) \ + --output $(1)/recovery.avbpubkey) +endef + +define build-vbmetaimage-target + $(call pretty,"Target vbmeta image: $(INSTALLED_VBMETAIMAGE_TARGET)") + $(hide) mkdir -p $(AVB_CHAIN_KEY_DIR) + $(call extract-avb-chain-public-keys, $(AVB_CHAIN_KEY_DIR)) + $(hide) $(AVBTOOL) make_vbmeta_image \ + $(INTERNAL_AVB_MAKE_VBMETA_IMAGE_ARGS) \ + $(INTERNAL_AVB_SIGNING_ARGS) \ + $(BOARD_AVB_MAKE_VBMETA_IMAGE_ARGS) \ + --output $@ + $(hide) rm -rf $(AVB_CHAIN_KEY_DIR) +endef + +INSTALLED_VBMETAIMAGE_TARGET := $(BUILT_VBMETAIMAGE_TARGET) +$(INSTALLED_VBMETAIMAGE_TARGET): \ + $(AVBTOOL) \ + $(INSTALLED_BOOTIMAGE_TARGET) \ + $(INSTALLED_SYSTEMIMAGE) \ + $(INSTALLED_VENDORIMAGE_TARGET) \ + $(INSTALLED_PRODUCTIMAGE_TARGET) \ + $(INSTALLED_DTBOIMAGE_TARGET) \ + $(INSTALLED_RECOVERYIMAGE_TARGET) \ + $(BOARD_AVB_KEY_PATH) + $(build-vbmetaimage-target) + +.PHONY: vbmetaimage-nodeps +vbmetaimage-nodeps: + $(build-vbmetaimage-target) + +else ifeq (true,$(BOARD_BUILD_DISABLED_VBMETAIMAGE)) +BUILT_DISABLED_VBMETAIMAGE := $(PRODUCT_OUT)/vbmeta.img + +INSTALLED_VBMETAIMAGE_TARGET := $(BUILT_DISABLED_VBMETAIMAGE) +$(INSTALLED_VBMETAIMAGE_TARGET): $(AVBTOOL) + $(hide) $(AVBTOOL) make_vbmeta_image \ + --flag 2 --padding_size 4096 --output $@ + +endif # BOARD_AVB_ENABLE + +# ----------------------------------------------------------------- +# bring in the installer image generation defines if necessary +ifeq ($(TARGET_USE_DISKINSTALLER),true) +include bootable/diskinstaller/config.mk +endif + +# ----------------------------------------------------------------- +# host tools needed to build dist and OTA packages + +build_ota_package := true +ifeq ($(TARGET_SKIP_OTA_PACKAGE),true) +build_ota_package := false +endif +ifeq ($(BUILD_OS),darwin) +build_ota_package := false +endif +ifneq ($(strip $(SANITIZE_TARGET)),) +build_ota_package := false +endif +ifeq ($(TARGET_PRODUCT),sdk) +build_ota_package := false +endif +ifneq ($(filter generic%,$(TARGET_DEVICE)),) +build_ota_package := false +endif +ifeq ($(TARGET_NO_KERNEL),true) +build_ota_package := false +endif +ifeq ($(recovery_fstab),) +build_ota_package := false +endif +ifeq ($(TARGET_BUILD_PDK),true) +build_ota_package := false +endif + +ifeq ($(build_ota_package),true) +OTATOOLS := $(HOST_OUT_EXECUTABLES)/minigzip \ + $(HOST_OUT_EXECUTABLES)/aapt \ + $(HOST_OUT_EXECUTABLES)/checkvintf \ + $(HOST_OUT_EXECUTABLES)/mkbootfs \ + $(HOST_OUT_EXECUTABLES)/mkbootimg \ + $(HOST_OUT_EXECUTABLES)/fs_config \ + $(HOST_OUT_EXECUTABLES)/zipalign \ + $(HOST_OUT_EXECUTABLES)/bsdiff \ + $(HOST_OUT_EXECUTABLES)/imgdiff \ + $(HOST_OUT_JAVA_LIBRARIES)/dumpkey.jar \ + $(HOST_OUT_JAVA_LIBRARIES)/signapk.jar \ + $(HOST_OUT_JAVA_LIBRARIES)/BootSignature.jar \ + $(HOST_OUT_JAVA_LIBRARIES)/VeritySigner.jar \ + $(HOST_OUT_EXECUTABLES)/mke2fs \ + $(HOST_OUT_EXECUTABLES)/mkuserimg_mke2fs.sh \ + $(HOST_OUT_EXECUTABLES)/e2fsdroid \ + $(HOST_OUT_EXECUTABLES)/mksquashfsimage.sh \ + $(HOST_OUT_EXECUTABLES)/mksquashfs \ + $(HOST_OUT_EXECUTABLES)/mkf2fsuserimg.sh \ + $(HOST_OUT_EXECUTABLES)/make_f2fs \ + $(HOST_OUT_EXECUTABLES)/sload_f2fs \ + $(HOST_OUT_EXECUTABLES)/simg2img \ + $(HOST_OUT_EXECUTABLES)/e2fsck \ + $(HOST_OUT_EXECUTABLES)/build_verity_tree \ + $(HOST_OUT_EXECUTABLES)/generate_verity_key \ + $(HOST_OUT_EXECUTABLES)/verity_signer \ + $(HOST_OUT_EXECUTABLES)/verity_verifier \ + $(HOST_OUT_EXECUTABLES)/append2simg \ + $(HOST_OUT_EXECUTABLES)/img2simg \ + $(HOST_OUT_EXECUTABLES)/boot_signer \ + $(HOST_OUT_EXECUTABLES)/fec \ + $(HOST_OUT_EXECUTABLES)/brillo_update_payload \ + $(HOST_OUT_EXECUTABLES)/lib/shflags/shflags \ + $(HOST_OUT_EXECUTABLES)/delta_generator \ + $(AVBTOOL) \ + $(BLK_ALLOC_TO_BASE_FS) \ + $(BROTLI) + +ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT)) +OTATOOLS += \ + $(FUTILITY) \ + $(VBOOT_SIGNER) +endif + +# Shared libraries. +OTATOOLS += \ + $(HOST_LIBRARY_PATH)/libc++$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/liblog$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libcutils$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libselinux$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libcrypto_utils$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libcrypto-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libext2fs-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libext2_blkid-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libext2_com_err-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libext2_e2p-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libext2_misc$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libext2_profile-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libext2_quota-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libext2_uuid-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libconscrypt_openjdk_jni$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libbrillo$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libbrillo-stream$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libchrome$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libcurl-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libevent-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libprotobuf-cpp-lite$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libssl-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libz-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libsparse-host$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libbase$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libpcre2$(HOST_SHLIB_SUFFIX) \ + $(HOST_LIBRARY_PATH)/libbrotli$(HOST_SHLIB_SUFFIX) + + +.PHONY: otatools +otatools: $(OTATOOLS) + +BUILT_OTATOOLS_PACKAGE := $(PRODUCT_OUT)/otatools.zip +$(BUILT_OTATOOLS_PACKAGE): zip_root := $(call intermediates-dir-for,PACKAGING,otatools)/otatools + +OTATOOLS_DEPS := \ + system/extras/verity/build_verity_metadata.py \ + system/extras/ext4_utils/mke2fs.conf \ + $(sort $(shell find external/avb/test/data -type f -name "testkey_*.pem" -o \ + -name "atx_metadata.bin")) \ + $(sort $(shell find system/update_engine/scripts -name \*.pyc -prune -o -type f -print)) \ + $(sort $(shell find build/target/product/security -type f -name \*.x509.pem -o -name \*.pk8 -o \ + -name verity_key)) \ + $(sort $(shell find device $(wildcard vendor) -type f -name \*.pk8 -o -name verifiedboot\* -o \ + -name \*.x509.pem -o -name oem\*.prop)) + +OTATOOLS_RELEASETOOLS := \ + $(sort $(shell find build/make/tools/releasetools -name \*.pyc -prune -o -type f)) + +ifeq (true,$(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SUPPORTS_VBOOT)) +OTATOOLS_DEPS += \ + $(sort $(shell find external/vboot_reference/tests/devkeys -type f)) +endif + +$(BUILT_OTATOOLS_PACKAGE): $(OTATOOLS) $(OTATOOLS_DEPS) $(OTATOOLS_RELEASETOOLS) | $(ACP) + @echo "Package OTA tools: $@" + $(hide) rm -rf $@ $(zip_root) + $(hide) mkdir -p $(dir $@) $(zip_root)/bin $(zip_root)/framework $(zip_root)/releasetools + $(call copy-files-with-structure,$(OTATOOLS),$(HOST_OUT)/,$(zip_root)) + $(hide) $(ACP) -r -d -p build/make/tools/releasetools/* $(zip_root)/releasetools + $(hide) rm -rf $@ $(zip_root)/releasetools/*.pyc + $(hide) (cd $(zip_root) && zip -qryX $(abspath $@) *) + $(hide) echo $(OTATOOLS_DEPS) | xargs zip -qryX $(abspath $@)>/dev/null || true + +.PHONY: otatools-package +otatools-package: $(BUILT_OTATOOLS_PACKAGE) + +endif # build_ota_package + +# ----------------------------------------------------------------- +# A zip of the directories that map to the target filesystem. +# This zip can be used to create an OTA package or filesystem image +# as a post-build step. +# +name := $(TARGET_PRODUCT) +ifeq ($(TARGET_BUILD_TYPE),debug) + name := $(name)_debug +endif +name := $(name)-target_files-$(FILE_NAME_TAG) + +intermediates := $(call intermediates-dir-for,PACKAGING,target_files) +BUILT_TARGET_FILES_PACKAGE := $(intermediates)/$(name).zip +$(BUILT_TARGET_FILES_PACKAGE): intermediates := $(intermediates) +$(BUILT_TARGET_FILES_PACKAGE): \ + zip_root := $(intermediates)/$(name) + +# $(1): Directory to copy +# $(2): Location to copy it to +# The "ls -A" is to prevent "acp s/* d" from failing if s is empty. +define package_files-copy-root + if [ -d "$(strip $(1))" -a "$$(ls -A $(1))" ]; then \ + mkdir -p $(2) && \ + $(ACP) -rd $(strip $(1))/* $(2); \ + fi +endef + +built_ota_tools := + +# We can't build static executables when SANITIZE_TARGET=address +ifeq ($(strip $(SANITIZE_TARGET)),) +built_ota_tools += \ + $(call intermediates-dir-for,EXECUTABLES,updater,,,$(TARGET_PREFER_32_BIT))/updater +endif + +$(BUILT_TARGET_FILES_PACKAGE): PRIVATE_OTA_TOOLS := $(built_ota_tools) + +$(BUILT_TARGET_FILES_PACKAGE): PRIVATE_RECOVERY_API_VERSION := $(RECOVERY_API_VERSION) +$(BUILT_TARGET_FILES_PACKAGE): PRIVATE_RECOVERY_FSTAB_VERSION := $(RECOVERY_FSTAB_VERSION) + +ifeq ($(TARGET_RELEASETOOLS_EXTENSIONS),) +# default to common dir for device vendor +tool_extensions := $(TARGET_DEVICE_DIR)/../common +else +tool_extensions := $(TARGET_RELEASETOOLS_EXTENSIONS) +endif +tool_extension := $(wildcard $(tool_extensions)/releasetools.py) +$(BUILT_TARGET_FILES_PACKAGE): PRIVATE_TOOL_EXTENSIONS := $(tool_extensions) +$(BUILT_TARGET_FILES_PACKAGE): PRIVATE_TOOL_EXTENSION := $(tool_extension) + +ifeq ($(AB_OTA_UPDATER),true) +updater_dep := system/update_engine/update_engine.conf +else +# Build OTA tools if not using the AB Updater. +updater_dep := $(built_ota_tools) +endif +$(BUILT_TARGET_FILES_PACKAGE): $(updater_dep) + +# If we are using recovery as boot, output recovery files to BOOT/. +ifeq ($(BOARD_USES_RECOVERY_AS_BOOT),true) +$(BUILT_TARGET_FILES_PACKAGE): PRIVATE_RECOVERY_OUT := BOOT +else +$(BUILT_TARGET_FILES_PACKAGE): PRIVATE_RECOVERY_OUT := RECOVERY +endif + +ifeq ($(AB_OTA_UPDATER),true) + ifdef BRILLO_VENDOR_PARTITIONS + $(BUILT_TARGET_FILES_PACKAGE): $(foreach p,$(BRILLO_VENDOR_PARTITIONS),\ + $(call word-colon,1,$(p))/$(call word-colon,2,$(p))) + endif + ifdef OSRELEASED_DIRECTORY + $(BUILT_TARGET_FILES_PACKAGE): $(TARGET_OUT_OEM)/$(OSRELEASED_DIRECTORY)/product_id + $(BUILT_TARGET_FILES_PACKAGE): $(TARGET_OUT_OEM)/$(OSRELEASED_DIRECTORY)/product_version + $(BUILT_TARGET_FILES_PACKAGE): $(TARGET_OUT_ETC)/$(OSRELEASED_DIRECTORY)/system_version + endif +endif + +# Run fs_config while creating the target files package +# $1: root directory +# $2: add prefix +define fs_config +(cd $(1); find . -type d | sed 's,$$,/,'; find . \! -type d) | cut -c 3- | sort | sed 's,^,$(2),' | $(HOST_OUT_EXECUTABLES)/fs_config -C -D $(TARGET_OUT) -S $(SELINUX_FC) -R "$(2)" +endef + +# Depending on the various images guarantees that the underlying +# directories are up-to-date. +$(BUILT_TARGET_FILES_PACKAGE): \ + $(INSTALLED_BOOTIMAGE_TARGET) \ + $(INSTALLED_RADIOIMAGE_TARGET) \ + $(INSTALLED_RECOVERYIMAGE_TARGET) \ + $(FULL_SYSTEMIMAGE_DEPS) \ + $(INSTALLED_USERDATAIMAGE_TARGET) \ + $(INSTALLED_CACHEIMAGE_TARGET) \ + $(INSTALLED_VENDORIMAGE_TARGET) \ + $(INSTALLED_PRODUCTIMAGE_TARGET) \ + $(INSTALLED_VBMETAIMAGE_TARGET) \ + $(INSTALLED_DTBOIMAGE_TARGET) \ + $(INTERNAL_SYSTEMOTHERIMAGE_FILES) \ + $(INSTALLED_ANDROID_INFO_TXT_TARGET) \ + $(INSTALLED_KERNEL_TARGET) \ + $(INSTALLED_2NDBOOTLOADER_TARGET) \ + $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_BASE_FS_PATH) \ + $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_BASE_FS_PATH) \ + $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_BASE_FS_PATH) \ + $(SELINUX_FC) \ + $(APKCERTS_FILE) \ + $(SOONG_ZIP) \ + $(HOST_OUT_EXECUTABLES)/fs_config \ + $(HOST_OUT_EXECUTABLES)/imgdiff \ + $(HOST_OUT_EXECUTABLES)/bsdiff \ + $(BUILD_IMAGE_SRCS) \ + $(BUILT_VENDOR_MANIFEST) \ + $(BUILT_VENDOR_MATRIX) \ + | $(ACP) + @echo "Package target files: $@" + $(call create-system-vendor-symlink) + $(call create-system-product-symlink) + $(hide) rm -rf $@ $@.list $(zip_root) + $(hide) mkdir -p $(dir $@) $(zip_root) +ifneq (,$(INSTALLED_RECOVERYIMAGE_TARGET)$(filter true,$(BOARD_USES_RECOVERY_AS_BOOT))) + @# Components of the recovery image + $(hide) mkdir -p $(zip_root)/$(PRIVATE_RECOVERY_OUT) + $(hide) $(call package_files-copy-root, \ + $(TARGET_RECOVERY_ROOT_OUT),$(zip_root)/$(PRIVATE_RECOVERY_OUT)/RAMDISK) +ifdef INSTALLED_KERNEL_TARGET + $(hide) cp $(INSTALLED_KERNEL_TARGET) $(zip_root)/$(PRIVATE_RECOVERY_OUT)/kernel +endif +ifdef INSTALLED_2NDBOOTLOADER_TARGET + $(hide) cp $(INSTALLED_2NDBOOTLOADER_TARGET) $(zip_root)/$(PRIVATE_RECOVERY_OUT)/second +endif +ifdef BOARD_INCLUDE_RECOVERY_DTBO + $(hide) cp $(INSTALLED_DTBOIMAGE_TARGET) $(zip_root)/$(PRIVATE_RECOVERY_OUT)/recovery_dtbo +endif +ifdef INTERNAL_KERNEL_CMDLINE + $(hide) echo "$(INTERNAL_KERNEL_CMDLINE)" > $(zip_root)/$(PRIVATE_RECOVERY_OUT)/cmdline +endif +ifdef BOARD_KERNEL_BASE + $(hide) echo "$(BOARD_KERNEL_BASE)" > $(zip_root)/$(PRIVATE_RECOVERY_OUT)/base +endif +ifdef BOARD_KERNEL_PAGESIZE + $(hide) echo "$(BOARD_KERNEL_PAGESIZE)" > $(zip_root)/$(PRIVATE_RECOVERY_OUT)/pagesize +endif +endif # INSTALLED_RECOVERYIMAGE_TARGET defined or BOARD_USES_RECOVERY_AS_BOOT is true + @# Components of the boot image + $(hide) mkdir -p $(zip_root)/BOOT +ifeq ($(BOARD_BUILD_SYSTEM_ROOT_IMAGE),true) + $(hide) mkdir -p $(zip_root)/ROOT + $(hide) $(call package_files-copy-root, \ + $(TARGET_ROOT_OUT),$(zip_root)/ROOT) +else + $(hide) $(call package_files-copy-root, \ + $(TARGET_ROOT_OUT),$(zip_root)/BOOT/RAMDISK) +endif + @# If we are using recovery as boot, this is already done when processing recovery. +ifneq ($(BOARD_USES_RECOVERY_AS_BOOT),true) +ifdef INSTALLED_KERNEL_TARGET + $(hide) cp $(INSTALLED_KERNEL_TARGET) $(zip_root)/BOOT/kernel +endif +ifdef INSTALLED_2NDBOOTLOADER_TARGET + $(hide) cp $(INSTALLED_2NDBOOTLOADER_TARGET) $(zip_root)/BOOT/second +endif +ifdef INTERNAL_KERNEL_CMDLINE + $(hide) echo "$(INTERNAL_KERNEL_CMDLINE)" > $(zip_root)/BOOT/cmdline +endif +ifdef BOARD_KERNEL_BASE + $(hide) echo "$(BOARD_KERNEL_BASE)" > $(zip_root)/BOOT/base +endif +ifdef BOARD_KERNEL_PAGESIZE + $(hide) echo "$(BOARD_KERNEL_PAGESIZE)" > $(zip_root)/BOOT/pagesize +endif +endif # BOARD_USES_RECOVERY_AS_BOOT + $(hide) $(foreach t,$(INSTALLED_RADIOIMAGE_TARGET),\ + mkdir -p $(zip_root)/RADIO; \ + cp $(t) $(zip_root)/RADIO/$(notdir $(t));) + @# Contents of the system image + $(hide) $(call package_files-copy-root, \ + $(SYSTEMIMAGE_SOURCE_DIR),$(zip_root)/SYSTEM) + @# Contents of the data image + $(hide) $(call package_files-copy-root, \ + $(TARGET_OUT_DATA),$(zip_root)/DATA) +ifdef BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE + @# Contents of the vendor image + $(hide) $(call package_files-copy-root, \ + $(TARGET_OUT_VENDOR),$(zip_root)/VENDOR) +endif +ifdef BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE + @# Contents of the product image + $(hide) $(call package_files-copy-root, \ + $(TARGET_OUT_PRODUCT),$(zip_root)/PRODUCT) +endif +ifdef INSTALLED_SYSTEMOTHERIMAGE_TARGET + @# Contents of the system_other image + $(hide) $(call package_files-copy-root, \ + $(TARGET_OUT_SYSTEM_OTHER),$(zip_root)/SYSTEM_OTHER) +endif + @# Extra contents of the OTA package + $(hide) mkdir -p $(zip_root)/OTA + $(hide) cp $(INSTALLED_ANDROID_INFO_TXT_TARGET) $(zip_root)/OTA/ +ifneq ($(AB_OTA_UPDATER),true) +ifneq ($(built_ota_tools),) + $(hide) mkdir -p $(zip_root)/OTA/bin + $(hide) cp $(PRIVATE_OTA_TOOLS) $(zip_root)/OTA/bin/ +endif +endif + @# Files that do not end up in any images, but are necessary to + @# build them. + $(hide) mkdir -p $(zip_root)/META + $(hide) cp $(APKCERTS_FILE) $(zip_root)/META/apkcerts.txt +ifneq ($(tool_extension),) + $(hide) cp $(PRIVATE_TOOL_EXTENSION) $(zip_root)/META/ +endif + $(hide) echo "$(PRODUCT_OTA_PUBLIC_KEYS)" > $(zip_root)/META/otakeys.txt + $(hide) cp $(SELINUX_FC) $(zip_root)/META/file_contexts.bin + $(hide) echo "recovery_api_version=$(PRIVATE_RECOVERY_API_VERSION)" > $(zip_root)/META/misc_info.txt + $(hide) echo "fstab_version=$(PRIVATE_RECOVERY_FSTAB_VERSION)" >> $(zip_root)/META/misc_info.txt +ifdef BOARD_FLASH_BLOCK_SIZE + $(hide) echo "blocksize=$(BOARD_FLASH_BLOCK_SIZE)" >> $(zip_root)/META/misc_info.txt +endif +ifdef BOARD_BOOTIMAGE_PARTITION_SIZE + $(hide) echo "boot_size=$(BOARD_BOOTIMAGE_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt +endif +ifeq ($(INSTALLED_RECOVERYIMAGE_TARGET),) + $(hide) echo "no_recovery=true" >> $(zip_root)/META/misc_info.txt +endif +ifdef BOARD_INCLUDE_RECOVERY_DTBO + $(hide) echo "include_recovery_dtbo=true" >> $(zip_root)/META/misc_info.txt +endif +ifdef BOARD_RECOVERYIMAGE_PARTITION_SIZE + $(hide) echo "recovery_size=$(BOARD_RECOVERYIMAGE_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt +endif +ifdef TARGET_RECOVERY_FSTYPE_MOUNT_OPTIONS + @# TARGET_RECOVERY_FSTYPE_MOUNT_OPTIONS can be empty to indicate that nothing but defaults should be used. + $(hide) echo "recovery_mount_options=$(TARGET_RECOVERY_FSTYPE_MOUNT_OPTIONS)" >> $(zip_root)/META/misc_info.txt +else + $(hide) echo "recovery_mount_options=$(DEFAULT_TARGET_RECOVERY_FSTYPE_MOUNT_OPTIONS)" >> $(zip_root)/META/misc_info.txt +endif + $(hide) echo "tool_extensions=$(PRIVATE_TOOL_EXTENSIONS)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "default_system_dev_certificate=$(DEFAULT_SYSTEM_DEV_CERTIFICATE)" >> $(zip_root)/META/misc_info.txt +ifdef PRODUCT_EXTRA_RECOVERY_KEYS + $(hide) echo "extra_recovery_keys=$(PRODUCT_EXTRA_RECOVERY_KEYS)" >> $(zip_root)/META/misc_info.txt +endif + $(hide) echo 'mkbootimg_args=$(BOARD_MKBOOTIMG_ARGS)' >> $(zip_root)/META/misc_info.txt + $(hide) echo 'mkbootimg_version_args=$(INTERNAL_MKBOOTIMG_VERSION_ARGS)' >> $(zip_root)/META/misc_info.txt + $(hide) echo "multistage_support=1" >> $(zip_root)/META/misc_info.txt + $(hide) echo "blockimgdiff_versions=3,4" >> $(zip_root)/META/misc_info.txt +ifneq ($(OEM_THUMBPRINT_PROPERTIES),) + # OTA scripts are only interested in fingerprint related properties + $(hide) echo "oem_fingerprint_properties=$(OEM_THUMBPRINT_PROPERTIES)" >> $(zip_root)/META/misc_info.txt +endif +ifneq ($(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_BASE_FS_PATH),) + $(hide) cp $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_BASE_FS_PATH) \ + $(zip_root)/META/$(notdir $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_BASE_FS_PATH)) +endif +ifneq ($(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_BASE_FS_PATH),) + $(hide) cp $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_BASE_FS_PATH) \ + $(zip_root)/META/$(notdir $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_BASE_FS_PATH)) +endif +ifneq ($(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_BASE_FS_PATH),) + $(hide) cp $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_BASE_FS_PATH) \ + $(zip_root)/META/$(notdir $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_BASE_FS_PATH)) +endif +ifneq ($(strip $(SANITIZE_TARGET)),) + # We need to create userdata.img with real data because the instrumented libraries are in userdata.img. + $(hide) echo "userdata_img_with_data=true" >> $(zip_root)/META/misc_info.txt +endif +ifeq ($(BOARD_USES_FULL_RECOVERY_IMAGE),true) + $(hide) echo "full_recovery_image=true" >> $(zip_root)/META/misc_info.txt +endif +ifeq ($(BOARD_AVB_ENABLE),true) + $(hide) echo "avb_enable=true" >> $(zip_root)/META/misc_info.txt + $(hide) echo "avb_vbmeta_key_path=$(BOARD_AVB_KEY_PATH)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "avb_vbmeta_algorithm=$(BOARD_AVB_ALGORITHM)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "avb_vbmeta_args=$(BOARD_AVB_MAKE_VBMETA_IMAGE_ARGS)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "avb_boot_add_hash_footer_args=$(BOARD_AVB_BOOT_ADD_HASH_FOOTER_ARGS)" >> $(zip_root)/META/misc_info.txt +ifdef BOARD_AVB_BOOT_KEY_PATH + $(hide) echo "avb_boot_key_path=$(BOARD_AVB_BOOT_KEY_PATH)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "avb_boot_algorithm=$(BOARD_AVB_BOOT_ALGORITHM)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "avb_boot_rollback_index_location=$(BOARD_AVB_BOOT_ROLLBACK_INDEX_LOCATION)" >> $(zip_root)/META/misc_info.txt +endif # BOARD_AVB_BOOT_KEY_PATH + $(hide) echo "avb_recovery_add_hash_footer_args=$(BOARD_AVB_RECOVERY_ADD_HASH_FOOTER_ARGS)" >> $(zip_root)/META/misc_info.txt +ifdef BOARD_AVB_RECOVERY_KEY_PATH + $(hide) echo "avb_recovery_key_path=$(BOARD_AVB_RECOVERY_KEY_PATH)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "avb_recovery_algorithm=$(BOARD_AVB_RECOVERY_ALGORITHM)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "avb_recovery_rollback_index_location=$(BOARD_AVB_RECOVERY_ROLLBACK_INDEX_LOCATION)" >> $(zip_root)/META/misc_info.txt +endif # BOARD_AVB_RECOVERY_KEY_PATH +endif # BOARD_AVB_ENABLE +ifdef BOARD_BPT_INPUT_FILES + $(hide) echo "board_bpt_enable=true" >> $(zip_root)/META/misc_info.txt + $(hide) echo "board_bpt_make_table_args=$(BOARD_BPT_MAKE_TABLE_ARGS)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "board_bpt_input_files=$(BOARD_BPT_INPUT_FILES)" >> $(zip_root)/META/misc_info.txt +endif +ifdef BOARD_BPT_DISK_SIZE + $(hide) echo "board_bpt_disk_size=$(BOARD_BPT_DISK_SIZE)" >> $(zip_root)/META/misc_info.txt +endif + $(call generate-userimage-prop-dictionary, $(zip_root)/META/misc_info.txt) +ifneq ($(INSTALLED_RECOVERYIMAGE_TARGET),) + $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH MKBOOTIMG=$(MKBOOTIMG) \ + build/make/tools/releasetools/make_recovery_patch $(zip_root) $(zip_root) +endif +ifeq ($(AB_OTA_UPDATER),true) + @# When using the A/B updater, include the updater config files in the zip. + $(hide) cp $(TOPDIR)system/update_engine/update_engine.conf $(zip_root)/META/update_engine_config.txt + $(hide) for part in $(AB_OTA_PARTITIONS); do \ + echo "$${part}" >> $(zip_root)/META/ab_partitions.txt; \ + done + $(hide) for conf in $(AB_OTA_POSTINSTALL_CONFIG); do \ + echo "$${conf}" >> $(zip_root)/META/postinstall_config.txt; \ + done + @# Include the build type in META/misc_info.txt so the server can easily differentiate production builds. + $(hide) echo "build_type=$(TARGET_BUILD_VARIANT)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "ab_update=true" >> $(zip_root)/META/misc_info.txt +ifdef BRILLO_VENDOR_PARTITIONS + $(hide) mkdir -p $(zip_root)/VENDOR_IMAGES + $(hide) for f in $(BRILLO_VENDOR_PARTITIONS); do \ + pair1="$$(echo $$f | awk -F':' '{print $$1}')"; \ + pair2="$$(echo $$f | awk -F':' '{print $$2}')"; \ + src=$${pair1}/$${pair2}; \ + dest=$(zip_root)/VENDOR_IMAGES/$${pair2}; \ + mkdir -p $$(dirname "$${dest}"); \ + cp $${src} $${dest}; \ + done; +endif +ifdef OSRELEASED_DIRECTORY + $(hide) cp $(TARGET_OUT_OEM)/$(OSRELEASED_DIRECTORY)/product_id $(zip_root)/META/product_id.txt + $(hide) cp $(TARGET_OUT_OEM)/$(OSRELEASED_DIRECTORY)/product_version $(zip_root)/META/product_version.txt + $(hide) cp $(TARGET_OUT_ETC)/$(OSRELEASED_DIRECTORY)/system_version $(zip_root)/META/system_version.txt +endif +endif +ifeq ($(BREAKPAD_GENERATE_SYMBOLS),true) + @# If breakpad symbols have been generated, add them to the zip. + $(hide) $(ACP) -r $(TARGET_OUT_BREAKPAD) $(zip_root)/BREAKPAD +endif +# BOARD_BUILD_DISABLED_VBMETAIMAGE is used to build a special vbmeta.img +# that disables AVB verification. The content is fixed and we can just copy +# it to $(zip_root)/IMAGES without passing some info into misc_info.txt for +# regeneration. +ifeq (true,$(BOARD_BUILD_DISABLED_VBMETAIMAGE)) + $(hide) mkdir -p $(zip_root)/IMAGES + $(hide) cp $(INSTALLED_VBMETAIMAGE_TARGET) $(zip_root)/IMAGES/ +endif +ifdef BOARD_PREBUILT_VENDORIMAGE + $(hide) mkdir -p $(zip_root)/IMAGES + $(hide) cp $(INSTALLED_VENDORIMAGE_TARGET) $(zip_root)/IMAGES/ +endif +ifdef BOARD_PREBUILT_PRODUCTIMAGE + $(hide) mkdir -p $(zip_root)/IMAGES + $(hide) cp $(INSTALLED_PRODUCTIMAGE_TARGET) $(zip_root)/IMAGES/ +endif +ifdef BOARD_PREBUILT_BOOTIMAGE + $(hide) mkdir -p $(zip_root)/IMAGES + $(hide) cp $(INSTALLED_BOOTIMAGE_TARGET) $(zip_root)/IMAGES/ +endif +ifdef BOARD_PREBUILT_DTBOIMAGE + $(hide) mkdir -p $(zip_root)/PREBUILT_IMAGES + $(hide) cp $(INSTALLED_DTBOIMAGE_TARGET) $(zip_root)/PREBUILT_IMAGES/ + $(hide) echo "has_dtbo=true" >> $(zip_root)/META/misc_info.txt +ifeq ($(BOARD_AVB_ENABLE),true) + $(hide) echo "dtbo_size=$(BOARD_DTBOIMG_PARTITION_SIZE)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "avb_dtbo_add_hash_footer_args=$(BOARD_AVB_DTBO_ADD_HASH_FOOTER_ARGS)" >> $(zip_root)/META/misc_info.txt +ifdef BOARD_AVB_DTBO_KEY_PATH + $(hide) echo "avb_dtbo_key_path=$(BOARD_AVB_DTBO_KEY_PATH)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "avb_dtbo_algorithm=$(BOARD_AVB_DTBO_ALGORITHM)" >> $(zip_root)/META/misc_info.txt + $(hide) echo "avb_dtbo_rollback_index_location=$(BOARD_AVB_DTBO_ROLLBACK_INDEX_LOCATION)" \ + >> $(zip_root)/META/misc_info.txt +endif # BOARD_AVB_DTBO_KEY_PATH +endif # BOARD_AVB_ENABLE +endif # BOARD_PREBUILT_DTBOIMAGE + @# The radio images in BOARD_PACK_RADIOIMAGES will be additionally copied from RADIO/ into + @# IMAGES/, which then will be added into -img.zip. Such images must be listed in + @# INSTALLED_RADIOIMAGE_TARGET. + $(hide) $(foreach part,$(BOARD_PACK_RADIOIMAGES), \ + echo $(part) >> $(zip_root)/META/pack_radioimages.txt;) + @# Run fs_config on all the system, vendor, boot ramdisk, + @# and recovery ramdisk files in the zip, and save the output + $(hide) $(call fs_config,$(zip_root)/SYSTEM,system/) > $(zip_root)/META/filesystem_config.txt +ifdef BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE + $(hide) $(call fs_config,$(zip_root)/VENDOR,vendor/) > $(zip_root)/META/vendor_filesystem_config.txt +endif +ifdef BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE + $(hide) $(call fs_config,$(zip_root)/PRODUCT,product/) > $(zip_root)/META/product_filesystem_config.txt +endif +ifeq ($(BOARD_BUILD_SYSTEM_ROOT_IMAGE),true) + @# When using BOARD_BUILD_SYSTEM_ROOT_IMAGE, ROOT always contains the files for the root under + @# normal boot. BOOT/RAMDISK exists only if additionally using BOARD_USES_RECOVERY_AS_BOOT. + $(hide) $(call fs_config,$(zip_root)/ROOT,) > $(zip_root)/META/root_filesystem_config.txt +ifeq ($(BOARD_USES_RECOVERY_AS_BOOT),true) + $(hide) $(call fs_config,$(zip_root)/BOOT/RAMDISK,) > $(zip_root)/META/boot_filesystem_config.txt +endif +else # BOARD_BUILD_SYSTEM_ROOT_IMAGE != true + $(hide) $(call fs_config,$(zip_root)/BOOT/RAMDISK,) > $(zip_root)/META/boot_filesystem_config.txt +endif +ifneq ($(INSTALLED_RECOVERYIMAGE_TARGET),) + $(hide) $(call fs_config,$(zip_root)/RECOVERY/RAMDISK,) > $(zip_root)/META/recovery_filesystem_config.txt +endif +ifdef INSTALLED_SYSTEMOTHERIMAGE_TARGET + $(hide) $(call fs_config,$(zip_root)/SYSTEM_OTHER,system/) > $(zip_root)/META/system_other_filesystem_config.txt +endif + @# Metadata for compatibility verification. + $(hide) cp $(BUILT_SYSTEM_MANIFEST) $(zip_root)/META/system_manifest.xml + $(hide) cp $(BUILT_SYSTEM_COMPATIBILITY_MATRIX) $(zip_root)/META/system_matrix.xml +ifdef BUILT_VENDOR_MANIFEST + $(hide) cp $(BUILT_VENDOR_MANIFEST) $(zip_root)/META/vendor_manifest.xml +endif +ifdef BUILT_VENDOR_MATRIX + $(hide) cp $(BUILT_VENDOR_MATRIX) $(zip_root)/META/vendor_matrix.xml +endif + + $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH MKBOOTIMG=$(MKBOOTIMG) \ + build/make/tools/releasetools/add_img_to_target_files -a -v -p $(HOST_OUT) $(zip_root) + @# Zip everything up, preserving symlinks and placing META/ files first to + @# help early validation of the .zip file while uploading it. + $(hide) find $(zip_root)/META | sort >$@.list + $(hide) find $(zip_root) -path $(zip_root)/META -prune -o -print | sort >>$@.list + $(hide) $(SOONG_ZIP) -d -o $@ -C $(zip_root) -l $@.list + +.PHONY: target-files-package +target-files-package: $(BUILT_TARGET_FILES_PACKAGE) + +ifneq ($(filter $(MAKECMDGOALS),target-files-package),) +$(call dist-for-goals, target-files-package, $(BUILT_TARGET_FILES_PACKAGE)) +endif + +# ----------------------------------------------------------------- +# NDK Sysroot Package +NDK_SYSROOT_TARGET := $(PRODUCT_OUT)/ndk_sysroot.tar.bz2 +$(NDK_SYSROOT_TARGET): ndk + @echo Package NDK sysroot... + $(hide) tar cjf $@ -C $(SOONG_OUT_DIR) ndk + +$(call dist-for-goals,sdk,$(NDK_SYSROOT_TARGET)) + +ifeq ($(build_ota_package),true) +# ----------------------------------------------------------------- +# OTA update package + +name := $(TARGET_PRODUCT) +ifeq ($(TARGET_BUILD_TYPE),debug) + name := $(name)_debug +endif +name := $(name)-ota-$(FILE_NAME_TAG) + +INTERNAL_OTA_PACKAGE_TARGET := $(PRODUCT_OUT)/$(name).zip + +$(INTERNAL_OTA_PACKAGE_TARGET): KEY_CERT_PAIR := $(DEFAULT_KEY_CERT_PAIR) + +ifeq ($(AB_OTA_UPDATER),true) +$(INTERNAL_OTA_PACKAGE_TARGET): $(BRILLO_UPDATE_PAYLOAD) +else +$(INTERNAL_OTA_PACKAGE_TARGET): $(BROTLI) +endif + +$(INTERNAL_OTA_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) \ + build/make/tools/releasetools/ota_from_target_files + @echo "Package OTA: $@" + $(hide) PATH=$(foreach p,$(INTERNAL_USERIMAGES_BINARY_PATHS),$(p):)$$PATH MKBOOTIMG=$(MKBOOTIMG) \ + build/make/tools/releasetools/ota_from_target_files -v \ + --block \ + --extracted_input_target_files $(patsubst %.zip,%,$(BUILT_TARGET_FILES_PACKAGE)) \ + -p $(HOST_OUT) \ + -k $(KEY_CERT_PAIR) \ + $(if $(OEM_OTA_CONFIG), -o $(OEM_OTA_CONFIG)) \ + $(BUILT_TARGET_FILES_PACKAGE) $@ + +.PHONY: otapackage +otapackage: $(INTERNAL_OTA_PACKAGE_TARGET) + +endif # build_ota_package + +# ----------------------------------------------------------------- +# The update package + +name := $(TARGET_PRODUCT) +ifeq ($(TARGET_BUILD_TYPE),debug) + name := $(name)_debug +endif +name := $(name)-img-$(FILE_NAME_TAG) + +INTERNAL_UPDATE_PACKAGE_TARGET := $(PRODUCT_OUT)/$(name).zip + +$(INTERNAL_UPDATE_PACKAGE_TARGET): $(BUILT_TARGET_FILES_PACKAGE) $(ZIP2ZIP) + @echo "Package: $@" + $(hide) $(ZIP2ZIP) -i $(BUILT_TARGET_FILES_PACKAGE) -o $@ \ + OTA/android-info.txt:android-info.txt "IMAGES/*.img:." + +.PHONY: updatepackage +updatepackage: $(INTERNAL_UPDATE_PACKAGE_TARGET) + +# ----------------------------------------------------------------- +# A zip of the symbols directory. Keep the full paths to make it +# more obvious where these files came from. +# +name := $(TARGET_PRODUCT) +ifeq ($(TARGET_BUILD_TYPE),debug) + name := $(name)_debug +endif +name := $(name)-symbols-$(FILE_NAME_TAG) + +SYMBOLS_ZIP := $(PRODUCT_OUT)/$(name).zip +# For apps_only build we'll establish the dependency later in build/make/core/main.mk. +ifndef TARGET_BUILD_APPS +$(SYMBOLS_ZIP): $(INSTALLED_SYSTEMIMAGE) \ + $(INSTALLED_BOOTIMAGE_TARGET) \ + $(INSTALLED_USERDATAIMAGE_TARGET) \ + $(INSTALLED_VENDORIMAGE_TARGET) \ + $(INSTALLED_PRODUCTIMAGE_TARGET) \ + $(updater_dep) +endif +$(SYMBOLS_ZIP): PRIVATE_LIST_FILE := $(call intermediates-dir-for,PACKAGING,symbols)/filelist +$(SYMBOLS_ZIP): $(SOONG_ZIP) + @echo "Package symbols: $@" + $(hide) rm -rf $@ $(PRIVATE_LIST_FILE) + $(hide) mkdir -p $(dir $@) $(TARGET_OUT_UNSTRIPPED) $(dir $(PRIVATE_LIST_FILE)) + $(hide) find $(TARGET_OUT_UNSTRIPPED) | sort >$(PRIVATE_LIST_FILE) + $(hide) $(SOONG_ZIP) -d -o $@ -C $(OUT_DIR)/.. -l $(PRIVATE_LIST_FILE) +# ----------------------------------------------------------------- +# A zip of the coverage directory. +# +name := $(TARGET_PRODUCT) +ifeq ($(TARGET_BUILD_TYPE),debug) +name := $(name)_debug +endif +name := $(name)-coverage-$(FILE_NAME_TAG) +COVERAGE_ZIP := $(PRODUCT_OUT)/$(name).zip +ifndef TARGET_BUILD_APPS +$(COVERAGE_ZIP): $(INSTALLED_SYSTEMIMAGE) \ + $(INSTALLED_BOOTIMAGE_TARGET) \ + $(INSTALLED_USERDATAIMAGE_TARGET) \ + $(INSTALLED_VENDORIMAGE_TARGET) \ + $(INSTALLED_PRODUCTIMAGE_TARGET) +endif +$(COVERAGE_ZIP): PRIVATE_LIST_FILE := $(call intermediates-dir-for,PACKAGING,coverage)/filelist +$(COVERAGE_ZIP): $(SOONG_ZIP) + @echo "Package coverage: $@" + $(hide) rm -rf $@ $(PRIVATE_LIST_FILE) + $(hide) mkdir -p $(dir $@) $(TARGET_OUT_COVERAGE) $(dir $(PRIVATE_LIST_FILE)) + $(hide) find $(TARGET_OUT_COVERAGE) | sort >$(PRIVATE_LIST_FILE) + $(hide) $(SOONG_ZIP) -d -o $@ -C $(TARGET_OUT_COVERAGE) -l $(PRIVATE_LIST_FILE) + +# ----------------------------------------------------------------- +# A zip of the Android Apps. Not keeping full path so that we don't +# include product names when distributing +# +name := $(TARGET_PRODUCT) +ifeq ($(TARGET_BUILD_TYPE),debug) + name := $(name)_debug +endif +name := $(name)-apps-$(FILE_NAME_TAG) + +APPS_ZIP := $(PRODUCT_OUT)/$(name).zip +$(APPS_ZIP): $(INSTALLED_SYSTEMIMAGE) + @echo "Package apps: $@" + $(hide) rm -rf $@ + $(hide) mkdir -p $(dir $@) + $(hide) apps_to_zip=`find $(TARGET_OUT_APPS) $(TARGET_OUT_APPS_PRIVILEGED) -mindepth 2 -maxdepth 3 -name "*.apk"`; \ + if [ -z "$$apps_to_zip" ]; then \ + echo "No apps to zip up. Generating empty apps archive." ; \ + a=$$(mktemp /tmp/XXXXXXX) && touch $$a && zip $@ $$a && zip -d $@ $$a; \ + else \ + zip -qjX $@ $$apps_to_zip; \ + fi + +ifeq (true,$(EMMA_INSTRUMENT)) +#------------------------------------------------------------------ +# An archive of classes for use in generating code-coverage reports +# These are the uninstrumented versions of any classes that were +# to be instrumented. +# Any dependencies are set up later in build/make/core/main.mk. + +JACOCO_REPORT_CLASSES_ALL := $(PRODUCT_OUT)/jacoco-report-classes-all.jar +$(JACOCO_REPORT_CLASSES_ALL) : + @echo "Collecting uninstrumented classes" + $(hide) find $(TARGET_COMMON_OUT_ROOT) $(HOST_COMMON_OUT_ROOT) -name "jacoco-report-classes.jar" | \ + zip -@ -0 -q -X $@ +# Meaning of these options: +# -@ scan stdin for file paths to add to the zip +# -0 don't do any compression +# -q supress most output +# -X skip storing extended file attributes + +endif # EMMA_INSTRUMENT=true + + +#------------------------------------------------------------------ +# A zip of Proguard obfuscation dictionary files. +# Only for apps_only build. +# +ifdef TARGET_BUILD_APPS +PROGUARD_DICT_ZIP := $(PRODUCT_OUT)/$(TARGET_PRODUCT)-proguard-dict-$(FILE_NAME_TAG).zip +# the dependency will be set up later in build/make/core/main.mk. +$(PROGUARD_DICT_ZIP) : + @echo "Packaging Proguard obfuscation dictionary files." + $(hide) dict_files=`find $(TARGET_OUT_COMMON_INTERMEDIATES)/APPS -name proguard_dictionary`; \ + if [ -n "$$dict_files" ]; then \ + unobfuscated_jars=$${dict_files//proguard_dictionary/classes.jar}; \ + zip -qX $@ $$dict_files $$unobfuscated_jars; \ + else \ + touch $(dir $@)/zipdummy; \ + (cd $(dir $@) && zip -q $(notdir $@) zipdummy); \ + zip -qd $@ zipdummy; \ + rm $(dir $@)/zipdummy; \ + fi + +endif # TARGET_BUILD_APPS + +# ----------------------------------------------------------------- +# dalvik something +.PHONY: dalvikfiles +dalvikfiles: $(INTERNAL_DALVIK_MODULES) + +ifeq ($(BUILD_QEMU_IMAGES),true) +INSTALLED_QEMU_SYSTEMIMAGE := $(PRODUCT_OUT)/system-qemu.img +MK_QEMU_IMAGE_SH := device/generic/goldfish/tools/mk_qemu_image.sh +SGDISK_HOST := $(HOST_OUT_EXECUTABLES)/sgdisk +$(INSTALLED_QEMU_SYSTEMIMAGE): $(INSTALLED_SYSTEMIMAGE) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST) + @echo Create system-qemu.img + (export SGDISK=$(SGDISK_HOST); $(MK_QEMU_IMAGE_SH) ${PRODUCT_OUT}/system.img) + +systemimage: $(INSTALLED_QEMU_SYSTEMIMAGE) +droidcore: $(INSTALLED_QEMU_SYSTEMIMAGE) +ifeq ($(BOARD_USES_VENDORIMAGE),true) +INSTALLED_QEMU_VENDORIMAGE := $(PRODUCT_OUT)/vendor-qemu.img +$(INSTALLED_QEMU_VENDORIMAGE): $(INSTALLED_VENDORIMAGE_TARGET) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST) + @echo Create vendor-qemu.img + (export SGDISK=$(SGDISK_HOST); $(MK_QEMU_IMAGE_SH) ${PRODUCT_OUT}/vendor.img) + +vendorimage: $(INSTALLED_QEMU_VENDORIMAGE) +droidcore: $(INSTALLED_QEMU_VENDORIMAGE) +endif +ifeq ($(BOARD_USES_PRODUCTIMAGE),true) +INSTALLED_QEMU_PRODUCTIMAGE := $(PRODUCT_OUT)/product-qemu.img +$(INSTALLED_QEMU_PRODUCTIMAGE): $(INSTALLED_PRODUCTIMAGE_TARGET) $(MK_QEMU_IMAGE_SH) $(SGDISK_HOST) + @echo Create product-qemu.img + (export SGDISK=$(SGDISK_HOST); $(MK_QEMU_IMAGE_SH) ${PRODUCT_OUT}/product.img) + +productimage: $(INSTALLED_QEMU_PRODUCTIMAGE) +droidcore: $(INSTALLED_QEMU_PRODUCTIMAGE) +endif +endif +# ----------------------------------------------------------------- +# The emulator package +ifeq ($(BUILD_EMULATOR),true) +INTERNAL_EMULATOR_PACKAGE_FILES += \ + $(HOST_OUT_EXECUTABLES)/emulator$(HOST_EXECUTABLE_SUFFIX) \ + prebuilts/qemu-kernel/$(TARGET_ARCH)/kernel-qemu \ + $(INSTALLED_RAMDISK_TARGET) \ + $(INSTALLED_SYSTEMIMAGE) \ + $(INSTALLED_USERDATAIMAGE_TARGET) + +name := $(TARGET_PRODUCT)-emulator-$(FILE_NAME_TAG) + +INTERNAL_EMULATOR_PACKAGE_TARGET := $(PRODUCT_OUT)/$(name).zip + +$(INTERNAL_EMULATOR_PACKAGE_TARGET): $(INTERNAL_EMULATOR_PACKAGE_FILES) + @echo "Package: $@" + $(hide) zip -qjX $@ $(INTERNAL_EMULATOR_PACKAGE_FILES) + +endif +# ----------------------------------------------------------------- +# Old PDK stuffs, retired +# The pdk package (Platform Development Kit) + +#ifneq (,$(filter pdk,$(MAKECMDGOALS))) +# include development/pdk/Pdk.mk +#endif + + +# ----------------------------------------------------------------- +# The SDK + +# The SDK includes host-specific components, so it belongs under HOST_OUT. +sdk_dir := $(HOST_OUT)/sdk/$(TARGET_PRODUCT) + +# Build a name that looks like: +# +# linux-x86 --> android-sdk_12345_linux-x86 +# darwin-x86 --> android-sdk_12345_mac-x86 +# windows-x86 --> android-sdk_12345_windows +# +sdk_name := android-sdk_$(FILE_NAME_TAG) +ifeq ($(HOST_OS),darwin) + INTERNAL_SDK_HOST_OS_NAME := mac +else + INTERNAL_SDK_HOST_OS_NAME := $(HOST_OS) +endif +ifneq ($(HOST_OS),windows) + INTERNAL_SDK_HOST_OS_NAME := $(INTERNAL_SDK_HOST_OS_NAME)-$(SDK_HOST_ARCH) +endif +sdk_name := $(sdk_name)_$(INTERNAL_SDK_HOST_OS_NAME) + +sdk_dep_file := $(sdk_dir)/sdk_deps.mk + +ATREE_FILES := +-include $(sdk_dep_file) + +# if we don't have a real list, then use "everything" +ifeq ($(strip $(ATREE_FILES)),) +ATREE_FILES := \ + $(ALL_DEFAULT_INSTALLED_MODULES) \ + $(INSTALLED_RAMDISK_TARGET) \ + $(ALL_DOCS) \ + $(ALL_SDK_FILES) +endif + +atree_dir := development/build + + +sdk_atree_files := \ + $(atree_dir)/sdk.exclude.atree \ + $(atree_dir)/sdk-$(HOST_OS)-$(SDK_HOST_ARCH).atree + +# development/build/sdk-android-.atree is used to differentiate +# between architecture models (e.g. ARMv5TE versus ARMv7) when copying +# files like the kernel image. We use TARGET_CPU_ABI because we don't +# have a better way to distinguish between CPU models. +ifneq (,$(strip $(wildcard $(atree_dir)/sdk-android-$(TARGET_CPU_ABI).atree))) + sdk_atree_files += $(atree_dir)/sdk-android-$(TARGET_CPU_ABI).atree +endif + +ifneq ($(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SDK_ATREE_FILES),) +sdk_atree_files += $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SDK_ATREE_FILES) +else +sdk_atree_files += $(atree_dir)/sdk.atree +endif + +include $(BUILD_SYSTEM)/sdk_font.mk + +deps := \ + $(target_notice_file_txt) \ + $(tools_notice_file_txt) \ + $(OUT_DOCS)/offline-sdk-timestamp \ + $(SYMBOLS_ZIP) \ + $(COVERAGE_ZIP) \ + $(INSTALLED_SYSTEMIMAGE) \ + $(INSTALLED_QEMU_SYSTEMIMAGE) \ + $(INSTALLED_QEMU_VENDORIMAGE) \ + $(INSTALLED_USERDATAIMAGE_TARGET) \ + $(INSTALLED_RAMDISK_TARGET) \ + $(INSTALLED_SDK_BUILD_PROP_TARGET) \ + $(INSTALLED_BUILD_PROP_TARGET) \ + $(ATREE_FILES) \ + $(sdk_atree_files) \ + $(HOST_OUT_EXECUTABLES)/atree \ + $(HOST_OUT_EXECUTABLES)/line_endings \ + $(SDK_FONT_DEPS) + +INTERNAL_SDK_TARGET := $(sdk_dir)/$(sdk_name).zip +$(INTERNAL_SDK_TARGET): PRIVATE_NAME := $(sdk_name) +$(INTERNAL_SDK_TARGET): PRIVATE_DIR := $(sdk_dir)/$(sdk_name) +$(INTERNAL_SDK_TARGET): PRIVATE_DEP_FILE := $(sdk_dep_file) +$(INTERNAL_SDK_TARGET): PRIVATE_INPUT_FILES := $(sdk_atree_files) + +# Set SDK_GNU_ERROR to non-empty to fail when a GNU target is built. +# +#SDK_GNU_ERROR := true + +$(INTERNAL_SDK_TARGET): $(deps) + @echo "Package SDK: $@" + $(hide) rm -rf $(PRIVATE_DIR) $@ + $(hide) for f in $(target_gnu_MODULES); do \ + if [ -f $$f ]; then \ + echo SDK: $(if $(SDK_GNU_ERROR),ERROR:,warning:) \ + including GNU target $$f >&2; \ + FAIL=$(SDK_GNU_ERROR); \ + fi; \ + done; \ + if [ $$FAIL ]; then exit 1; fi + $(hide) echo $(notdir $(SDK_FONT_DEPS)) | tr " " "\n" > $(SDK_FONT_TEMP)/fontsInSdk.txt + $(hide) ( \ + ATREE_STRIP="strip -x" \ + $(HOST_OUT_EXECUTABLES)/atree \ + $(addprefix -f ,$(PRIVATE_INPUT_FILES)) \ + -m $(PRIVATE_DEP_FILE) \ + -I . \ + -I $(PRODUCT_OUT) \ + -I $(HOST_OUT) \ + -I $(TARGET_COMMON_OUT_ROOT) \ + -v "PLATFORM_NAME=android-$(PLATFORM_VERSION)" \ + -v "OUT_DIR=$(OUT_DIR)" \ + -v "HOST_OUT=$(HOST_OUT)" \ + -v "TARGET_ARCH=$(TARGET_ARCH)" \ + -v "TARGET_CPU_ABI=$(TARGET_CPU_ABI)" \ + -v "DLL_EXTENSION=$(HOST_SHLIB_SUFFIX)" \ + -v "FONT_OUT=$(SDK_FONT_TEMP)" \ + -o $(PRIVATE_DIR) && \ + cp -f $(target_notice_file_txt) \ + $(PRIVATE_DIR)/system-images/android-$(PLATFORM_VERSION)/$(TARGET_CPU_ABI)/NOTICE.txt && \ + cp -f $(tools_notice_file_txt) $(PRIVATE_DIR)/platform-tools/NOTICE.txt && \ + HOST_OUT_EXECUTABLES=$(HOST_OUT_EXECUTABLES) HOST_OS=$(HOST_OS) \ + development/build/tools/sdk_clean.sh $(PRIVATE_DIR) && \ + chmod -R ug+rwX $(PRIVATE_DIR) && \ + cd $(dir $@) && zip -rqX $(notdir $@) $(PRIVATE_NAME) \ + ) || ( rm -rf $(PRIVATE_DIR) $@ && exit 44 ) + + +# Is a Windows SDK requested? If so, we need some definitions from here +# in order to find the Linux SDK used to create the Windows one. +MAIN_SDK_NAME := $(sdk_name) +MAIN_SDK_DIR := $(sdk_dir) +MAIN_SDK_ZIP := $(INTERNAL_SDK_TARGET) +ifneq ($(filter win_sdk winsdk-tools,$(MAKECMDGOALS)),) +include $(TOPDIR)development/build/tools/windows_sdk.mk +endif + +# ----------------------------------------------------------------- +# Findbugs +INTERNAL_FINDBUGS_XML_TARGET := $(PRODUCT_OUT)/findbugs.xml +INTERNAL_FINDBUGS_HTML_TARGET := $(PRODUCT_OUT)/findbugs.html +$(INTERNAL_FINDBUGS_XML_TARGET): $(ALL_FINDBUGS_FILES) + @echo UnionBugs: $@ + $(hide) $(FINDBUGS_DIR)/unionBugs $(ALL_FINDBUGS_FILES) \ + > $@ +$(INTERNAL_FINDBUGS_HTML_TARGET): $(INTERNAL_FINDBUGS_XML_TARGET) + @echo ConvertXmlToText: $@ + $(hide) $(FINDBUGS_DIR)/convertXmlToText -html:fancy.xsl \ + $(INTERNAL_FINDBUGS_XML_TARGET) > $@ + +# ----------------------------------------------------------------- +# Findbugs + +# ----------------------------------------------------------------- +# These are some additional build tasks that need to be run. +ifneq ($(dont_bother),true) +include $(sort $(wildcard $(BUILD_SYSTEM)/tasks/*.mk)) +-include $(sort $(wildcard vendor/*/build/tasks/*.mk)) +-include $(sort $(wildcard device/*/build/tasks/*.mk)) +-include $(sort $(wildcard product/*/build/tasks/*.mk)) +# Also the project-specific tasks +-include $(sort $(wildcard vendor/*/*/build/tasks/*.mk)) +-include $(sort $(wildcard device/*/*/build/tasks/*.mk)) +-include $(sort $(wildcard product/*/*/build/tasks/*.mk)) +# Also add test specifc tasks +include $(sort $(wildcard platform_testing/build/tasks/*.mk)) +include $(sort $(wildcard test/vts/tools/build/tasks/*.mk)) +endif + +include $(BUILD_SYSTEM)/product-graph.mk + +# ----------------------------------------------------------------- +# Create SDK repository packages. Must be done after tasks/* since +# we need the addon rules defined. +ifneq ($(sdk_repo_goal),) +include $(TOPDIR)development/build/tools/sdk_repo.mk +endif + +#------------------------------------------------------------------ +# Find lsdump paths +FIND_LSDUMPS_FILE := $(PRODUCT_OUT)/lsdump_paths.txt +$(FIND_LSDUMPS_FILE) : $(LSDUMP_PATHS) + $(hide) rm -rf $@ && echo "$^" > $@ diff --git a/aosp/build/make/core/main.mk b/aosp/build/make/core/main.mk new file mode 100644 index 000000000..0a456ff75 --- /dev/null +++ b/aosp/build/make/core/main.mk @@ -0,0 +1,1294 @@ +# Only use ANDROID_BUILD_SHELL to wrap around bash. +# DO NOT use other shells such as zsh. +ifdef ANDROID_BUILD_SHELL +SHELL := $(ANDROID_BUILD_SHELL) +else +# Use bash, not whatever shell somebody has installed as /bin/sh +# This is repeated in config.mk, since envsetup.sh runs that file +# directly. +SHELL := /bin/bash +endif + +ifndef KATI + +host_prebuilts := linux-x86 +ifeq ($(shell uname),Darwin) +host_prebuilts := darwin-x86 +endif + +.PHONY: run_soong_ui +run_soong_ui: + +@prebuilts/build-tools/$(host_prebuilts)/bin/makeparallel --ninja build/soong/soong_ui.bash --make-mode $(MAKECMDGOALS) + +.PHONY: $(MAKECMDGOALS) +$(sort $(MAKECMDGOALS)) : run_soong_ui + @#empty + +else # KATI + +# Absolute path of the present working direcotry. +# This overrides the shell variable $PWD, which does not necessarily points to +# the top of the source tree, for example when "make -C" is used in m/mm/mmm. +PWD := $(shell pwd) + +TOP := . +TOPDIR := + +BUILD_SYSTEM := $(TOPDIR)build/make/core + +# This is the default target. It must be the first declared target. +.PHONY: droid +DEFAULT_GOAL := droid +$(DEFAULT_GOAL): droid_targets + +.PHONY: droid_targets +droid_targets: + +# Set up various standard variables based on configuration +# and host information. +include $(BUILD_SYSTEM)/config.mk + +ifneq ($(filter $(dont_bother_goals), $(MAKECMDGOALS)),) +dont_bother := true +endif + +.KATI_READONLY := SOONG_CONFIG_NAMESPACES +.KATI_READONLY := $(foreach n,$(SOONG_CONFIG_NAMESPACES),SOONG_CONFIG_$(n)) +.KATI_READONLY := $(foreach n,$(SOONG_CONFIG_NAMESPACES),$(foreach k,$(SOONG_CONFIG_$(n)),SOONG_CONFIG_$(n)_$(k))) + +include $(SOONG_MAKEVARS_MK) + +include $(BUILD_SYSTEM)/clang/config.mk + +# Write the build number to a file so it can be read back in +# without changing the command line every time. Avoids rebuilds +# when using ninja. +$(shell mkdir -p $(OUT_DIR) && \ + echo -n $(BUILD_NUMBER) > $(OUT_DIR)/build_number.txt) +BUILD_NUMBER_FILE := $(OUT_DIR)/build_number.txt + +ifeq ($(HOST_OS),darwin) +DATE_FROM_FILE := date -r $(BUILD_DATETIME_FROM_FILE) +else +DATE_FROM_FILE := date -d @$(BUILD_DATETIME_FROM_FILE) +endif + +# Pick a reasonable string to use to identify files. +ifeq ($(strip $(HAS_BUILD_NUMBER)),false) + # BUILD_NUMBER has a timestamp in it, which means that + # it will change every time. Pick a stable value. + FILE_NAME_TAG := eng.$(USER) +else + FILE_NAME_TAG := $(file <$(BUILD_NUMBER_FILE)) +endif + +# Make an empty directory, which can be used to make empty jars +EMPTY_DIRECTORY := $(OUT_DIR)/empty +$(shell mkdir -p $(EMPTY_DIRECTORY) && rm -rf $(EMPTY_DIRECTORY)/*) + +# CTS-specific config. +-include cts/build/config.mk +# VTS-specific config. +-include test/vts/tools/vts-tradefed/build/config.mk +# device-tests-specific-config. +-include tools/tradefederation/build/suites/device-tests/config.mk +# general-tests-specific-config. +-include tools/tradefederation/build/suites/general-tests/config.mk +# STS-specific config. +-include test/sts/tools/sts-tradefed/build/config.mk +# CTS-Instant-specific config +-include test/suite_harness/tools/cts-instant-tradefed/build/config.mk + +# Clean rules +.PHONY: clean-dex-files +clean-dex-files: + $(hide) find $(OUT_DIR) -name "*.dex" | xargs rm -f + $(hide) for i in `find $(OUT_DIR) -name "*.jar" -o -name "*.apk"` ; do ((unzip -l $$i 2> /dev/null | \ + grep -q "\.dex$$" && rm -f $$i) || continue ) ; done + @echo "All dex files and archives containing dex files have been removed." + +# Include the google-specific config +-include vendor/google/build/config.mk + +# These are the modifier targets that don't do anything themselves, but +# change the behavior of the build. +# (must be defined before including definitions.make) +INTERNAL_MODIFIER_TARGETS := all + +# EMMA_INSTRUMENT_STATIC merges the static jacoco library to each +# jacoco-enabled module. +ifeq (true,$(EMMA_INSTRUMENT_STATIC)) +EMMA_INSTRUMENT := true +endif + +ifeq (true,$(EMMA_INSTRUMENT)) +# Adding the jacoco library can cause the inclusion of +# some typically banned classes +# So if the user didn't specify SKIP_BOOT_JARS_CHECK, enable it here +ifndef SKIP_BOOT_JARS_CHECK +SKIP_BOOT_JARS_CHECK := true +endif +endif + +# +# ----------------------------------------------------------------- +# Validate ADDITIONAL_DEFAULT_PROPERTIES. +ifneq ($(ADDITIONAL_DEFAULT_PROPERTIES),) +$(error ADDITIONAL_DEFAULT_PROPERTIES must not be set before here: $(ADDITIONAL_DEFAULT_PROPERTIES)) +endif + +# +# ----------------------------------------------------------------- +# Validate ADDITIONAL_BUILD_PROPERTIES. +ifneq ($(ADDITIONAL_BUILD_PROPERTIES),) +$(error ADDITIONAL_BUILD_PROPERTIES must not be set before here: $(ADDITIONAL_BUILD_PROPERTIES)) +endif + +ADDITIONAL_BUILD_PROPERTIES := + +# +# ----------------------------------------------------------------- +# Add the product-defined properties to the build properties. +ifdef PRODUCT_SHIPPING_API_LEVEL +ADDITIONAL_BUILD_PROPERTIES += \ + ro.product.first_api_level=$(PRODUCT_SHIPPING_API_LEVEL) +endif + +ifneq ($(BOARD_PROPERTY_OVERRIDES_SPLIT_ENABLED), true) + ADDITIONAL_BUILD_PROPERTIES += $(PRODUCT_PROPERTY_OVERRIDES) +else + ifndef BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE + ADDITIONAL_BUILD_PROPERTIES += $(PRODUCT_PROPERTY_OVERRIDES) + endif +endif + + +# Bring in standard build system definitions. +include $(BUILD_SYSTEM)/definitions.mk + +# Bring in dex_preopt.mk +include $(BUILD_SYSTEM)/dex_preopt.mk + +ifneq ($(filter user userdebug eng,$(MAKECMDGOALS)),) +$(info ***************************************************************) +$(info ***************************************************************) +$(info Do not pass '$(filter user userdebug eng,$(MAKECMDGOALS))' on \ + the make command line.) +$(info Set TARGET_BUILD_VARIANT in buildspec.mk, or use lunch or) +$(info choosecombo.) +$(info ***************************************************************) +$(info ***************************************************************) +$(error stopping) +endif + +ifneq ($(filter-out $(INTERNAL_VALID_VARIANTS),$(TARGET_BUILD_VARIANT)),) +$(info ***************************************************************) +$(info ***************************************************************) +$(info Invalid variant: $(TARGET_BUILD_VARIANT)) +$(info Valid values are: $(INTERNAL_VALID_VARIANTS)) +$(info ***************************************************************) +$(info ***************************************************************) +$(error stopping) +endif + +# ----------------------------------------------------------------- +# Variable to check java support level inside PDK build. +# Not necessary if the components is not in PDK. +# not defined : not supported +# "sdk" : sdk API only +# "platform" : platform API supproted +TARGET_BUILD_JAVA_SUPPORT_LEVEL := platform + +# ----------------------------------------------------------------- +# The pdk (Platform Development Kit) build +include build/make/core/pdk_config.mk + +# +# ----------------------------------------------------------------- +# Enable dynamic linker and hidden API developer warnings for +# userdebug, eng and non-REL builds +ifneq ($(TARGET_BUILD_VARIANT),user) + ADDITIONAL_BUILD_PROPERTIES += ro.bionic.ld.warning=1 \ + ro.art.hiddenapi.warning=1 +else +# Enable it for user builds as long as they are not final. +ifneq ($(PLATFORM_VERSION_CODENAME),REL) + ADDITIONAL_BUILD_PROPERTIES += ro.bionic.ld.warning=1 \ + ro.art.hiddenapi.warning=1 +endif +endif + +ADDITIONAL_BUILD_PROPERTIES += ro.treble.enabled=${PRODUCT_FULL_TREBLE} + +$(KATI_obsolete_var PRODUCT_FULL_TREBLE,\ + Code should be written to work regardless of a device being Treble or \ + variables like PRODUCT_SEPOLICY_SPLIT should be used until that is \ + possible.) + +# Sets ro.actionable_compatible_property.enabled to know on runtime whether the whitelist +# of actionable compatible properties is enabled or not. +ifeq ($(PRODUCT_ACTIONABLE_COMPATIBLE_PROPERTY_DISABLE),true) +ADDITIONAL_DEFAULT_PROPERTIES += ro.actionable_compatible_property.enabled=false +else +ADDITIONAL_DEFAULT_PROPERTIES += ro.actionable_compatible_property.enabled=${PRODUCT_COMPATIBLE_PROPERTY} +endif + +# ----------------------------------------------------------------- +### +### In this section we set up the things that are different +### between the build variants +### + +is_sdk_build := + +ifneq ($(filter sdk win_sdk sdk_addon,$(MAKECMDGOALS)),) +is_sdk_build := true +endif + +# Add build properties for ART. These define system properties used by installd +# to pass flags to dex2oat. +ADDITIONAL_BUILD_PROPERTIES += persist.sys.dalvik.vm.lib.2=libart.so +ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.isa.$(TARGET_ARCH).variant=$(DEX2OAT_TARGET_CPU_VARIANT) +ifneq ($(DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES),) + ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.isa.$(TARGET_ARCH).features=$(DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES) +endif + +ifdef TARGET_2ND_ARCH + ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.isa.$(TARGET_2ND_ARCH).variant=$($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_CPU_VARIANT) + ifneq ($($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES),) + ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.isa.$(TARGET_2ND_ARCH).features=$($(TARGET_2ND_ARCH_VAR_PREFIX)DEX2OAT_TARGET_INSTRUCTION_SET_FEATURES) + endif +endif + +# Add the system server compiler filter if they are specified for the product. +ifneq (,$(PRODUCT_SYSTEM_SERVER_COMPILER_FILTER)) +ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.systemservercompilerfilter=$(PRODUCT_SYSTEM_SERVER_COMPILER_FILTER) +endif + +## user/userdebug ## + +user_variant := $(filter user userdebug,$(TARGET_BUILD_VARIANT)) +enable_target_debugging := true +tags_to_install := +ifneq (,$(user_variant)) + # Target is secure in user builds. + ADDITIONAL_DEFAULT_PROPERTIES += ro.secure=1 + ADDITIONAL_DEFAULT_PROPERTIES += security.perf_harden=1 + + ifeq ($(user_variant),user) + ADDITIONAL_DEFAULT_PROPERTIES += ro.adb.secure=1 + endif + + ifeq ($(user_variant),userdebug) + # Pick up some extra useful tools + tags_to_install += debug + else + # Disable debugging in plain user builds. + enable_target_debugging := + endif + + # Disallow mock locations by default for user builds + ADDITIONAL_DEFAULT_PROPERTIES += ro.allow.mock.location=0 + +else # !user_variant + # Turn on checkjni for non-user builds. + ADDITIONAL_BUILD_PROPERTIES += ro.kernel.android.checkjni=1 + # Set device insecure for non-user builds. + ADDITIONAL_DEFAULT_PROPERTIES += ro.secure=0 + # Allow mock locations by default for non user builds + ADDITIONAL_DEFAULT_PROPERTIES += ro.allow.mock.location=1 +endif # !user_variant + +ifeq (true,$(strip $(enable_target_debugging))) + # Target is more debuggable and adbd is on by default + ADDITIONAL_DEFAULT_PROPERTIES += ro.debuggable=1 + # Enable Dalvik lock contention logging. + ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.lockprof.threshold=500 + # Include the debugging/testing OTA keys in this build. + INCLUDE_TEST_OTA_KEYS := true +else # !enable_target_debugging + # Target is less debuggable and adbd is off by default + ADDITIONAL_DEFAULT_PROPERTIES += ro.debuggable=0 +endif # !enable_target_debugging + +## eng ## + +ifeq ($(TARGET_BUILD_VARIANT),eng) +tags_to_install := debug eng +ifneq ($(filter ro.setupwizard.mode=ENABLED, $(call collapse-pairs, $(ADDITIONAL_BUILD_PROPERTIES))),) + # Don't require the setup wizard on eng builds + ADDITIONAL_BUILD_PROPERTIES := $(filter-out ro.setupwizard.mode=%,\ + $(call collapse-pairs, $(ADDITIONAL_BUILD_PROPERTIES))) \ + ro.setupwizard.mode=OPTIONAL +endif +ifndef is_sdk_build + # To speedup startup of non-preopted builds, don't verify or compile the boot image. + ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.image-dex2oat-filter=verify-at-runtime +endif +endif + +## sdk ## + +ifdef is_sdk_build + +# Detect if we want to build a repository for the SDK +sdk_repo_goal := $(strip $(filter sdk_repo,$(MAKECMDGOALS))) +MAKECMDGOALS := $(strip $(filter-out sdk_repo,$(MAKECMDGOALS))) + +ifneq ($(words $(sort $(filter-out $(INTERNAL_MODIFIER_TARGETS) checkbuild emulator_tests target-files-package,$(MAKECMDGOALS)))),1) +$(error The 'sdk' target may not be specified with any other targets) +endif + +# AUX dependencies are already added by now; remove triggers from the MAKECMDGOALS +MAKECMDGOALS := $(strip $(filter-out AUX-%,$(MAKECMDGOALS))) + +# TODO: this should be eng I think. Since the sdk is built from the eng +# variant. +tags_to_install := debug eng +ADDITIONAL_BUILD_PROPERTIES += xmpp.auto-presence=true +ADDITIONAL_BUILD_PROPERTIES += ro.config.nocheckin=yes +else # !sdk +endif + +BUILD_WITHOUT_PV := true + +ADDITIONAL_BUILD_PROPERTIES += net.bt.name=Android + +# Sets the location that the runtime dumps stack traces to when signalled +# with SIGQUIT. Stack trace dumping is turned on for all android builds. +ADDITIONAL_BUILD_PROPERTIES += dalvik.vm.stack-trace-dir=/data/anr + +# ------------------------------------------------------------ +# Define a function that, given a list of module tags, returns +# non-empty if that module should be installed in /system. + +# For most goals, anything not tagged with the "tests" tag should +# be installed in /system. +define should-install-to-system +$(if $(filter tests,$(1)),,true) +endef + +ifdef is_sdk_build +# For the sdk goal, anything with the "samples" tag should be +# installed in /data even if that module also has "eng"/"debug"/"user". +define should-install-to-system +$(if $(filter samples tests,$(1)),,true) +endef +endif + + +# If they only used the modifier goals (all, etc), we'll actually +# build the default target. +ifeq ($(filter-out $(INTERNAL_MODIFIER_TARGETS),$(MAKECMDGOALS)),) +.PHONY: $(INTERNAL_MODIFIER_TARGETS) +$(INTERNAL_MODIFIER_TARGETS): $(DEFAULT_GOAL) +endif + +# +# Typical build; include any Android.mk files we can find. +# + +FULL_BUILD := true + +# Before we go and include all of the module makefiles, mark the PRODUCT_* +# and ADDITIONAL*PROPERTIES values readonly so that they won't be modified. +$(call readonly-product-vars) +ADDITIONAL_DEFAULT_PROPERTIES := $(strip $(ADDITIONAL_DEFAULT_PROPERTIES)) +.KATI_READONLY := ADDITIONAL_DEFAULT_PROPERTIES +ADDITIONAL_BUILD_PROPERTIES := $(strip $(ADDITIONAL_BUILD_PROPERTIES)) +.KATI_READONLY := ADDITIONAL_BUILD_PROPERTIES + +ifneq ($(PRODUCT_ENFORCE_RRO_TARGETS),) +ENFORCE_RRO_SOURCES := +endif + +ifneq ($(ONE_SHOT_MAKEFILE),) +# We've probably been invoked by the "mm" shell function +# with a subdirectory's makefile. +include $(SOONG_ANDROID_MK) $(wildcard $(ONE_SHOT_MAKEFILE)) +# Change CUSTOM_MODULES to include only modules that were +# defined by this makefile; this will install all of those +# modules as a side-effect. Do this after including ONE_SHOT_MAKEFILE +# so that the modules will be installed in the same place they +# would have been with a normal make. +CUSTOM_MODULES := $(sort $(call get-tagged-modules,$(ALL_MODULE_TAGS))) +FULL_BUILD := +# Stub out the notice targets, which probably aren't defined +# when using ONE_SHOT_MAKEFILE. +NOTICE-HOST-%: ; +NOTICE-TARGET-%: ; + +# A helper goal printing out install paths +define register_module_install_path +.PHONY: GET-MODULE-INSTALL-PATH-$(1) +GET-MODULE-INSTALL-PATH-$(1): + echo 'INSTALL-PATH: $(1) $(ALL_MODULES.$(1).INSTALLED)' +endef + +SORTED_ALL_MODULES := $(sort $(ALL_MODULES)) +UNIQUE_ALL_MODULES := +$(foreach m,$(SORTED_ALL_MODULES),\ + $(if $(call streq,$(m),$(lastword $(UNIQUE_ALL_MODULES))),,\ + $(eval UNIQUE_ALL_MODULES += $(m)))) +SORTED_ALL_MODULES := + +$(foreach mod,$(UNIQUE_ALL_MODULES),$(if $(ALL_MODULES.$(mod).INSTALLED),\ + $(eval $(call register_module_install_path,$(mod)))\ + $(foreach path,$(ALL_MODULES.$(mod).PATH),\ + $(eval my_path_prefix := GET-INSTALL-PATH-IN)\ + $(foreach component,$(subst /,$(space),$(path)),\ + $(eval my_path_prefix := $$(my_path_prefix)-$$(component))\ + $(eval .PHONY: $$(my_path_prefix))\ + $(eval $$(my_path_prefix): GET-MODULE-INSTALL-PATH-$(mod)))))) +UNIQUE_ALL_MODULES := + +else # ONE_SHOT_MAKEFILE + +ifneq ($(dont_bother),true) +# +# Include all of the makefiles in the system +# + +subdir_makefiles := $(SOONG_ANDROID_MK) $(file <$(OUT_DIR)/.module_paths/Android.mk.list) +subdir_makefiles_total := $(words $(subdir_makefiles)) +.KATI_READONLY := subdir_makefiles_total + +$(foreach mk,$(subdir_makefiles),$(info [$(call inc_and_print,subdir_makefiles_inc)/$(subdir_makefiles_total)] including $(mk) ...)$(eval include $(mk))) + +ifneq (,$(PDK_FUSION_PLATFORM_ZIP)$(PDK_FUSION_PLATFORM_DIR)) +# Bring in the PDK platform.zip modules. +include $(BUILD_SYSTEM)/pdk_fusion_modules.mk +endif # PDK_FUSION_PLATFORM_ZIP || PDK_FUSION_PLATFORM_DIR + +droid_targets : blueprint_tools + +endif # dont_bother + +endif # ONE_SHOT_MAKEFILE + +# ------------------------------------------------------------------- +# All module makefiles have been included at this point. +# ------------------------------------------------------------------- + +# ------------------------------------------------------------------- +# Enforce to generate all RRO packages for modules having resource +# overlays. +# ------------------------------------------------------------------- +ifneq ($(PRODUCT_ENFORCE_RRO_TARGETS),) +$(call generate_all_enforce_rro_packages) +endif + +# ------------------------------------------------------------------- +# Fix up CUSTOM_MODULES to refer to installed files rather than +# just bare module names. Leave unknown modules alone in case +# they're actually full paths to a particular file. +known_custom_modules := $(filter $(ALL_MODULES),$(CUSTOM_MODULES)) +unknown_custom_modules := $(filter-out $(ALL_MODULES),$(CUSTOM_MODULES)) +CUSTOM_MODULES := \ + $(call module-installed-files,$(known_custom_modules)) \ + $(unknown_custom_modules) + +# ------------------------------------------------------------------- +# Define dependencies for modules that require other modules. +# This can only happen now, after we've read in all module makefiles. +# +# TODO: deal with the fact that a bare module name isn't +# unambiguous enough. Maybe declare short targets like +# APPS:Quake or HOST:SHARED_LIBRARIES:libutils. +# BUG: the system image won't know to depend on modules that are +# brought in as requirements of other modules. +# +# Resolve the required module name to 32-bit or 64-bit variant. +# Get a list of corresponding 32-bit module names, if one exists. +ifneq ($(TARGET_TRANSLATE_2ND_ARCH),true) +define get-32-bit-modules +$(sort $(foreach m,$(1),\ + $(if $(ALL_MODULES.$(m)$(TARGET_2ND_ARCH_MODULE_SUFFIX).CLASS),\ + $(m)$(TARGET_2ND_ARCH_MODULE_SUFFIX))\ + $(if $(ALL_MODULES.$(m)$(HOST_2ND_ARCH_MODULE_SUFFIX).CLASS),\ + $(m)$(HOST_2ND_ARCH_MODULE_SUFFIX))\ + )) +endef +# Get a list of corresponding 32-bit module names, if one exists; +# otherwise return the original module name +define get-32-bit-modules-if-we-can +$(sort $(foreach m,$(1),\ + $(if $(ALL_MODULES.$(m)$(TARGET_2ND_ARCH_MODULE_SUFFIX).CLASS)$(ALL_MODULES.$(m)$(HOST_2ND_ARCH_MODULE_SUFFIX).CLASS),\ + $(if $(ALL_MODULES.$(m)$(TARGET_2ND_ARCH_MODULE_SUFFIX).CLASS),$(m)$(TARGET_2ND_ARCH_MODULE_SUFFIX)) \ + $(if $(ALL_MODULES.$(m)$(HOST_2ND_ARCH_MODULE_SUFFIX).CLASS),$(m)$(HOST_2ND_ARCH_MODULE_SUFFIX)),\ + $(m)))) +endef +else # TARGET_TRANSLATE_2ND_ARCH +# For binary translation config, by default only install the first arch. +define get-32-bit-modules +endef + +define get-32-bit-modules-if-we-can +$(strip $(1)) +endef +endif # TARGET_TRANSLATE_2ND_ARCH + +# If a module is for a cross host os, the required modules must be for +# that OS too. +# If a module is built for 32-bit, the required modules must be 32-bit too; +# Otherwise if the module is an executable or shared library, +# the required modules must be 64-bit; +# otherwise we require both 64-bit and 32-bit variant, if one exists. +define select-bitness-of-required-modules +$(foreach m,$(ALL_MODULES),\ + $(eval r := $(ALL_MODULES.$(m).REQUIRED))\ + $(if $(r),\ + $(if $(ALL_MODULES.$(m).FOR_HOST_CROSS),\ + $(eval r := $(addprefix host_cross_,$(r))))\ + $(if $(ALL_MODULES.$(m).FOR_2ND_ARCH),\ + $(eval r_r := $(call get-32-bit-modules-if-we-can,$(r))),\ + $(if $(filter EXECUTABLES SHARED_LIBRARIES NATIVE_TESTS,$(ALL_MODULES.$(m).CLASS)),\ + $(eval r_r := $(r)),\ + $(eval r_r := $(r) $(call get-32-bit-modules,$(r)))\ + )\ + )\ + $(eval ALL_MODULES.$(m).REQUIRED := $(strip $(r_r)))\ + )\ +) +endef +$(call select-bitness-of-required-modules) +r_r := + +define add-required-deps +$(1): | $(2) +endef + +# Use a normal dependency instead of an order-only dependency when installing +# host dynamic binaries so that the timestamp of the final binary always +# changes, even if the toc optimization has skipped relinking the binary +# and its dependant shared libraries. +define add-required-host-so-deps +$(1): $(2) +endef + +# Sets up dependencies such that whenever a host module is installed, +# any other host modules listed in $(ALL_MODULES.$(m).REQUIRED) will also be installed +define add-all-host-to-host-required-modules-deps +$(foreach m,$(ALL_MODULES), \ + $(eval r := $(ALL_MODULES.$(m).REQUIRED)) \ + $(if $(r), \ + $(eval r := $(call module-installed-files,$(r))) \ + $(eval h_m := $(filter $(HOST_OUT)/%, $(ALL_MODULES.$(m).INSTALLED))) \ + $(eval hc_m := $(filter $(HOST_CROSS_OUT)/%, $(ALL_MODULES.$(m).INSTALLED))) \ + $(eval h_r := $(filter $(HOST_OUT)/%, $(r))) \ + $(eval hc_r := $(filter $(HOST_CROSS_OUT)/%, $(r))) \ + $(eval h_m := $(filter-out $(h_r), $(h_m))) \ + $(eval hc_m := $(filter-out $(hc_r), $(hc_m))) \ + $(if $(h_m), $(eval $(call add-required-deps, $(h_m),$(h_r)))) \ + $(if $(hc_m), $(eval $(call add-required-deps, $(hc_m),$(hc_r)))) \ + ) \ +) +endef +$(call add-all-host-to-host-required-modules-deps) + +# Sets up dependencies such that whenever a target module is installed, +# any other target modules listed in $(ALL_MODULES.$(m).REQUIRED) will also be installed +define add-all-target-to-target-required-modules-deps +$(foreach m,$(ALL_MODULES), \ + $(eval r := $(ALL_MODULES.$(m).REQUIRED)) \ + $(if $(r), \ + $(eval r := $(call module-installed-files,$(r))) \ + $(eval t_m := $(filter $(TARGET_OUT_ROOT)/%, $(ALL_MODULES.$(m).INSTALLED))) \ + $(eval t_r := $(filter $(TARGET_OUT_ROOT)/%, $(r))) \ + $(eval t_m := $(filter-out $(t_r), $(t_m))) \ + $(if $(t_m), $(eval $(call add-required-deps, $(t_m),$(t_r)))) \ + ) \ +) +endef +$(call add-all-target-to-target-required-modules-deps) + +# Sets up dependencies such that whenever a host module is installed, +# any target modules listed in $(ALL_MODULES.$(m).TARGET_REQUIRED) will also be installed +define add-all-host-to-target-required-modules-deps +$(foreach m,$(ALL_MODULES), \ + $(eval req_mods := $(ALL_MODULES.$(m).TARGET_REQUIRED))\ + $(if $(req_mods), \ + $(eval req_files := )\ + $(foreach req_mod,$(req_mods), \ + $(eval req_file := $(filter $(TARGET_OUT_ROOT)/%, $(call module-installed-files,$(req_mod)))) \ + $(if $(strip $(req_file)),\ + ,\ + $(error $(m).LOCAL_TARGET_REQUIRED_MODULES : illegal value $(req_mod) : not a device module. If you want to specify host modules to be required to be installed along with your host module, add those module names to LOCAL_REQUIRED_MODULES instead)\ + )\ + $(eval req_files := $(req_files)$(space)$(req_file))\ + )\ + $(eval req_files := $(strip $(req_files)))\ + $(eval mod_files := $(filter $(HOST_OUT)/%, $(call module-installed-files,$(m)))) \ + $(eval mod_files := $(filter-out $(req_files),$(mod_files)))\ + $(if $(mod_files),\ + $(eval $(call add-required-deps, $(mod_files),$(req_files))) \ + )\ + )\ +) +endef +$(call add-all-host-to-target-required-modules-deps) + +# Sets up dependencies such that whenever a target module is installed, +# any host modules listed in $(ALL_MODULES.$(m).HOST_REQUIRED) will also be installed +define add-all-target-to-host-required-modules-deps +$(foreach m,$(ALL_MODULES), \ + $(eval req_mods := $(ALL_MODULES.$(m).HOST_REQUIRED))\ + $(if $(req_mods), \ + $(eval req_files := )\ + $(foreach req_mod,$(req_mods), \ + $(eval req_file := $(filter $(HOST_OUT)/%, $(call module-installed-files,$(req_mod)))) \ + $(if $(strip $(req_file)),\ + ,\ + $(error $(m).LOCAL_HOST_REQUIRED_MODULES : illegal value $(req_mod) : not a host module. If you want to specify target modules to be required to be installed along with your target module, add those module names to LOCAL_REQUIRED_MODULES instead)\ + )\ + $(eval req_files := $(req_files)$(space)$(req_file))\ + )\ + $(eval req_files := $(strip $(req_files)))\ + $(eval mod_files := $(filter $(TARGET_OUT_ROOT)/%, $(call module-installed-files,$(m))))\ + $(eval mod_files := $(filter-out $(req_files),$(mod_files)))\ + $(if $(mod_files),\ + $(eval $(call add-required-deps, $(mod_files),$(req_files))) \ + )\ + )\ +) +endef +$(call add-all-target-to-host-required-modules-deps) + +t_m := +h_m := +hc_m := +t_r := +h_r := +hc_r := + +# Establish the dependencies on the shared libraries. +# It also adds the shared library module names to ALL_MODULES.$(m).REQUIRED, +# so they can be expanded to product_MODULES later. +# $(1): TARGET_ or HOST_ or HOST_CROSS_. +# $(2): non-empty for 2nd arch. +# $(3): non-empty for host cross compile. +define resolve-shared-libs-depes +$(foreach m,$($(if $(2),$($(1)2ND_ARCH_VAR_PREFIX))$(1)DEPENDENCIES_ON_SHARED_LIBRARIES),\ + $(eval p := $(subst :,$(space),$(m)))\ + $(eval mod := $(firstword $(p)))\ + $(eval deps := $(subst $(comma),$(space),$(lastword $(p))))\ + $(eval root := $(1)OUT$(if $(call streq,$(1),TARGET_),_ROOT))\ + $(if $(2),$(eval deps := $(addsuffix $($(1)2ND_ARCH_MODULE_SUFFIX),$(deps))))\ + $(if $(3),$(eval deps := $(addprefix host_cross_,$(deps))))\ + $(eval r := $(filter $($(root))/%,$(call module-installed-files,\ + $(deps))))\ + $(if $(filter $(1),HOST_),\ + $(eval $(call add-required-host-so-deps,$(word 2,$(p)),$(r))),\ + $(eval $(call add-required-deps,$(word 2,$(p)),$(r))))\ + $(eval ALL_MODULES.$(mod).REQUIRED += $(deps))) +endef + +$(call resolve-shared-libs-depes,TARGET_) +ifdef TARGET_2ND_ARCH +$(call resolve-shared-libs-depes,TARGET_,true) +endif +$(call resolve-shared-libs-depes,HOST_) +ifdef HOST_2ND_ARCH +$(call resolve-shared-libs-depes,HOST_,true) +endif +ifdef HOST_CROSS_OS +$(call resolve-shared-libs-depes,HOST_CROSS_,,true) +endif + +m := +r := +p := +deps := +add-required-deps := + +################################################################################ +# Link type checking +# +# ALL_LINK_TYPES contains a list of all link type prefixes (generally one per +# module, but APKs can "link" to both java and native code). The link type +# prefix consists of all the information needed by intermediates-dir-for: +# +# LINK_TYPE:TARGET:_:2ND:STATIC_LIBRARIES:libfoo +# +# 1: LINK_TYPE literal +# 2: prefix +# - TARGET +# - HOST +# - HOST_CROSS +# - AUX- +# 3: Whether to use the common intermediates directory or not +# - _ +# - COMMON +# 4: Whether it's the second arch or not +# - _ +# - 2ND_ +# 5: Module Class +# - STATIC_LIBRARIES +# - SHARED_LIBRARIES +# - ... +# 6: Module Name +# +# Then fields under that are separated by a period and the field name: +# - TYPE: the link types for this module +# - MAKEFILE: Where this module was defined +# - BUILT: The built module location +# - DEPS: the link type prefixes for the module's dependencies +# - ALLOWED: the link types to allow in this module's dependencies +# - WARN: the link types to warn about in this module's dependencies +# +# All of the dependency link types not listed in ALLOWED or WARN will become +# errors. +################################################################################ + +link_type_error := + +define link-type-prefix-base +$(word 2,$(subst :,$(space),$(1))) +endef +define link-type-prefix +$(if $(filter AUX-%,$(link-type-prefix-base)),$(patsubst AUX-%,AUX,$(link-type-prefix-base)),$(link-type-prefix-base)) +endef +define link-type-aux-variant +$(if $(filter AUX-%,$(link-type-prefix-base)),$(patsubst AUX-%,%,$(link-type-prefix-base))) +endef +define link-type-common +$(patsubst _,,$(word 3,$(subst :,$(space),$(1)))) +endef +define link-type-2ndarchprefix +$(patsubst _,,$(word 4,$(subst :,$(space),$(1)))) +endef +define link-type-class +$(word 5,$(subst :,$(space),$(1))) +endef +define link-type-name +$(word 6,$(subst :,$(space),$(1))) +endef +define link-type-os +$(strip $(eval _p := $(link-type-prefix))\ + $(if $(filter HOST HOST_CROSS,$(_p)),\ + $($(_p)_OS),\ + $(if $(filter AUX,$(_p)),AUX,android))) +endef +define link-type-arch +$($(link-type-prefix)_$(link-type-2ndarchprefix)ARCH) +endef +define link-type-name-variant +$(link-type-name) ($(link-type-class) $(link-type-os)-$(link-type-arch)) +endef + +# $(1): the prefix of the module doing the linking +# $(2): the prefix of the linked module +define link-type-warning +$(shell $(call echo-warning,$($(1).MAKEFILE),"$(call link-type-name,$(1)) ($($(1).TYPE)) should not link against $(call link-type-name,$(2)) ($(3))")) +endef + +# $(1): the prefix of the module doing the linking +# $(2): the prefix of the linked module +define link-type-error +$(shell $(call echo-error,$($(1).MAKEFILE),"$(call link-type-name,$(1)) ($($(1).TYPE)) can not link against $(call link-type-name,$(2)) ($(3))"))\ +$(eval link_type_error := true) +endef + +link-type-missing := +ifneq ($(ALLOW_MISSING_DEPENDENCIES),true) + # Print an error message if the linked-to module is missing + # $(1): the prefix of the module doing the linking + # $(2): the prefix of the missing module + define link-type-missing + $(shell $(call echo-error,$($(1).MAKEFILE),"$(call link-type-name-variant,$(1)) missing $(call link-type-name-variant,$(2))"))\ + $(eval available_variants := $(filter %:$(call link-type-name,$(2)),$(ALL_LINK_TYPES)))\ + $(if $(available_variants),\ + $(info Available variants:)\ + $(foreach v,$(available_variants),$(info $(space)$(space)$(call link-type-name-variant,$(v)))))\ + $(info You can set ALLOW_MISSING_DEPENDENCIES=true in your environment if this is intentional, but that may defer real problems until later in the build.)\ + $(eval link_type_error := true) + endef +else + define link-type-missing + $(eval $$(1).MISSING := true) + endef +endif + +# Verify that $(1) can link against $(2) +# Both $(1) and $(2) are the link type prefix defined above +define verify-link-type +$(foreach t,$($(2).TYPE),\ + $(if $(filter-out $($(1).ALLOWED),$(t)),\ + $(if $(filter $(t),$($(1).WARN)),\ + $(call link-type-warning,$(1),$(2),$(t)),\ + $(call link-type-error,$(1),$(2),$(t))))) +endef + +# TODO: Verify all branches/configs have reasonable warnings/errors, and remove +# this override +verify-link-type = $(eval $$(1).MISSING := true) + +$(foreach lt,$(ALL_LINK_TYPES),\ + $(foreach d,$($(lt).DEPS),\ + $(if $($(d).TYPE),\ + $(call verify-link-type,$(lt),$(d)),\ + $(call link-type-missing,$(lt),$(d))))) + +ifdef link_type_error + $(error exiting from previous errors) +endif + +# The intermediate filename for link type rules +# +# APPS are special -- they have up to three different rules: +# 1. The COMMON rule for Java libraries +# 2. The jni_link_type rule for embedded native code +# 3. The 2ND_jni_link_type for the second architecture native code +define link-type-file +$(eval _ltf_aux_variant:=$(link-type-aux-variant))\ +$(if $(_ltf_aux_variant),$(call aux-variant-load-env,$(_ltf_aux_variant)))\ +$(call intermediates-dir-for,$(link-type-class),$(link-type-name),$(filter AUX HOST HOST_CROSS,$(link-type-prefix)),$(link-type-common),$(link-type-2ndarchprefix),$(filter HOST_CROSS,$(link-type-prefix)))/$(if $(filter APPS,$(link-type-class)),$(if $(link-type-common),,$(link-type-2ndarchprefix)jni_))link_type\ +$(if $(_ltf_aux_variant),$(call aux-variant-load-env,none))\ +$(eval _ltf_aux_variant:=) +endef + +# Write out the file-based link_type rules for the ALLOW_MISSING_DEPENDENCIES +# case. We always need to write the file for mm to work, but only need to +# check it if we weren't able to check it when reading the Android.mk files. +define link-type-file-rule +my_link_type_deps := $(foreach l,$($(1).DEPS),$(call link-type-file,$(l))) +my_link_type_file := $(call link-type-file,$(1)) +$($(1).BUILT): | $$(my_link_type_file) +$$(my_link_type_file): PRIVATE_DEPS := $$(my_link_type_deps) +ifeq ($($(1).MISSING),true) +$$(my_link_type_file): $(CHECK_LINK_TYPE) +endif +$$(my_link_type_file): $$(my_link_type_deps) + @echo Check module type: $$@ + $$(hide) mkdir -p $$(dir $$@) && rm -f $$@ +ifeq ($($(1).MISSING),true) + $$(hide) $(CHECK_LINK_TYPE) --makefile $($(1).MAKEFILE) --module $(link-type-name) \ + --type "$($(1).TYPE)" $(addprefix --allowed ,$($(1).ALLOWED)) \ + $(addprefix --warn ,$($(1).WARN)) $$(PRIVATE_DEPS) +endif + $$(hide) echo "$($(1).TYPE)" >$$@ +endef + +$(foreach lt,$(ALL_LINK_TYPES),\ + $(eval $(call link-type-file-rule,$(lt)))) + +# ------------------------------------------------------------------- +# Figure out our module sets. +# +# Of the modules defined by the component makefiles, +# determine what we actually want to build. + +########################################################### +## Expand a module name list with REQUIRED modules +########################################################### +# $(1): The variable name that holds the initial module name list. +# the variable will be modified to hold the expanded results. +# $(2): The initial module name list. +# Returns empty string (maybe with some whitespaces). +define expand-required-modules +$(eval _erm_new_modules := $(sort $(filter-out $($(1)),\ + $(foreach m,$(2),$(ALL_MODULES.$(m).REQUIRED)))))\ +$(if $(_erm_new_modules),$(eval $(1) += $(_erm_new_modules))\ + $(call expand-required-modules,$(1),$(_erm_new_modules))) +endef + +ifdef FULL_BUILD + # The base list of modules to build for this product is specified + # by the appropriate product definition file, which was included + # by product_config.mk. + product_MODULES := $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES) +ifdef BOARD_VNDK_VERSION + product_MODULES += vndk_package +endif + # Filter out the overridden packages before doing expansion + product_MODULES := $(filter-out $(foreach p, $(product_MODULES), \ + $(PACKAGES.$(p).OVERRIDES)), $(product_MODULES)) + # Filter out executables as well + product_MODULES := $(filter-out $(foreach m, $(product_MODULES), \ + $(EXECUTABLES.$(m).OVERRIDES)), $(product_MODULES)) + + # remove packages + product_sub_MODULES := $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES_DEL) + product_MODULES := $(filter-out $(product_sub_MODULES), $(product_MODULES)) + # Resolve the :32 :64 module name + modules_32 := $(patsubst %:32,%,$(filter %:32, $(product_MODULES))) + modules_64 := $(patsubst %:64,%,$(filter %:64, $(product_MODULES))) + modules_rest := $(filter-out %:32 %:64,$(product_MODULES)) + # Note for 32-bit product, $(modules_32) and $(modules_64) will be + # added as their original module names. + product_MODULES := $(call get-32-bit-modules-if-we-can, $(modules_32)) + product_MODULES += $(modules_64) + # For the rest we add both + product_MODULES += $(call get-32-bit-modules, $(modules_rest)) + product_MODULES += $(modules_rest) + + $(call expand-required-modules,product_MODULES,$(product_MODULES)) + + product_FILES := $(call module-installed-files, $(product_MODULES)) + ifeq (0,1) + $(info product_FILES for $(TARGET_DEVICE) ($(INTERNAL_PRODUCT)):) + $(foreach p,$(product_FILES),$(info : $(p))) + $(error done) + endif +else + # We're not doing a full build, and are probably only including + # a subset of the module makefiles. Don't try to build any modules + # requested by the product, because we probably won't have rules + # to build them. + product_FILES := +endif + +eng_MODULES := $(sort \ + $(call get-tagged-modules,eng) \ + $(call module-installed-files, $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES_ENG)) \ + ) +debug_MODULES := $(sort \ + $(call get-tagged-modules,debug) \ + $(call module-installed-files, $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES_DEBUG)) \ + ) +tests_MODULES := $(sort \ + $(call get-tagged-modules,tests) \ + $(call module-installed-files, $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES_TESTS)) \ + ) + +# TODO: Remove the 3 places in the tree that use ALL_DEFAULT_INSTALLED_MODULES +# and get rid of it from this list. +modules_to_install := $(sort \ + $(ALL_DEFAULT_INSTALLED_MODULES) \ + $(product_FILES) \ + $(foreach tag,$(tags_to_install),$($(tag)_MODULES)) \ + $(CUSTOM_MODULES) \ + ) + +# Some packages may override others using LOCAL_OVERRIDES_PACKAGES. +# Filter out (do not install) any overridden packages. +overridden_packages := $(call get-package-overrides,$(modules_to_install)) +ifdef overridden_packages +# old_modules_to_install := $(modules_to_install) + modules_to_install := \ + $(filter-out $(foreach p,$(overridden_packages),$(p) %/$(p).apk %/$(p).odex %/$(p).vdex), \ + $(modules_to_install)) +endif +#$(error filtered out +# $(filter-out $(modules_to_install),$(old_modules_to_install))) + +# Don't include any GNU General Public License shared objects or static +# libraries in SDK images. GPL executables (not static/dynamic libraries) +# are okay if they don't link against any closed source libraries (directly +# or indirectly) + +# It's ok (and necessary) to build the host tools, but nothing that's +# going to be installed on the target (including static libraries). + +ifdef is_sdk_build + target_gnu_MODULES := \ + $(filter \ + $(TARGET_OUT_INTERMEDIATES)/% \ + $(TARGET_OUT)/% \ + $(TARGET_OUT_DATA)/%, \ + $(sort $(call get-tagged-modules,gnu))) + target_gnu_MODULES := $(filter-out $(TARGET_OUT_EXECUTABLES)/%,$(target_gnu_MODULES)) + target_gnu_MODULES := $(filter-out %/libopenjdkjvmti.so,$(target_gnu_MODULES)) + target_gnu_MODULES := $(filter-out %/libopenjdkjvmtid.so,$(target_gnu_MODULES)) + $(info Removing from sdk:)$(foreach d,$(target_gnu_MODULES),$(info : $(d))) + modules_to_install := \ + $(filter-out $(target_gnu_MODULES),$(modules_to_install)) + + # Ensure every module listed in PRODUCT_PACKAGES* gets something installed + # TODO: Should we do this for all builds and not just the sdk? + dangling_modules := + $(foreach m, $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES), \ + $(if $(strip $(ALL_MODULES.$(m).INSTALLED) $(ALL_MODULES.$(m)$(TARGET_2ND_ARCH_MODULE_SUFFIX).INSTALLED)),,\ + $(eval dangling_modules += $(m)))) + ifneq ($(dangling_modules),) + $(warning: Modules '$(dangling_modules)' in PRODUCT_PACKAGES have nothing to install!) + endif + $(foreach m, $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES_DEBUG), \ + $(if $(strip $(ALL_MODULES.$(m).INSTALLED)),,\ + $(warning $(ALL_MODULES.$(m).MAKEFILE): Module '$(m)' in PRODUCT_PACKAGES_DEBUG has nothing to install!))) + $(foreach m, $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES_ENG), \ + $(if $(strip $(ALL_MODULES.$(m).INSTALLED)),,\ + $(warning $(ALL_MODULES.$(m).MAKEFILE): Module '$(m)' in PRODUCT_PACKAGES_ENG has nothing to install!))) + $(foreach m, $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGES_TESTS), \ + $(if $(strip $(ALL_MODULES.$(m).INSTALLED)),,\ + $(warning $(ALL_MODULES.$(m).MAKEFILE): Module '$(m)' in PRODUCT_PACKAGES_TESTS has nothing to install!))) +endif + +# build/make/core/Makefile contains extra stuff that we don't want to pollute this +# top-level makefile with. It expects that ALL_DEFAULT_INSTALLED_MODULES +# contains everything that's built during the current make, but it also further +# extends ALL_DEFAULT_INSTALLED_MODULES. +ALL_DEFAULT_INSTALLED_MODULES := $(modules_to_install) +include $(BUILD_SYSTEM)/Makefile +modules_to_install := $(sort $(ALL_DEFAULT_INSTALLED_MODULES)) +ALL_DEFAULT_INSTALLED_MODULES := + + +# These are additional goals that we build, in order to make sure that there +# is as little code as possible in the tree that doesn't build. +modules_to_check := $(foreach m,$(ALL_MODULES),$(ALL_MODULES.$(m).CHECKED)) + +# If you would like to build all goals, and not skip any intermediate +# steps, you can pass the "all" modifier goal on the commandline. +ifneq ($(filter all,$(MAKECMDGOALS)),) +modules_to_check += $(foreach m,$(ALL_MODULES),$(ALL_MODULES.$(m).BUILT)) +endif + +# for easier debugging +modules_to_check := $(sort $(modules_to_check)) +#$(error modules_to_check $(modules_to_check)) + +# ------------------------------------------------------------------- +# This is used to to get the ordering right, you can also use these, +# but they're considered undocumented, so don't complain if their +# behavior changes. +# An internal target that depends on all copied headers +# (see copy_headers.make). Other targets that need the +# headers to be copied first can depend on this target. +.PHONY: all_copied_headers +all_copied_headers: ; + +$(ALL_C_CPP_ETC_OBJECTS): | all_copied_headers + +# All the droid stuff, in directories +.PHONY: files +files: $(modules_to_install) \ + $(INSTALLED_ANDROID_INFO_TXT_TARGET) + +# ------------------------------------------------------------------- + +.PHONY: checkbuild +checkbuild: $(modules_to_check) droid_targets + +ifeq (true,$(ANDROID_BUILD_EVERYTHING_BY_DEFAULT)) +droid: checkbuild +endif + +.PHONY: ramdisk +ramdisk: $(INSTALLED_RAMDISK_TARGET) + +.PHONY: systemtarball +systemtarball: $(INSTALLED_SYSTEMTARBALL_TARGET) + +.PHONY: boottarball +boottarball: $(INSTALLED_BOOTTARBALL_TARGET) + +.PHONY: userdataimage +userdataimage: $(INSTALLED_USERDATAIMAGE_TARGET) + +ifneq (,$(filter userdataimage, $(MAKECMDGOALS))) +$(call dist-for-goals, userdataimage, $(BUILT_USERDATAIMAGE_TARGET)) +endif + +.PHONY: userdatatarball +userdatatarball: $(INSTALLED_USERDATATARBALL_TARGET) + +.PHONY: cacheimage +cacheimage: $(INSTALLED_CACHEIMAGE_TARGET) + +.PHONY: bptimage +bptimage: $(INSTALLED_BPTIMAGE_TARGET) + +.PHONY: vendorimage +vendorimage: $(INSTALLED_VENDORIMAGE_TARGET) + +.PHONY: productimage +productimage: $(INSTALLED_PRODUCTIMAGE_TARGET) + +.PHONY: systemotherimage +systemotherimage: $(INSTALLED_SYSTEMOTHERIMAGE_TARGET) + +.PHONY: bootimage +bootimage: $(INSTALLED_BOOTIMAGE_TARGET) + +.PHONY: vbmetaimage +vbmetaimage: $(INSTALLED_VBMETAIMAGE_TARGET) + +.PHONY: auxiliary +auxiliary: $(INSTALLED_AUX_TARGETS) + +# Build files and then package it into the rom formats +.PHONY: droidcore +droidcore: files \ + systemimage \ + $(INSTALLED_BOOTIMAGE_TARGET) \ + $(INSTALLED_RECOVERYIMAGE_TARGET) \ + $(INSTALLED_VBMETAIMAGE_TARGET) \ + $(INSTALLED_USERDATAIMAGE_TARGET) \ + $(INSTALLED_CACHEIMAGE_TARGET) \ + $(INSTALLED_BPTIMAGE_TARGET) \ + $(INSTALLED_VENDORIMAGE_TARGET) \ + $(INSTALLED_PRODUCTIMAGE_TARGET) \ + $(INSTALLED_SYSTEMOTHERIMAGE_TARGET) \ + $(INSTALLED_FILES_FILE) \ + $(INSTALLED_FILES_FILE_VENDOR) \ + $(INSTALLED_FILES_FILE_PRODUCT) \ + $(INSTALLED_FILES_FILE_SYSTEMOTHER) \ + soong_docs + +# dist_files only for putting your library into the dist directory with a full build. +.PHONY: dist_files + +ifneq ($(TARGET_BUILD_APPS),) + # If this build is just for apps, only build apps and not the full system by default. + + unbundled_build_modules := + ifneq ($(filter all,$(TARGET_BUILD_APPS)),) + # If they used the magic goal "all" then build all apps in the source tree. + unbundled_build_modules := $(foreach m,$(sort $(ALL_MODULES)),$(if $(filter APPS,$(ALL_MODULES.$(m).CLASS)),$(m))) + else + unbundled_build_modules := $(TARGET_BUILD_APPS) + endif + + # Dist the installed files if they exist. + apps_only_installed_files := $(foreach m,$(unbundled_build_modules),$(ALL_MODULES.$(m).INSTALLED)) + $(call dist-for-goals,apps_only, $(apps_only_installed_files)) + # For uninstallable modules such as static Java library, we have to dist the built file, + # as . + apps_only_dist_built_files := $(foreach m,$(unbundled_build_modules),$(if $(ALL_MODULES.$(m).INSTALLED),,\ + $(if $(ALL_MODULES.$(m).BUILT),$(ALL_MODULES.$(m).BUILT):$(m)$(suffix $(ALL_MODULES.$(m).BUILT)))\ + $(if $(ALL_MODULES.$(m).AAR),$(ALL_MODULES.$(m).AAR):$(m).aar)\ + )) + $(call dist-for-goals,apps_only, $(apps_only_dist_built_files)) + + ifeq ($(EMMA_INSTRUMENT),true) + $(JACOCO_REPORT_CLASSES_ALL) : $(apps_only_installed_files) + $(call dist-for-goals,apps_only, $(JACOCO_REPORT_CLASSES_ALL)) + endif + + $(PROGUARD_DICT_ZIP) : $(apps_only_installed_files) + $(call dist-for-goals,apps_only, $(PROGUARD_DICT_ZIP)) + + $(SYMBOLS_ZIP) : $(apps_only_installed_files) + $(call dist-for-goals,apps_only, $(SYMBOLS_ZIP)) + + $(COVERAGE_ZIP) : $(apps_only_installed_files) + $(call dist-for-goals,apps_only, $(COVERAGE_ZIP)) + +.PHONY: apps_only +apps_only: $(unbundled_build_modules) + +droid_targets: apps_only + +# Combine the NOTICE files for a apps_only build +$(eval $(call combine-notice-files, html, \ + $(target_notice_file_txt), \ + $(target_notice_file_html_or_xml), \ + "Notices for files for apps:", \ + $(TARGET_OUT_NOTICE_FILES), \ + $(apps_only_installed_files))) + + +else # TARGET_BUILD_APPS + $(call dist-for-goals, droidcore, \ + $(INTERNAL_UPDATE_PACKAGE_TARGET) \ + $(INTERNAL_OTA_PACKAGE_TARGET) \ + $(BUILT_OTATOOLS_PACKAGE) \ + $(SYMBOLS_ZIP) \ + $(COVERAGE_ZIP) \ + $(INSTALLED_FILES_FILE) \ + $(INSTALLED_FILES_FILE_VENDOR) \ + $(INSTALLED_FILES_FILE_PRODUCT) \ + $(INSTALLED_FILES_FILE_SYSTEMOTHER) \ + $(INSTALLED_BUILD_PROP_TARGET) \ + $(BUILT_TARGET_FILES_PACKAGE) \ + $(INSTALLED_ANDROID_INFO_TXT_TARGET) \ + $(INSTALLED_RAMDISK_TARGET) \ + ) + + # Put a copy of the radio/bootloader files in the dist dir. + $(foreach f,$(INSTALLED_RADIOIMAGE_TARGET), \ + $(call dist-for-goals, droidcore, $(f))) + + ifneq ($(ANDROID_BUILD_EMBEDDED),true) + ifneq ($(TARGET_BUILD_PDK),true) + $(call dist-for-goals, droidcore, \ + $(APPS_ZIP) \ + $(INTERNAL_EMULATOR_PACKAGE_TARGET) \ + $(PACKAGE_STATS_FILE) \ + ) + endif + endif + + ifeq ($(EMMA_INSTRUMENT),true) + $(JACOCO_REPORT_CLASSES_ALL) : $(INSTALLED_SYSTEMIMAGE) + $(call dist-for-goals, dist_files, $(JACOCO_REPORT_CLASSES_ALL)) + endif + +# Building a full system-- the default is to build droidcore +droid_targets: droidcore dist_files + +endif # TARGET_BUILD_APPS + +.PHONY: docs +docs: $(ALL_DOCS) + +.PHONY: sdk +ALL_SDK_TARGETS := $(INTERNAL_SDK_TARGET) +sdk: $(ALL_SDK_TARGETS) +$(call dist-for-goals,sdk win_sdk, \ + $(ALL_SDK_TARGETS) \ + $(SYMBOLS_ZIP) \ + $(COVERAGE_ZIP) \ + $(INSTALLED_BUILD_PROP_TARGET) \ +) + +# umbrella targets to assit engineers in verifying builds +.PHONY: java native target host java-host java-target native-host native-target \ + java-host-tests java-target-tests native-host-tests native-target-tests \ + java-tests native-tests host-tests target-tests tests java-dex +# some synonyms +.PHONY: host-java target-java host-native target-native \ + target-java-tests target-native-tests +host-java : java-host +target-java : java-target +host-native : native-host +target-native : native-target +target-java-tests : java-target-tests +target-native-tests : native-target-tests +tests : host-tests target-tests + +# Phony target to run all java compilations that use javac +.PHONY: javac-check + +ifneq (,$(filter samplecode, $(MAKECMDGOALS))) +.PHONY: samplecode +sample_MODULES := $(sort $(call get-tagged-modules,samples)) +sample_APKS_DEST_PATH := $(TARGET_COMMON_OUT_ROOT)/samples +sample_APKS_COLLECTION := \ + $(foreach module,$(sample_MODULES),$(sample_APKS_DEST_PATH)/$(notdir $(module))) +$(foreach module,$(sample_MODULES),$(eval $(call \ + copy-one-file,$(module),$(sample_APKS_DEST_PATH)/$(notdir $(module))))) +sample_ADDITIONAL_INSTALLED := \ + $(filter-out $(modules_to_install) $(modules_to_check),$(sample_MODULES)) +samplecode: $(sample_APKS_COLLECTION) + @echo "Collect sample code apks: $^" + # remove apks that are not intended to be installed. + rm -f $(sample_ADDITIONAL_INSTALLED) +endif # samplecode in $(MAKECMDGOALS) + +.PHONY: findbugs +findbugs: $(INTERNAL_FINDBUGS_HTML_TARGET) $(INTERNAL_FINDBUGS_XML_TARGET) + +.PHONY: findlsdumps +findlsdumps: $(FIND_LSDUMPS_FILE) + +#xxx scrape this from ALL_MODULE_NAME_TAGS +.PHONY: modules +modules: + @echo "Available sub-modules:" + @echo "$(call module-names-for-tag-list,$(ALL_MODULE_TAGS))" | \ + tr -s ' ' '\n' | sort -u | $(COLUMN) + +.PHONY: nothing +nothing: + @echo Successfully read the makefiles. + +.PHONY: tidy_only +tidy_only: + @echo Successfully make tidy_only. + +ndk: $(SOONG_OUT_DIR)/ndk.timestamp +.PHONY: ndk + +endif # KATI diff --git a/aosp/build/make/core/product.mk b/aosp/build/make/core/product.mk new file mode 100644 index 000000000..d7c089664 --- /dev/null +++ b/aosp/build/make/core/product.mk @@ -0,0 +1,359 @@ +# +# Copyright (C) 2007 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# +# Functions for including AndroidProducts.mk files +# PRODUCT_MAKEFILES is set up in AndroidProducts.mks. +# Format of PRODUCT_MAKEFILES: +# : +# If the is the same as the base file name (without dir +# and the .mk suffix) of the product makefile, ":" can be +# omitted. + +# Search for AndroidProducts.mks in the given dir. +# $(1): the path to the dir +define _search-android-products-files-in-dir +$(sort $(shell test -d $(1) && find -L $(1) \ + -maxdepth 6 \ + -name .git -prune \ + -o -name AndroidProducts.mk -print)) +endef + +# +# Returns the list of all AndroidProducts.mk files. +# $(call ) isn't necessary. +# +define _find-android-products-files +$(foreach d, device vendor product,$(call _search-android-products-files-in-dir,$(d))) \ + $(SRC_TARGET_DIR)/product/AndroidProducts.mk +endef + +# +# Returns the sorted concatenation of PRODUCT_MAKEFILES +# variables set in the given AndroidProducts.mk files. +# $(1): the list of AndroidProducts.mk files. +# +define get-product-makefiles +$(sort \ + $(foreach f,$(1), \ + $(eval PRODUCT_MAKEFILES :=) \ + $(eval LOCAL_DIR := $(patsubst %/,%,$(dir $(f)))) \ + $(eval include $(f)) \ + $(PRODUCT_MAKEFILES) \ + ) \ + $(eval PRODUCT_MAKEFILES :=) \ + $(eval LOCAL_DIR :=) \ + ) +endef + +# +# Returns the sorted concatenation of all PRODUCT_MAKEFILES +# variables set in all AndroidProducts.mk files. +# $(call ) isn't necessary. +# +define get-all-product-makefiles +$(call get-product-makefiles,$(_find-android-products-files)) +endef + +# +# Functions for including product makefiles +# + +_product_var_list := \ + PRODUCT_NAME \ + PRODUCT_MODEL \ + PRODUCT_LOCALES \ + PRODUCT_AAPT_CONFIG \ + PRODUCT_AAPT_PREF_CONFIG \ + PRODUCT_AAPT_PREBUILT_DPI \ + PRODUCT_PACKAGES \ + PRODUCT_PACKAGES_DEBUG \ + PRODUCT_PACKAGES_DEL \ + PRODUCT_PACKAGES_ENG \ + PRODUCT_PACKAGES_TESTS \ + PRODUCT_DEVICE \ + PRODUCT_MANUFACTURER \ + PRODUCT_BRAND \ + PRODUCT_PROPERTY_OVERRIDES \ + PRODUCT_DEFAULT_PROPERTY_OVERRIDES \ + PRODUCT_PRODUCT_PROPERTIES \ + PRODUCT_CHARACTERISTICS \ + PRODUCT_COPY_FILES \ + PRODUCT_OTA_PUBLIC_KEYS \ + PRODUCT_EXTRA_RECOVERY_KEYS \ + PRODUCT_PACKAGE_OVERLAYS \ + DEVICE_PACKAGE_OVERLAYS \ + PRODUCT_ENFORCE_RRO_EXCLUDED_OVERLAYS \ + PRODUCT_ENFORCE_RRO_TARGETS \ + PRODUCT_SDK_ATREE_FILES \ + PRODUCT_SDK_ADDON_NAME \ + PRODUCT_SDK_ADDON_COPY_FILES \ + PRODUCT_SDK_ADDON_COPY_MODULES \ + PRODUCT_SDK_ADDON_DOC_MODULES \ + PRODUCT_SDK_ADDON_SYS_IMG_SOURCE_PROP \ + PRODUCT_SOONG_NAMESPACES \ + PRODUCT_DEFAULT_WIFI_CHANNELS \ + PRODUCT_DEFAULT_DEV_CERTIFICATE \ + PRODUCT_RESTRICT_VENDOR_FILES \ + PRODUCT_VENDOR_KERNEL_HEADERS \ + PRODUCT_BOOT_JARS \ + PRODUCT_SUPPORTS_BOOT_SIGNER \ + PRODUCT_SUPPORTS_VBOOT \ + PRODUCT_SUPPORTS_VERITY \ + PRODUCT_SUPPORTS_VERITY_FEC \ + PRODUCT_OEM_PROPERTIES \ + PRODUCT_SYSTEM_DEFAULT_PROPERTIES \ + PRODUCT_SYSTEM_PROPERTY_BLACKLIST \ + PRODUCT_VENDOR_PROPERTY_BLACKLIST \ + PRODUCT_SYSTEM_SERVER_APPS \ + PRODUCT_SYSTEM_SERVER_JARS \ + PRODUCT_ALWAYS_PREOPT_EXTRACTED_APK \ + PRODUCT_DEXPREOPT_SPEED_APPS \ + PRODUCT_LOADED_BY_PRIVILEGED_MODULES \ + PRODUCT_VBOOT_SIGNING_KEY \ + PRODUCT_VBOOT_SIGNING_SUBKEY \ + PRODUCT_VERITY_SIGNING_KEY \ + PRODUCT_SYSTEM_VERITY_PARTITION \ + PRODUCT_VENDOR_VERITY_PARTITION \ + PRODUCT_PRODUCT_VERITY_PARTITION \ + PRODUCT_SYSTEM_SERVER_DEBUG_INFO \ + PRODUCT_OTHER_JAVA_DEBUG_INFO \ + PRODUCT_DEX_PREOPT_MODULE_CONFIGS \ + PRODUCT_DEX_PREOPT_DEFAULT_COMPILER_FILTER \ + PRODUCT_DEX_PREOPT_DEFAULT_FLAGS \ + PRODUCT_DEX_PREOPT_BOOT_FLAGS \ + PRODUCT_DEX_PREOPT_PROFILE_DIR \ + PRODUCT_DEX_PREOPT_BOOT_IMAGE_PROFILE_LOCATION \ + PRODUCT_DEX_PREOPT_GENERATE_DM_FILES \ + PRODUCT_USE_PROFILE_FOR_BOOT_IMAGE \ + PRODUCT_SYSTEM_SERVER_COMPILER_FILTER \ + PRODUCT_SANITIZER_MODULE_CONFIGS \ + PRODUCT_SYSTEM_BASE_FS_PATH \ + PRODUCT_VENDOR_BASE_FS_PATH \ + PRODUCT_PRODUCT_BASE_FS_PATH \ + PRODUCT_SHIPPING_API_LEVEL \ + VENDOR_PRODUCT_RESTRICT_VENDOR_FILES \ + VENDOR_EXCEPTION_MODULES \ + VENDOR_EXCEPTION_PATHS \ + PRODUCT_ART_TARGET_INCLUDE_DEBUG_BUILD \ + PRODUCT_ART_USE_READ_BARRIER \ + PRODUCT_IOT \ + PRODUCT_SYSTEM_HEADROOM \ + PRODUCT_MINIMIZE_JAVA_DEBUG_INFO \ + PRODUCT_INTEGER_OVERFLOW_EXCLUDE_PATHS \ + PRODUCT_ADB_KEYS \ + PRODUCT_CFI_INCLUDE_PATHS \ + PRODUCT_CFI_EXCLUDE_PATHS \ + PRODUCT_COMPATIBLE_PROPERTY_OVERRIDE \ + PRODUCT_ACTIONABLE_COMPATIBLE_PROPERTY_DISABLE \ + +define dump-product +$(info ==== $(1) ====)\ +$(foreach v,$(_product_var_list),\ +$(info PRODUCTS.$(1).$(v) := $(PRODUCTS.$(1).$(v))))\ +$(info --------) +endef + +define dump-products +$(foreach p,$(PRODUCTS),$(call dump-product,$(p))) +endef + +# +# $(1): product to inherit +# +# Does three things: +# 1. Inherits all of the variables from $1. +# 2. Records the inheritance in the .INHERITS_FROM variable +# 3. Records that we've visited this node, in ALL_PRODUCTS +# +define inherit-product + $(if $(findstring ../,$(1)),\ + $(eval np := $(call normalize-paths,$(1))),\ + $(eval np := $(strip $(1))))\ + $(foreach v,$(_product_var_list), \ + $(eval $(v) := $($(v)) $(INHERIT_TAG)$(np))) \ + $(eval inherit_var := \ + PRODUCTS.$(strip $(word 1,$(_include_stack))).INHERITS_FROM) \ + $(eval $(inherit_var) := $(sort $($(inherit_var)) $(np))) \ + $(eval inherit_var:=) \ + $(eval ALL_PRODUCTS := $(sort $(ALL_PRODUCTS) $(word 1,$(_include_stack)))) +endef + + +# +# Do inherit-product only if $(1) exists +# +define inherit-product-if-exists + $(if $(wildcard $(1)),$(call inherit-product,$(1)),) +endef + +# +# $(1): product makefile list +# +#TODO: check to make sure that products have all the necessary vars defined +define import-products +$(call import-nodes,PRODUCTS,$(1),$(_product_var_list)) +endef + + +# +# Does various consistency checks on all of the known products. +# Takes no parameters, so $(call ) is not necessary. +# +define check-all-products +$(if ,, \ + $(eval _cap_names :=) \ + $(foreach p,$(PRODUCTS), \ + $(eval pn := $(strip $(PRODUCTS.$(p).PRODUCT_NAME))) \ + $(if $(pn),,$(error $(p): PRODUCT_NAME must be defined.)) \ + $(if $(filter $(pn),$(_cap_names)), \ + $(error $(p): PRODUCT_NAME must be unique; "$(pn)" already used by $(strip \ + $(foreach \ + pp,$(PRODUCTS), + $(if $(filter $(pn),$(PRODUCTS.$(pp).PRODUCT_NAME)), \ + $(pp) \ + ))) \ + ) \ + ) \ + $(eval _cap_names += $(pn)) \ + $(if $(call is-c-identifier,$(pn)),, \ + $(error $(p): PRODUCT_NAME must be a valid C identifier, not "$(pn)") \ + ) \ + $(eval pb := $(strip $(PRODUCTS.$(p).PRODUCT_BRAND))) \ + $(if $(pb),,$(error $(p): PRODUCT_BRAND must be defined.)) \ + $(foreach cf,$(strip $(PRODUCTS.$(p).PRODUCT_COPY_FILES)), \ + $(if $(filter 2 3,$(words $(subst :,$(space),$(cf)))),, \ + $(error $(p): malformed COPY_FILE "$(cf)") \ + ) \ + ) \ + ) \ +) +endef + + +# +# Returns the product makefile path for the product with the provided name +# +# $(1): short product name like "generic" +# +define _resolve-short-product-name + $(eval pn := $(strip $(1))) + $(eval p := \ + $(foreach p,$(PRODUCTS), \ + $(if $(filter $(pn),$(PRODUCTS.$(p).PRODUCT_NAME)), \ + $(p) \ + )) \ + ) + $(eval p := $(sort $(p))) + $(if $(filter 1,$(words $(p))), \ + $(p), \ + $(if $(filter 0,$(words $(p))), \ + $(error No matches for product "$(pn)"), \ + $(error Product "$(pn)" ambiguous: matches $(p)) \ + ) \ + ) +endef +define resolve-short-product-name +$(strip $(call _resolve-short-product-name,$(1))) +endef + + +_product_stash_var_list := $(_product_var_list) \ + PRODUCT_BOOTCLASSPATH \ + PRODUCT_SYSTEM_SERVER_CLASSPATH \ + TARGET_ARCH \ + TARGET_ARCH_VARIANT \ + TARGET_CPU_VARIANT \ + TARGET_BOARD_PLATFORM \ + TARGET_BOARD_PLATFORM_GPU \ + TARGET_BOARD_KERNEL_HEADERS \ + TARGET_DEVICE_KERNEL_HEADERS \ + TARGET_PRODUCT_KERNEL_HEADERS \ + TARGET_BOOTLOADER_BOARD_NAME \ + TARGET_NO_BOOTLOADER \ + TARGET_NO_KERNEL \ + TARGET_NO_RECOVERY \ + TARGET_NO_RADIOIMAGE \ + TARGET_HARDWARE_3D \ + TARGET_CPU_ABI \ + TARGET_CPU_ABI2 \ + + +_product_stash_var_list += \ + BOARD_WPA_SUPPLICANT_DRIVER \ + BOARD_WLAN_DEVICE \ + BOARD_USES_GENERIC_AUDIO \ + BOARD_KERNEL_CMDLINE \ + BOARD_KERNEL_BASE \ + BOARD_HAVE_BLUETOOTH \ + BOARD_VENDOR_USE_AKMD \ + BOARD_EGL_CFG \ + BOARD_BOOTIMAGE_PARTITION_SIZE \ + BOARD_RECOVERYIMAGE_PARTITION_SIZE \ + BOARD_SYSTEMIMAGE_PARTITION_SIZE \ + BOARD_SYSTEMIMAGE_FILE_SYSTEM_TYPE \ + BOARD_USERDATAIMAGE_FILE_SYSTEM_TYPE \ + BOARD_USERDATAIMAGE_PARTITION_SIZE \ + BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE \ + BOARD_CACHEIMAGE_PARTITION_SIZE \ + BOARD_FLASH_BLOCK_SIZE \ + BOARD_VENDORIMAGE_PARTITION_SIZE \ + BOARD_VENDORIMAGE_FILE_SYSTEM_TYPE \ + BOARD_PRODUCTIMAGE_PARTITION_SIZE \ + BOARD_PRODUCTIMAGE_FILE_SYSTEM_TYPE \ + BOARD_INSTALLER_CMDLINE \ + + +_product_stash_var_list += \ + DEFAULT_SYSTEM_DEV_CERTIFICATE \ + WITH_DEXPREOPT \ + WITH_DEXPREOPT_BOOT_IMG_AND_SYSTEM_SERVER_ONLY + +# +# Mark the variables in _product_stash_var_list as readonly +# +define readonly-product-vars +$(foreach v,$(_product_stash_var_list), \ + $(eval $(v) ?=) \ + $(eval .KATI_READONLY := $(v)) \ + ) +endef + +define add-to-product-copy-files-if-exists +$(if $(wildcard $(word 1,$(subst :, ,$(1)))),$(1)) +endef + +# whitespace placeholder when we record module's dex-preopt config. +_PDPMC_SP_PLACE_HOLDER := |@SP@| +# Set up dex-preopt config for a module. +# $(1) list of module names +# $(2) the modules' dex-preopt config +define add-product-dex-preopt-module-config +$(eval _c := $(subst $(space),$(_PDPMC_SP_PLACE_HOLDER),$(strip $(2))))\ +$(eval PRODUCT_DEX_PREOPT_MODULE_CONFIGS += \ + $(foreach m,$(1),$(m)=$(_c))) +endef + +# whitespace placeholder when we record module's sanitizer config. +_PSMC_SP_PLACE_HOLDER := |@SP@| +# Set up sanitizer config for a module. +# $(1) list of module names +# $(2) the modules' sanitizer config +define add-product-sanitizer-module-config +$(eval _c := $(subst $(space),$(_PSMC_SP_PLACE_HOLDER),$(strip $(2))))\ +$(eval PRODUCT_SANITIZER_MODULE_CONFIGS += \ + $(foreach m,$(1),$(m)=$(_c))) +endef diff --git a/aosp/build/make/core/product_config.mk b/aosp/build/make/core/product_config.mk new file mode 100644 index 000000000..e56ff2a4d --- /dev/null +++ b/aosp/build/make/core/product_config.mk @@ -0,0 +1,507 @@ +# +# Copyright (C) 2008 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# --------------------------------------------------------------- +# Generic functions +# TODO: Move these to definitions.make once we're able to include +# definitions.make before config.make. + +########################################################### +## Return non-empty if $(1) is a C identifier; i.e., if it +## matches /^[a-zA-Z_][a-zA-Z0-9_]*$/. We do this by first +## making sure that it isn't empty and doesn't start with +## a digit, then by removing each valid character. If the +## final result is empty, then it was a valid C identifier. +## +## $(1): word to check +########################################################### + +_ici_digits := 0 1 2 3 4 5 6 7 8 9 +_ici_alphaunderscore := \ + a b c d e f g h i j k l m n o p q r s t u v w x y z \ + A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ +define is-c-identifier +$(strip \ + $(if $(1), \ + $(if $(filter $(addsuffix %,$(_ici_digits)),$(1)), \ + , \ + $(eval w := $(1)) \ + $(foreach c,$(_ici_digits) $(_ici_alphaunderscore), \ + $(eval w := $(subst $(c),,$(w))) \ + ) \ + $(if $(w),,TRUE) \ + $(eval w :=) \ + ) \ + ) \ + ) +endef + +# TODO: push this into the combo files; unfortunately, we don't even +# know HOST_OS at this point. +trysed := $(shell echo a | sed -E -e 's/a/b/' 2>/dev/null) +ifeq ($(trysed),b) + SED_EXTENDED := sed -E +else + trysed := $(shell echo c | sed -r -e 's/c/d/' 2>/dev/null) + ifeq ($(trysed),d) + SED_EXTENDED := sed -r + else + $(error Unknown sed version) + endif +endif + +########################################################### +## List all of the files in a subdirectory in a format +## suitable for PRODUCT_COPY_FILES and +## PRODUCT_SDK_ADDON_COPY_FILES +## +## $(1): Glob to match file name +## $(2): Source directory +## $(3): Target base directory +########################################################### + +define find-copy-subdir-files +$(sort $(shell find $(2) -name "$(1)" -type f | $(SED_EXTENDED) "s:($(2)/?(.*)):\\1\\:$(3)/\\2:" | sed "s://:/:g")) +endef + +# --------------------------------------------------------------- + +# These are the valid values of TARGET_BUILD_VARIANT. Also, if anything else is passed +# as the variant in the PRODUCT-$TARGET_BUILD_PRODUCT-$TARGET_BUILD_VARIANT form, +# it will be treated as a goal, and the eng variant will be used. +INTERNAL_VALID_VARIANTS := user userdebug eng + +# --------------------------------------------------------------- +# Provide "PRODUCT--" targets, which lets you build +# a particular configuration without needing to set up the environment. +# +ifeq ($(CALLED_FROM_SETUP),true) +product_goals := $(strip $(filter PRODUCT-%,$(MAKECMDGOALS))) +ifdef product_goals + # Scrape the product and build names out of the goal, + # which should be of the form PRODUCT--. + # + ifneq ($(words $(product_goals)),1) + $(error Only one PRODUCT-* goal may be specified; saw "$(product_goals)") + endif + goal_name := $(product_goals) + product_goals := $(patsubst PRODUCT-%,%,$(product_goals)) + product_goals := $(subst -, ,$(product_goals)) + ifneq ($(words $(product_goals)),2) + $(error Bad PRODUCT-* goal "$(goal_name)") + endif + + # The product they want + TARGET_PRODUCT := $(word 1,$(product_goals)) + + # The variant they want + TARGET_BUILD_VARIANT := $(word 2,$(product_goals)) + + ifeq ($(TARGET_BUILD_VARIANT),tests) + $(error "tests" has been deprecated as a build variant. Use it as a build goal instead.) + endif + + # The build server wants to do make PRODUCT-dream-sdk + # which really means TARGET_PRODUCT=dream make sdk. + ifneq ($(filter-out $(INTERNAL_VALID_VARIANTS),$(TARGET_BUILD_VARIANT)),) + override MAKECMDGOALS := $(MAKECMDGOALS) $(TARGET_BUILD_VARIANT) + TARGET_BUILD_VARIANT := userdebug + default_goal_substitution := + else + default_goal_substitution := droid + endif + + # Replace the PRODUCT-* goal with the build goal that it refers to. + # Note that this will ensure that it appears in the same relative + # position, in case it matters. + override MAKECMDGOALS := $(patsubst $(goal_name),$(default_goal_substitution),$(MAKECMDGOALS)) +endif +endif # CALLED_FROM_SETUP +# else: Use the value set in the environment or buildspec.mk. + +# --------------------------------------------------------------- +# Provide "APP-" targets, which lets you build +# an unbundled app. +# +ifeq ($(CALLED_FROM_SETUP),true) +unbundled_goals := $(strip $(filter APP-%,$(MAKECMDGOALS))) +ifdef unbundled_goals + ifneq ($(words $(unbundled_goals)),1) + $(error Only one APP-* goal may be specified; saw "$(unbundled_goals)") + endif + TARGET_BUILD_APPS := $(strip $(subst -, ,$(patsubst APP-%,%,$(unbundled_goals)))) + ifneq ($(filter droid,$(MAKECMDGOALS)),) + override MAKECMDGOALS := $(patsubst $(unbundled_goals),,$(MAKECMDGOALS)) + else + override MAKECMDGOALS := $(patsubst $(unbundled_goals),droid,$(MAKECMDGOALS)) + endif +endif # unbundled_goals +endif + +# Now that we've parsed APP-* and PRODUCT-*, mark these as readonly +TARGET_BUILD_APPS ?= +.KATI_READONLY := \ + TARGET_PRODUCT \ + TARGET_BUILD_VARIANT \ + TARGET_BUILD_APPS + +# Default to building dalvikvm on hosts that support it... +ifeq ($(HOST_OS),linux) +# ... or if the if the option is already set +ifeq ($(WITH_HOST_DALVIK),) + WITH_HOST_DALVIK := true +endif +endif + +# --------------------------------------------------------------- +# Include the product definitions. +# We need to do this to translate TARGET_PRODUCT into its +# underlying TARGET_DEVICE before we start defining any rules. +# +include $(BUILD_SYSTEM)/node_fns.mk +include $(BUILD_SYSTEM)/product.mk +include $(BUILD_SYSTEM)/device.mk + +ifneq ($(strip $(TARGET_BUILD_APPS)),) +# An unbundled app build needs only the core product makefiles. +all_product_configs := $(call get-product-makefiles,\ + $(SRC_TARGET_DIR)/product/AndroidProducts.mk) +else +# Read in all of the product definitions specified by the AndroidProducts.mk +# files in the tree. +all_product_configs := $(get-all-product-makefiles) +endif + +all_named_products := + +# Find the product config makefile for the current product. +# all_product_configs consists items like: +# : +# or just in case the product name is the +# same as the base filename of the product config makefile. +current_product_makefile := +all_product_makefiles := +$(foreach f, $(all_product_configs),\ + $(eval _cpm_words := $(subst :,$(space),$(f)))\ + $(eval _cpm_word1 := $(word 1,$(_cpm_words)))\ + $(eval _cpm_word2 := $(word 2,$(_cpm_words)))\ + $(if $(_cpm_word2),\ + $(eval all_product_makefiles += $(_cpm_word2))\ + $(eval all_named_products += $(_cpm_word1))\ + $(if $(filter $(TARGET_PRODUCT),$(_cpm_word1)),\ + $(eval current_product_makefile += $(_cpm_word2)),),\ + $(eval all_product_makefiles += $(f))\ + $(eval all_named_products += $(basename $(notdir $(f))))\ + $(if $(filter $(TARGET_PRODUCT),$(basename $(notdir $(f)))),\ + $(eval current_product_makefile += $(f)),))) +_cpm_words := +_cpm_word1 := +_cpm_word2 := +current_product_makefile := $(strip $(current_product_makefile)) +all_product_makefiles := $(strip $(all_product_makefiles)) + +load_all_product_makefiles := +ifneq (,$(filter product-graph, $(MAKECMDGOALS))) +ifeq ($(ANDROID_PRODUCT_GRAPH),--all) +load_all_product_makefiles := true +endif +endif +ifneq (,$(filter dump-products,$(MAKECMDGOALS))) +ifeq ($(ANDROID_DUMP_PRODUCTS),all) +load_all_product_makefiles := true +endif +endif + +ifeq ($(load_all_product_makefiles),true) +# Import all product makefiles. +$(call import-products, $(all_product_makefiles)) +else +# Import just the current product. +ifndef current_product_makefile +$(error Can not locate config makefile for product "$(TARGET_PRODUCT)") +endif +ifneq (1,$(words $(current_product_makefile))) +$(error Product "$(TARGET_PRODUCT)" ambiguous: matches $(current_product_makefile)) +endif +$(call import-products, $(current_product_makefile)) +endif # Import all or just the current product makefile + +# Sanity check +$(check-all-products) + +ifneq ($(filter dump-products, $(MAKECMDGOALS)),) +$(dump-products) +$(error done) +endif + +# Convert a short name like "sooner" into the path to the product +# file defining that product. +# +INTERNAL_PRODUCT := $(call resolve-short-product-name, $(TARGET_PRODUCT)) +ifneq ($(current_product_makefile),$(INTERNAL_PRODUCT)) +$(error PRODUCT_NAME inconsistent in $(current_product_makefile) and $(INTERNAL_PRODUCT)) +endif +current_product_makefile := +all_product_makefiles := +all_product_configs := + + +############################################################################# + +# A list of module names of BOOTCLASSPATH (jar files) +PRODUCT_BOOT_JARS := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_BOOT_JARS)) +PRODUCT_SYSTEM_SERVER_JARS := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_SERVER_JARS)) +PRODUCT_SYSTEM_SERVER_APPS := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_SERVER_APPS)) +PRODUCT_DEXPREOPT_SPEED_APPS := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEXPREOPT_SPEED_APPS)) +PRODUCT_LOADED_BY_PRIVILEGED_MODULES := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_LOADED_BY_PRIVILEGED_MODULES)) + +# All of the apps that we force preopt, this overrides WITH_DEXPREOPT. +PRODUCT_ALWAYS_PREOPT_EXTRACTED_APK := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ALWAYS_PREOPT_EXTRACTED_APK)) + +# Find the device that this product maps to. +TARGET_DEVICE := $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEVICE) + +# Figure out which resoure configuration options to use for this +# product. +PRODUCT_LOCALES := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_LOCALES)) +# TODO: also keep track of things like "port", "land" in product files. + +# If CUSTOM_LOCALES contains any locales not already included +# in PRODUCT_LOCALES, add them to PRODUCT_LOCALES. +extra_locales := $(filter-out $(PRODUCT_LOCALES),$(CUSTOM_LOCALES)) +ifneq (,$(extra_locales)) + ifneq ($(CALLED_FROM_SETUP),true) + # Don't spam stdout, because envsetup.sh may be scraping values from it. + $(info Adding CUSTOM_LOCALES [$(extra_locales)] to PRODUCT_LOCALES [$(PRODUCT_LOCALES)]) + endif + PRODUCT_LOCALES += $(extra_locales) + extra_locales := +endif + +# Add PRODUCT_LOCALES to PRODUCT_AAPT_CONFIG +PRODUCT_AAPT_CONFIG := $(strip $(PRODUCT_LOCALES) $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_AAPT_CONFIG)) +PRODUCT_AAPT_PREF_CONFIG := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_AAPT_PREF_CONFIG)) +PRODUCT_AAPT_PREBUILT_DPI := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_AAPT_PREBUILT_DPI)) + +# Keep a copy of the space-separated config +PRODUCT_AAPT_CONFIG_SP := $(PRODUCT_AAPT_CONFIG) + +# Convert spaces to commas. +PRODUCT_AAPT_CONFIG := \ + $(subst $(space),$(comma),$(strip $(PRODUCT_AAPT_CONFIG))) + +PRODUCT_BRAND := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_BRAND)) + +PRODUCT_MODEL := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_MODEL)) +ifndef PRODUCT_MODEL + PRODUCT_MODEL := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_NAME)) +endif + +PRODUCT_MANUFACTURER := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_MANUFACTURER)) +ifndef PRODUCT_MANUFACTURER + PRODUCT_MANUFACTURER := huawei +endif + +ifeq ($(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_CHARACTERISTICS),) + TARGET_AAPT_CHARACTERISTICS := default +else + TARGET_AAPT_CHARACTERISTICS := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_CHARACTERISTICS)) +endif + +PRODUCT_DEFAULT_WIFI_CHANNELS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEFAULT_WIFI_CHANNELS)) + +PRODUCT_DEFAULT_DEV_CERTIFICATE := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEFAULT_DEV_CERTIFICATE)) +ifdef PRODUCT_DEFAULT_DEV_CERTIFICATE +ifneq (1,$(words $(PRODUCT_DEFAULT_DEV_CERTIFICATE))) + $(error PRODUCT_DEFAULT_DEV_CERTIFICATE='$(PRODUCT_DEFAULT_DEV_CERTIFICATE)', \ + only 1 certificate is allowed.) +endif +endif + +# A list of words like :[:]. +# The file at the source path should be copied to the destination path +# when building this product. is relative to +# $(PRODUCT_OUT), so it should look like, e.g., "system/etc/file.xml". +# The rules for these copy steps are defined in build/make/core/Makefile. +# The optional : is used to indicate the owner of a vendor file. +PRODUCT_COPY_FILES := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_COPY_FILES)) + +# A list of property assignments, like "key = value", with zero or more +# whitespace characters on either side of the '='. +PRODUCT_PROPERTY_OVERRIDES := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PROPERTY_OVERRIDES)) +.KATI_READONLY := PRODUCT_PROPERTY_OVERRIDES + +PRODUCT_SHIPPING_API_LEVEL := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SHIPPING_API_LEVEL)) + +# A list of property assignments, like "key = value", with zero or more +# whitespace characters on either side of the '='. +# used for adding properties to default.prop +PRODUCT_DEFAULT_PROPERTY_OVERRIDES := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEFAULT_PROPERTY_OVERRIDES)) +.KATI_READONLY := PRODUCT_DEFAULT_PROPERTY_OVERRIDES + +# A list of property assignments, like "key = value", with zero or more +# whitespace characters on either side of the '='. +# used for adding properties to default.prop of system partition +PRODUCT_SYSTEM_DEFAULT_PROPERTIES := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_DEFAULT_PROPERTIES)) +.KATI_READONLY := PRODUCT_SYSTEM_DEFAULT_PROPERTIES + +# A list of property assignments, like "key = value", with zero or more +# whitespace characters on either side of the '='. +# used for adding properties to build.prop of product partition +PRODUCT_PRODUCT_PROPERTIES := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PRODUCT_PROPERTIES)) +.KATI_READONLY := PRODUCT_PRODUCT_PROPERTIES + +# Should we use the default resources or add any product specific overlays +PRODUCT_PACKAGE_OVERLAYS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_PACKAGE_OVERLAYS)) +DEVICE_PACKAGE_OVERLAYS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).DEVICE_PACKAGE_OVERLAYS)) + +# The list of product-specific kernel header dirs +PRODUCT_VENDOR_KERNEL_HEADERS := \ + $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_VENDOR_KERNEL_HEADERS) + +# The OTA key(s) specified by the product config, if any. The names +# of these keys are stored in the target-files zip so that post-build +# signing tools can substitute them for the test key embedded by +# default. +PRODUCT_OTA_PUBLIC_KEYS := $(sort \ + $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_OTA_PUBLIC_KEYS)) + +PRODUCT_EXTRA_RECOVERY_KEYS := $(sort \ + $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_EXTRA_RECOVERY_KEYS)) + +PRODUCT_DEX_PREOPT_DEFAULT_COMPILER_FILTER := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_DEFAULT_COMPILER_FILTER)) +PRODUCT_DEX_PREOPT_DEFAULT_FLAGS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_DEFAULT_FLAGS)) +PRODUCT_DEX_PREOPT_GENERATE_DM_FILES := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_GENERATE_DM_FILES)) +PRODUCT_DEX_PREOPT_BOOT_FLAGS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_BOOT_FLAGS)) +PRODUCT_DEX_PREOPT_PROFILE_DIR := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_PROFILE_DIR)) + +# Boot image options. +PRODUCT_USE_PROFILE_FOR_BOOT_IMAGE := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_USE_PROFILE_FOR_BOOT_IMAGE)) +PRODUCT_DEX_PREOPT_BOOT_IMAGE_PROFILE_LOCATION := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_BOOT_IMAGE_PROFILE_LOCATION)) + +PRODUCT_SYSTEM_SERVER_COMPILER_FILTER := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_SERVER_COMPILER_FILTER)) +PRODUCT_SYSTEM_SERVER_DEBUG_INFO := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_SERVER_DEBUG_INFO)) +PRODUCT_OTHER_JAVA_DEBUG_INFO := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_OTHER_JAVA_DEBUG_INFO)) + +# Resolve and setup per-module dex-preopt configs. +PRODUCT_DEX_PREOPT_MODULE_CONFIGS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_DEX_PREOPT_MODULE_CONFIGS)) +# If a module has multiple setups, the first takes precedence. +_pdpmc_modules := +$(foreach c,$(PRODUCT_DEX_PREOPT_MODULE_CONFIGS),\ + $(eval m := $(firstword $(subst =,$(space),$(c))))\ + $(if $(filter $(_pdpmc_modules),$(m)),,\ + $(eval _pdpmc_modules += $(m))\ + $(eval cf := $(patsubst $(m)=%,%,$(c)))\ + $(eval cf := $(subst $(_PDPMC_SP_PLACE_HOLDER),$(space),$(cf)))\ + $(eval DEXPREOPT.$(TARGET_PRODUCT).$(m).CONFIG := $(cf)))) +_pdpmc_modules := + +# Resolve and setup per-module sanitizer configs. +PRODUCT_SANITIZER_MODULE_CONFIGS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SANITIZER_MODULE_CONFIGS)) +# If a module has multiple setups, the first takes precedence. +_psmc_modules := +$(foreach c,$(PRODUCT_SANITIZER_MODULE_CONFIGS),\ + $(eval m := $(firstword $(subst =,$(space),$(c))))\ + $(if $(filter $(_psmc_modules),$(m)),,\ + $(eval _psmc_modules += $(m))\ + $(eval cf := $(patsubst $(m)=%,%,$(c)))\ + $(eval cf := $(subst $(_PSMC_SP_PLACE_HOLDER),$(space),$(cf)))\ + $(eval SANITIZER.$(TARGET_PRODUCT).$(m).CONFIG := $(cf)))) +_psmc_modules := + +# Whether the product wants to ship libartd. For rules and meaning, see art/Android.mk. +PRODUCT_ART_TARGET_INCLUDE_DEBUG_BUILD := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ART_TARGET_INCLUDE_DEBUG_BUILD)) + +# Make this art variable visible to soong_config.mk. +PRODUCT_ART_USE_READ_BARRIER := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ART_USE_READ_BARRIER)) + +# Whether the product is an Android Things variant. +PRODUCT_IOT := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_IOT)) + +# Resource overlay list which must be excluded from enforcing RRO. +PRODUCT_ENFORCE_RRO_EXCLUDED_OVERLAYS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ENFORCE_RRO_EXCLUDED_OVERLAYS)) + +# Package list to apply enforcing RRO. +PRODUCT_ENFORCE_RRO_TARGETS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ENFORCE_RRO_TARGETS)) + +# Add reserved headroom to a system image. +PRODUCT_SYSTEM_HEADROOM := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SYSTEM_HEADROOM)) + +# Whether to save disk space by minimizing java debug info +PRODUCT_MINIMIZE_JAVA_DEBUG_INFO := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_MINIMIZE_JAVA_DEBUG_INFO)) + +# Whether any paths are excluded from sanitization when SANITIZE_TARGET=integer_overflow +PRODUCT_INTEGER_OVERFLOW_EXCLUDE_PATHS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_INTEGER_OVERFLOW_EXCLUDE_PATHS)) + +# ADB keys for debuggable builds +PRODUCT_ADB_KEYS := +ifneq ($(filter eng userdebug,$(TARGET_BUILD_VARIANT)),) + PRODUCT_ADB_KEYS := $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ADB_KEYS)) +endif +ifneq ($(filter-out 0 1,$(words $(PRODUCT_ADB_KEYS))),) + $(error Only one file may be in PRODUCT_ADB_KEYS: $(PRODUCT_ADB_KEYS)) +endif +.KATI_READONLY := PRODUCT_ADB_KEYS + +# Whether any paths are excluded from sanitization when SANITIZE_TARGET=cfi +PRODUCT_CFI_EXCLUDE_PATHS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_CFI_EXCLUDE_PATHS)) + +# Whether any paths should have CFI enabled for components +PRODUCT_CFI_INCLUDE_PATHS := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_CFI_INCLUDE_PATHS)) + +# which Soong namespaces to export to Make +PRODUCT_SOONG_NAMESPACES := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_SOONG_NAMESPACES)) + +# A flag to override PRODUCT_COMPATIBLE_PROPERTY +PRODUCT_COMPATIBLE_PROPERTY_OVERRIDE := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_COMPATIBLE_PROPERTY_OVERRIDE)) + +# Whether the whitelist of actionable compatible properties should be disabled or not +PRODUCT_ACTIONABLE_COMPATIBLE_PROPERTY_DISABLE := \ + $(strip $(PRODUCTS.$(INTERNAL_PRODUCT).PRODUCT_ACTIONABLE_COMPATIBLE_PROPERTY_DISABLE)) diff --git a/aosp/build/make/core/soong_config.mk b/aosp/build/make/core/soong_config.mk new file mode 100644 index 000000000..5e3895f4e --- /dev/null +++ b/aosp/build/make/core/soong_config.mk @@ -0,0 +1,177 @@ +SOONG := $(SOONG_OUT_DIR)/soong +SOONG_BOOTSTRAP := $(SOONG_OUT_DIR)/.soong.bootstrap +SOONG_BUILD_NINJA := $(SOONG_OUT_DIR)/build.ninja +SOONG_IN_MAKE := $(SOONG_OUT_DIR)/.soong.in_make +SOONG_MAKEVARS_MK := $(SOONG_OUT_DIR)/make_vars-$(TARGET_PRODUCT).mk +SOONG_VARIABLES := $(SOONG_OUT_DIR)/soong.variables +SOONG_ANDROID_MK := $(SOONG_OUT_DIR)/Android-$(TARGET_PRODUCT).mk + +BINDER32BIT := +ifneq ($(TARGET_USES_64_BIT_BINDER),true) +ifneq ($(TARGET_IS_64_BIT),true) +BINDER32BIT := true +endif +endif + +ifeq ($(WRITE_SOONG_VARIABLES),true) +# Converts a list to a JSON list. +# $1: List separator. +# $2: List. +_json_list = [$(if $(2),"$(subst $(1),"$(comma)",$(2))")] + +# Converts a space-separated list to a JSON list. +json_list = $(call _json_list,$(space),$(1)) + +# Converts a comma-separated list to a JSON list. +csv_to_json_list = $(call _json_list,$(comma),$(1)) + +# 1: Key name +# 2: Value +add_json_val = $(eval _contents := $$(_contents) "$$(strip $$(1))":$$(space)$$(strip $$(2))$$(comma)$$(newline)) +add_json_str = $(call add_json_val,$(1),"$(strip $(2))") +add_json_list = $(call add_json_val,$(1),$(call json_list,$(patsubst %,%,$(2)))) +add_json_csv = $(call add_json_val,$(1),$(call csv_to_json_list,$(strip $(2)))) +add_json_bool = $(call add_json_val,$(1),$(if $(strip $(2)),true,false)) + +invert_bool = $(if $(strip $(1)),,true) + +# Create soong.variables with copies of makefile settings. Runs every build, +# but only updates soong.variables if it changes +$(shell mkdir -p $(dir $(SOONG_VARIABLES))) +_contents := {$(newline) + +$(call add_json_str, Make_suffix, -$(TARGET_PRODUCT)) + +$(call add_json_str, BuildId, $(BUILD_ID)) +$(call add_json_str, BuildNumberFromFile, $$$(BUILD_NUMBER_FROM_FILE)) + +$(call add_json_str, Platform_version_name, $(PLATFORM_VERSION)) +$(call add_json_val, Platform_sdk_version, $(PLATFORM_SDK_VERSION)) +$(call add_json_str, Platform_sdk_codename, $(PLATFORM_VERSION_CODENAME)) +$(call add_json_bool, Platform_sdk_final, $(filter REL,$(PLATFORM_VERSION_CODENAME))) +$(call add_json_csv, Platform_version_active_codenames, $(PLATFORM_VERSION_ALL_CODENAMES)) +$(call add_json_csv, Platform_version_future_codenames, $(PLATFORM_VERSION_FUTURE_CODENAMES)) + +$(call add_json_bool, Allow_missing_dependencies, $(ALLOW_MISSING_DEPENDENCIES)) +$(call add_json_bool, Unbundled_build, $(TARGET_BUILD_APPS)) +$(call add_json_bool, Pdk, $(filter true,$(TARGET_BUILD_PDK))) + +$(call add_json_bool, Debuggable, $(filter userdebug eng,$(TARGET_BUILD_VARIANT))) +$(call add_json_bool, Eng, $(filter eng,$(TARGET_BUILD_VARIANT))) + +$(call add_json_str, DeviceName, $(TARGET_DEVICE)) +$(call add_json_str, DeviceArch, $(TARGET_ARCH)) +$(call add_json_str, DeviceArchVariant, $(TARGET_ARCH_VARIANT)) +$(call add_json_str, DeviceCpuVariant, $(TARGET_CPU_VARIANT)) +$(call add_json_list, DeviceAbi, $(TARGET_CPU_ABI) $(TARGET_CPU_ABI2)) + +$(call add_json_str, DeviceSecondaryArch, $(TARGET_2ND_ARCH)) +$(call add_json_str, DeviceSecondaryArchVariant, $(TARGET_2ND_ARCH_VARIANT)) +$(call add_json_str, DeviceSecondaryCpuVariant, $(TARGET_2ND_CPU_VARIANT)) +$(call add_json_list, DeviceSecondaryAbi, $(TARGET_2ND_CPU_ABI) $(TARGET_2ND_CPU_ABI2)) + +$(call add_json_str, HostArch, $(HOST_ARCH)) +$(call add_json_str, HostSecondaryArch, $(HOST_2ND_ARCH)) +$(call add_json_bool, HostStaticBinaries, $(BUILD_HOST_static)) + +$(call add_json_str, CrossHost, $(HOST_CROSS_OS)) +$(call add_json_str, CrossHostArch, $(HOST_CROSS_ARCH)) +$(call add_json_str, CrossHostSecondaryArch, $(HOST_CROSS_2ND_ARCH)) + +$(call add_json_list, ResourceOverlays, $(PRODUCT_PACKAGE_OVERLAYS) $(DEVICE_PACKAGE_OVERLAYS)) +$(call add_json_list, EnforceRROTargets, $(PRODUCT_ENFORCE_RRO_TARGETS)) +$(call add_json_list, EnforceRROExcludedOverlays, $(PRODUCT_ENFORCE_RRO_EXCLUDED_OVERLAYS)) + +$(call add_json_str, AAPTCharacteristics, $(TARGET_AAPT_CHARACTERISTICS)) +$(call add_json_list, AAPTConfig, $(PRODUCT_AAPT_CONFIG)) +$(call add_json_str, AAPTPreferredConfig, $(PRODUCT_AAPT_PREF_CONFIG)) +$(call add_json_list, AAPTPrebuiltDPI, $(PRODUCT_AAPT_PREBUILT_DPI)) + +$(call add_json_str, DefaultAppCertificate, $(PRODUCT_DEFAULT_DEV_CERTIFICATE)) + +$(call add_json_str, AppsDefaultVersionName, $(APPS_DEFAULT_VERSION_NAME)) + +$(call add_json_list, SanitizeHost, $(SANITIZE_HOST)) +$(call add_json_list, SanitizeDevice, $(SANITIZE_TARGET)) +$(call add_json_list, SanitizeDeviceDiag, $(SANITIZE_TARGET_DIAG)) +$(call add_json_list, SanitizeDeviceArch, $(SANITIZE_TARGET_ARCH)) + +$(call add_json_bool, Safestack, $(filter true,$(USE_SAFESTACK))) +$(call add_json_bool, EnableCFI, $(call invert_bool,$(filter false,$(ENABLE_CFI)))) +$(call add_json_list, CFIExcludePaths, $(CFI_EXCLUDE_PATHS) $(PRODUCT_CFI_EXCLUDE_PATHS)) +$(call add_json_list, CFIIncludePaths, $(CFI_INCLUDE_PATHS) $(PRODUCT_CFI_INCLUDE_PATHS)) +$(call add_json_list, IntegerOverflowExcludePaths, $(INTEGER_OVERFLOW_EXCLUDE_PATHS) $(PRODUCT_INTEGER_OVERFLOW_EXCLUDE_PATHS)) + +$(call add_json_bool, ClangTidy, $(filter 1 true,$(WITH_TIDY))) +$(call add_json_str, TidyChecks, $(WITH_TIDY_CHECKS)) + +$(call add_json_bool, NativeCoverage, $(filter true,$(NATIVE_COVERAGE))) +$(call add_json_list, CoveragePaths, $(COVERAGE_PATHS)) +$(call add_json_list, CoverageExcludePaths, $(COVERAGE_EXCLUDE_PATHS)) + +$(call add_json_bool, ArtUseReadBarrier, $(call invert_bool,$(filter false,$(PRODUCT_ART_USE_READ_BARRIER)))) +$(call add_json_bool, Binder32bit, $(BINDER32BIT)) +$(call add_json_bool, Brillo, $(BRILLO)) +$(call add_json_str, BtConfigIncludeDir, $(BOARD_BLUETOOTH_BDROID_BUILDCFG_INCLUDE_DIR)) +$(call add_json_bool, Device_uses_hwc2, $(filter true,$(TARGET_USES_HWC2))) +$(call add_json_list, DeviceKernelHeaders, $(TARGET_PROJECT_SYSTEM_INCLUDES)) +$(call add_json_bool, DevicePrefer32BitExecutables, $(filter true,$(TARGET_PREFER_32_BIT_EXECUTABLES))) +$(call add_json_str, DeviceVndkVersion, $(BOARD_VNDK_VERSION)) +$(call add_json_str, Platform_vndk_version, $(PLATFORM_VNDK_VERSION)) +$(call add_json_list, ExtraVndkVersions, $(PRODUCT_EXTRA_VNDK_VERSIONS)) +$(call add_json_list, DeviceSystemSdkVersions, $(BOARD_SYSTEMSDK_VERSIONS)) +$(call add_json_list, Platform_systemsdk_versions, $(PLATFORM_SYSTEMSDK_VERSIONS)) +$(call add_json_bool, Malloc_not_svelte, $(call invert_bool,$(filter true,$(MALLOC_SVELTE)))) +$(call add_json_str, Override_rs_driver, $(OVERRIDE_RS_DRIVER)) + +$(call add_json_bool, Treble_linker_namespaces, $(filter true,$(PRODUCT_TREBLE_LINKER_NAMESPACES))) +$(call add_json_bool, Enforce_vintf_manifest, $(filter true,$(PRODUCT_ENFORCE_VINTF_MANIFEST))) + +$(call add_json_bool, Uml, $(filter true,$(TARGET_USER_MODE_LINUX))) +$(call add_json_bool, Use_lmkd_stats_log, $(filter true,$(TARGET_LMKD_STATS_LOG))) +$(call add_json_str, VendorPath, $(TARGET_COPY_OUT_VENDOR)) +$(call add_json_str, OdmPath, $(TARGET_COPY_OUT_ODM)) +$(call add_json_str, ProductPath, $(TARGET_COPY_OUT_PRODUCT)) +$(call add_json_bool, MinimizeJavaDebugInfo, $(filter true,$(PRODUCT_MINIMIZE_JAVA_DEBUG_INFO))) + +$(call add_json_bool, UseGoma, $(filter-out false,$(USE_GOMA))) +$(call add_json_bool, Arc, $(filter true,$(TARGET_ARC))) + +$(call add_json_str, DistDir, $(if $(dist_goal), $(DIST_DIR))) + +$(call add_json_list, NamespacesToExport, $(PRODUCT_SOONG_NAMESPACES)) + +$(call add_json_list, PgoAdditionalProfileDirs, $(PGO_ADDITIONAL_PROFILE_DIRS)) + +$(call add_json_bool, Large_system_property_node, $(filter true,$(LARGE_SYSTEM_PROPERTY_NODE))) + +_contents := $(_contents) "VendorVars": {$(newline) +$(foreach namespace,$(SOONG_CONFIG_NAMESPACES),\ + $(eval _contents := $$(_contents) "$(namespace)": {$$(newline)) \ + $(foreach key,$(SOONG_CONFIG_$(namespace)),\ + $(eval _contents := $$(_contents) "$(key)": "$(SOONG_CONFIG_$(namespace)_$(key))",$$(newline)))\ + $(eval _contents := $$(_contents)$(if $(strip $(SOONG_CONFIG_$(namespace))),__SV_END) },$$(newline))) +_contents := $(_contents)$(if $(strip $(SOONG_CONFIG_NAMESPACES)),__SV_END) },$(newline) + +_contents := $(subst $(comma)$(newline)__SV_END,$(newline),$(_contents)__SV_END}$(newline)) + +$(file >$(SOONG_VARIABLES).tmp,$(_contents)) + +$(shell if ! cmp -s $(SOONG_VARIABLES).tmp $(SOONG_VARIABLES); then \ + mv $(SOONG_VARIABLES).tmp $(SOONG_VARIABLES); \ + else \ + rm $(SOONG_VARIABLES).tmp; \ + fi) + +_json_list := +json_list := +csv_to_json_list := +add_json_val := +add_json_str := +add_json_list := +add_json_csv := +add_json_bool := +invert_bool := +_contents := + +endif # CONFIGURE_SOONG diff --git a/aosp/build/make/core/version_defaults.mk b/aosp/build/make/core/version_defaults.mk new file mode 100644 index 000000000..17f74ecf0 --- /dev/null +++ b/aosp/build/make/core/version_defaults.mk @@ -0,0 +1,301 @@ +# +# Copyright (C) 2008 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# +# Handle various build version information. +# +# Guarantees that the following are defined: +# PLATFORM_VERSION +# PLATFORM_SDK_VERSION +# PLATFORM_VERSION_CODENAME +# DEFAULT_APP_TARGET_SDK +# BUILD_ID +# BUILD_NUMBER +# PLATFORM_SECURITY_PATCH +# PLATFORM_VNDK_VERSION +# PLATFORM_SYSTEMSDK_VERSIONS +# + +# Look for an optional file containing overrides of the defaults, +# but don't cry if we don't find it. We could just use -include, but +# the build.prop target also wants INTERNAL_BUILD_ID_MAKEFILE to be set +# if the file exists. +# +INTERNAL_BUILD_ID_MAKEFILE := $(wildcard $(BUILD_SYSTEM)/build_id.mk) +ifdef INTERNAL_BUILD_ID_MAKEFILE + include $(INTERNAL_BUILD_ID_MAKEFILE) +endif + +DEFAULT_PLATFORM_VERSION := PPR1 +MIN_PLATFORM_VERSION := PPR1 +MAX_PLATFORM_VERSION := PPR1 + +ALLOWED_VERSIONS := $(call allowed-platform-versions,\ + $(MIN_PLATFORM_VERSION),\ + $(MAX_PLATFORM_VERSION),\ + $(DEFAULT_PLATFORM_VERSION)) + +ifndef TARGET_PLATFORM_VERSION + TARGET_PLATFORM_VERSION := $(DEFAULT_PLATFORM_VERSION) +endif + +ifeq (,$(filter $(ALLOWED_VERSIONS), $(TARGET_PLATFORM_VERSION))) + $(warning Invalid TARGET_PLATFORM_VERSION '$(TARGET_PLATFORM_VERSION)', must be one of) + $(error $(ALLOWED_VERSIONS)) +endif + +# Default versions for each TARGET_PLATFORM_VERSION +# TODO: PLATFORM_VERSION, PLATFORM_SDK_VERSION, etc. should be conditional +# on this + +# This is the canonical definition of the platform version, +# which is the version that we reveal to the end user. +# Update this value when the platform version changes (rather +# than overriding it somewhere else). Can be an arbitrary string. + +# When you add a new PLATFORM_VERSION which will result in a new +# PLATFORM_SDK_VERSION please ensure you add a corresponding isAtLeast* +# method in the following java file: +# frameworks/support/compat/gingerbread/android/support/v4/os/BuildCompat.java + +# When you change PLATFORM_VERSION for a given PLATFORM_SDK_VERSION +# please add that PLATFORM_VERSION as well as clean up obsolete PLATFORM_VERSION's +# in the following text file: +# cts/tests/tests/os/assets/platform_versions.txt +PLATFORM_VERSION.PPR1 := 9 + +# These are the current development codenames, if the build is not a final +# release build. If this is a final release build, it is simply "REL". +PLATFORM_VERSION_CODENAME.PPR1 := REL + +ifndef PLATFORM_VERSION + PLATFORM_VERSION := $(PLATFORM_VERSION.$(TARGET_PLATFORM_VERSION)) + ifndef PLATFORM_VERSION + # PLATFORM_VERSION falls back to TARGET_PLATFORM_VERSION + PLATFORM_VERSION := $(TARGET_PLATFORM_VERSION) + endif +endif + +ifndef PLATFORM_SDK_VERSION + # This is the canonical definition of the SDK version, which defines + # the set of APIs and functionality available in the platform. It + # is a single integer that increases monotonically as updates to + # the SDK are released. It should only be incremented when the APIs for + # the new release are frozen (so that developers don't write apps against + # intermediate builds). During development, this number remains at the + # SDK version the branch is based on and PLATFORM_VERSION_CODENAME holds + # the code-name of the new development work. + + # When you change PLATFORM_SDK_VERSION please ensure you also update the + # corresponding methods for isAtLeast* in the following java file: + # frameworks/support/compat/gingerbread/android/support/v4/os/BuildCompat.java + + # When you increment the PLATFORM_SDK_VERSION please ensure you also + # clear out the following text file of all older PLATFORM_VERSION's: + # cts/tests/tests/os/assets/platform_versions.txt + PLATFORM_SDK_VERSION := 28 +endif + +ifndef PLATFORM_VERSION_CODENAME + PLATFORM_VERSION_CODENAME := $(PLATFORM_VERSION_CODENAME.$(TARGET_PLATFORM_VERSION)) + ifndef PLATFORM_VERSION_CODENAME + # PLATFORM_VERSION_CODENAME falls back to TARGET_PLATFORM_VERSION + PLATFORM_VERSION_CODENAME := $(TARGET_PLATFORM_VERSION) + endif + + # This is all of the *active* development codenames. There are future + # codenames not included in this list. This confusing name is needed because + # all_codenames has been baked into build.prop for ages. + # + # Should be either the same as PLATFORM_VERSION_CODENAME or a comma-separated + # list of additional codenames after PLATFORM_VERSION_CODENAME. + PLATFORM_VERSION_ALL_CODENAMES := + + # Build a list of all active code names. Avoid duplicates, and stop when we + # reach a codename that matches PLATFORM_VERSION_CODENAME (anything beyond + # that is not included in our build). + _versions_in_target := \ + $(call find_and_earlier,$(ALL_VERSIONS),$(TARGET_PLATFORM_VERSION)) + $(foreach version,$(_versions_in_target),\ + $(eval _codename := $(PLATFORM_VERSION_CODENAME.$(version)))\ + $(if $(filter $(_codename),$(PLATFORM_VERSION_ALL_CODENAMES)),,\ + $(eval PLATFORM_VERSION_ALL_CODENAMES += $(_codename)))) + + # This is all of the inactive development codenames. Available to be targeted + # in this branch but in the future relative to our current target. + PLATFORM_VERSION_FUTURE_CODENAMES := + + # Build a list of all untargeted code names. Avoid duplicates. + _versions_not_in_target := \ + $(filter-out $(PLATFORM_VERSION_ALL_CODENAMES),$(ALL_VERSIONS)) + $(foreach version,$(_versions_not_in_target),\ + $(eval _codename := $(PLATFORM_VERSION_CODENAME.$(version)))\ + $(if $(filter $(_codename),$(PLATFORM_VERSION_FUTURE_CODENAMES)),,\ + $(eval PLATFORM_VERSION_FUTURE_CODENAMES += $(_codename)))) + + # And convert from space separated to comma separated. + PLATFORM_VERSION_ALL_CODENAMES := \ + $(subst $(space),$(comma),$(strip $(PLATFORM_VERSION_ALL_CODENAMES))) + PLATFORM_VERSION_FUTURE_CODENAMES := \ + $(subst $(space),$(comma),$(strip $(PLATFORM_VERSION_FUTURE_CODENAMES))) + +endif + +ifeq (REL,$(PLATFORM_VERSION_CODENAME)) + PLATFORM_PREVIEW_SDK_VERSION := 0 +else + ifndef PLATFORM_PREVIEW_SDK_VERSION + # This is the definition of a preview SDK version over and above the current + # platform SDK version. Unlike the platform SDK version, a higher value + # for preview SDK version does NOT mean that all prior preview APIs are + # included. Packages reading this value to determine compatibility with + # known APIs should check that this value is precisely equal to the preview + # SDK version the package was built for, otherwise it should fall back to + # assuming the device can only support APIs as of the previous official + # public release. + # This value will always be 0 for release builds. + PLATFORM_PREVIEW_SDK_VERSION := 0 + endif +endif + +ifndef DEFAULT_APP_TARGET_SDK + # This is the default minSdkVersion and targetSdkVersion to use for + # all .apks created by the build system. It can be overridden by explicitly + # setting these in the .apk's AndroidManifest.xml. It is either the code + # name of the development build or, if this is a release build, the official + # SDK version of this release. + ifeq (REL,$(PLATFORM_VERSION_CODENAME)) + DEFAULT_APP_TARGET_SDK := $(PLATFORM_SDK_VERSION) + else + DEFAULT_APP_TARGET_SDK := $(PLATFORM_VERSION_CODENAME) + endif +endif + +ifndef PLATFORM_VNDK_VERSION + # This is the definition of the VNDK version for the current VNDK libraries. + # The version is only available when PLATFORM_VERSION_CODENAME == REL. + # Otherwise, it will be set to a CODENAME version. The ABI is allowed to be + # changed only before the Android version is released. Once + # PLATFORM_VNDK_VERSION is set to actual version, the ABI for this version + # will be frozon and emit build errors if any ABI for the VNDK libs are + # changed. + # After that the snapshot of the VNDK with this version will be generated. + # + # The VNDK version follows PLATFORM_SDK_VERSION. + ifeq (REL,$(PLATFORM_VERSION_CODENAME)) + PLATFORM_VNDK_VERSION := $(PLATFORM_SDK_VERSION) + else + PLATFORM_VNDK_VERSION := $(PLATFORM_VERSION_CODENAME) + endif +endif + +ifndef PLATFORM_SYSTEMSDK_MIN_VERSION + # This is the oldest version of system SDK that the platform supports. Contrary + # to the public SDK where platform essentially supports all previous SDK versions, + # platform supports only a few number of recent system SDK versions as some of + # old system APIs are gradually deprecated, removed and then deleted. + PLATFORM_SYSTEMSDK_MIN_VERSION := 28 +endif + +# This is the list of system SDK versions that the current platform supports. +PLATFORM_SYSTEMSDK_VERSIONS := +ifneq (,$(PLATFORM_SYSTEMSDK_MIN_VERSION)) + $(if $(call math_is_number,$(PLATFORM_SYSTEMSDK_MIN_VERSION)),,\ + $(error PLATFORM_SYSTEMSDK_MIN_VERSION must be a number, but was $(PLATFORM_SYSTEMSDK_MIN_VERSION))) + PLATFORM_SYSTEMSDK_VERSIONS := $(call int_range_list,$(PLATFORM_SYSTEMSDK_MIN_VERSION),$(PLATFORM_SDK_VERSION)) +endif +# Platform always supports the current version +ifeq (REL,$(PLATFORM_VERSION_CODENAME)) + PLATFORM_SYSTEMSDK_VERSIONS += $(PLATFORM_SDK_VERSION) +else + PLATFORM_SYSTEMSDK_VERSIONS += $(PLATFORM_VERSION_CODENAME) +endif +PLATFORM_SYSTEMSDK_VERSIONS := $(strip $(sort $(PLATFORM_SYSTEMSDK_VERSIONS))) + +ifndef PLATFORM_SECURITY_PATCH + # Used to indicate the security patch that has been applied to the device. + # It must signify that the build includes all security patches issued up through the designated Android Public Security Bulletin. + # It must be of the form "YYYY-MM-DD" on production devices. + # It must match one of the Android Security Patch Level strings of the Public Security Bulletins. + # If there is no $PLATFORM_SECURITY_PATCH set, keep it empty. + PLATFORM_SECURITY_PATCH := 2018-08-05 +endif + +ifndef PLATFORM_SECURITY_PATCH_TIMESTAMP + # Used to indicate the matching timestamp for the security patch string in PLATFORM_SECURITY_PATCH. + ifneq (,$(findstring Darwin,$(UNAME))) + PLATFORM_SECURITY_PATCH_TIMESTAMP := $(shell date -jf '%Y-%m-%d %T %Z' '$(PLATFORM_SECURITY_PATCH) 00:00:00 GMT' +%s) + else + PLATFORM_SECURITY_PATCH_TIMESTAMP := $(shell date -d 'TZ="GMT" $(PLATFORM_SECURITY_PATCH)' +%s) + endif +endif +.KATI_READONLY := PLATFORM_SECURITY_PATCH_TIMESTAMP + +ifndef PLATFORM_BASE_OS + # Used to indicate the base os applied to the device. + # Can be an arbitrary string, but must be a single word. + # + # If there is no $PLATFORM_BASE_OS set, keep it empty. + PLATFORM_BASE_OS := +endif + +ifndef BUILD_ID + # Used to signify special builds. E.g., branches and/or releases, + # like "M5-RC7". Can be an arbitrary string, but must be a single + # word and a valid file name. + # + # If there is no BUILD_ID set, make it obvious. + BUILD_ID := UNKNOWN +endif + +ifndef BUILD_DATETIME + # Used to reproduce builds by setting the same time. Must be the number + # of seconds since the Epoch. + BUILD_DATETIME := $(shell date +%s) +endif + +ifneq (,$(findstring Darwin,$(UNAME))) +DATE := date -r $(BUILD_DATETIME) +else +DATE := date -d @$(BUILD_DATETIME) +endif + +# Everything should be using BUILD_DATETIME_FROM_FILE instead. +# BUILD_DATETIME and DATE can be removed once BUILD_NUMBER moves +# to soong_ui. +BUILD_DATETIME := + +HAS_BUILD_NUMBER := true +ifndef BUILD_NUMBER + # BUILD_NUMBER should be set to the source control value that + # represents the current state of the source code. E.g., a + # perforce changelist number or a git hash. Can be an arbitrary string + # (to allow for source control that uses something other than numbers), + # but must be a single word and a valid file name. + # + # If no BUILD_NUMBER is set, create a useful "I am an engineering build + # from this date/time" value. Make it start with a non-digit so that + # anyone trying to parse it as an integer will probably get "0". + BUILD_NUMBER := 9.0.0.143C01 + HAS_BUILD_NUMBER := false +endif + +ifndef PLATFORM_MIN_SUPPORTED_TARGET_SDK_VERSION + # Used to set minimum supported target sdk version. Apps targeting sdk + # version lower than the set value will fail to install and run on android + # device. + PLATFORM_MIN_SUPPORTED_TARGET_SDK_VERSION := 17 +endif diff --git a/aosp/build/make/target/product/core_base.mk b/aosp/build/make/target/product/core_base.mk new file mode 100644 index 000000000..ffae96a87 --- /dev/null +++ b/aosp/build/make/target/product/core_base.mk @@ -0,0 +1,66 @@ +# +# Copyright (C) 2013 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Note that components added here will be also shared in PDK. Components +# that should not be in PDK should be added in lower level like core.mk. + +PRODUCT_PROPERTY_OVERRIDES := \ + ro.config.notification_sound=OnTheHunt.ogg \ + ro.config.alarm_alert=Alarm_Classic.ogg \ + ro.config.media_vol_default=13 + +PRODUCT_PACKAGES += \ + ContactsProvider \ + DefaultContainerService \ + Home \ + TelephonyProvider \ + UserDictionaryProvider \ + atrace \ + libandroidfw \ + libaudiopreprocessing \ + libaudioutils \ + libfilterpack_imageproc \ + libgabi++ \ + libmdnssd \ + libnfc_ndef \ + libpowermanager \ + libspeexresampler \ + libstagefright_soft_aacdec \ + libstagefright_soft_aacenc \ + libstagefright_soft_amrdec \ + libstagefright_soft_amrnbenc \ + libstagefright_soft_amrwbenc \ + libstagefright_soft_avcdec \ + libstagefright_soft_avcenc \ + libstagefright_soft_flacdec \ + libstagefright_soft_flacenc \ + libstagefright_soft_g711dec \ + libstagefright_soft_gsmdec \ + libstagefright_soft_hevcdec \ + libstagefright_soft_mp3dec \ + libstagefright_soft_mpeg2dec \ + libstagefright_soft_mpeg4dec \ + libstagefright_soft_mpeg4enc \ + libstagefright_soft_opusdec \ + libstagefright_soft_rawdec \ + libstagefright_soft_vorbisdec \ + libstagefright_soft_vpxdec \ + libstagefright_soft_vpxenc \ + libvariablespeed \ + libwebrtc_audio_preprocessing \ + mdnsd \ + requestsync \ + +$(call inherit-product, $(SRC_TARGET_DIR)/product/core_minimal.mk) diff --git a/aosp/build/make/target/product/embedded.mk b/aosp/build/make/target/product/embedded.mk new file mode 100644 index 000000000..3c82a7d3d --- /dev/null +++ b/aosp/build/make/target/product/embedded.mk @@ -0,0 +1,120 @@ +# +# Copyright (C) 2009 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is a build configuration for a very minimal build of the +# Open-Source part of the tree. + +PRODUCT_PACKAGES += \ + adb \ + watchdogd \ + usbd \ + android.hardware.configstore@1.1-service \ + android.hidl.allocator@1.0-service \ + android.hidl.memory@1.0-impl \ + android.hidl.memory@1.0-impl.vendor \ + atrace \ + blank_screen \ + bootanimation \ + bootstat \ + cmd \ + crash_dump \ + debuggerd\ + dumpstate \ + dumpsys \ + fastboot \ + gralloc.default \ + healthd \ + hwservicemanager \ + init \ + init.environ.rc \ + init.rc \ + libEGL \ + libETC1 \ + libFFTEm \ + libGLESv1_CM \ + libGLESv2 \ + libGLESv3 \ + libbinder \ + libc \ + libc_malloc_debug \ + libc_malloc_hooks \ + libcutils \ + libdl \ + libgui \ + libhardware \ + libhardware_legacy \ + libjpeg \ + liblog \ + libm \ + libpixelflinger \ + libpower \ + libsigchain \ + libstdc++ \ + libsurfaceflinger \ + libsurfaceflinger_ddmconnection \ + libsysutils \ + libui \ + libutils \ + linker \ + lmkd \ + logcat \ + lshal \ + service \ + servicemanager \ + shell_and_utilities \ + storaged \ + surfaceflinger \ + thermalserviced \ + tombstoned \ + tzdatacheck \ + vndservice \ + vndservicemanager \ + +# VINTF data +PRODUCT_PACKAGES += \ + device_compatibility_matrix.xml \ + device_manifest.xml \ + framework_manifest.xml \ + framework_compatibility_matrix.xml \ + +# SELinux packages are added as dependencies of the selinux_policy +# phony package. +PRODUCT_PACKAGES += \ + selinux_policy \ + +# AID Generation for +# and +PRODUCT_PACKAGES += \ + passwd \ + group \ + fs_config_files \ + fs_config_dirs + +# If there are product-specific adb keys defined, install them on debuggable +# builds. +PRODUCT_PACKAGES_DEBUG += \ + adb_keys + +# Ensure that this property is always defined so that bionic_systrace.cpp +# can rely on it being initially set by init. +PRODUCT_SYSTEM_DEFAULT_PROPERTIES += \ + debug.atrace.tags.enableflags=0 + +PRODUCT_COPY_FILES += \ + system/core/rootdir/init.usb.rc:root/init.usb.rc \ + system/core/rootdir/init.usb.configfs.rc:root/init.usb.configfs.rc \ + system/core/rootdir/ueventd.rc:root/ueventd.rc \ + system/core/rootdir/etc/hosts:system/etc/hosts diff --git a/aosp/build/make/target/product/generic_no_telephony.mk b/aosp/build/make/target/product/generic_no_telephony.mk new file mode 100644 index 000000000..c8a3c5b47 --- /dev/null +++ b/aosp/build/make/target/product/generic_no_telephony.mk @@ -0,0 +1,77 @@ +# +# Copyright (C) 2007 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# This is a generic phone product that isn't specialized for a specific device. +# It includes the base Android platform. + +PRODUCT_PACKAGES := \ + Bluetooth \ + BluetoothMidiService \ + Gallery2 \ + Music \ + MusicFX \ + OneTimeInitializer \ + Provision \ + SystemUI \ + SysuiDarkThemeOverlay \ + DisplayCutoutEmulationDoubleOverlay \ + DisplayCutoutEmulationCornerOverlay \ + DisplayCutoutEmulationTallOverlay \ + EasterEgg \ + WallpaperCropper + +PRODUCT_PACKAGES += \ + clatd \ + clatd.conf \ + pppd \ + screenrecord + +PRODUCT_PACKAGES += \ + librs_jni \ + libvideoeditor_jni \ + libvideoeditor_core \ + libvideoeditor_osal \ + libvideoeditor_videofilters \ + libvideoeditorplayer \ + +PRODUCT_PACKAGES += \ + audio.primary.default \ + local_time.default \ + vibrator.default \ + power.default + +PRODUCT_COPY_FILES := \ + frameworks/av/media/libeffects/data/audio_effects.conf:system/etc/audio_effects.conf + +PRODUCT_PROPERTY_OVERRIDES += \ + ro.carrier=unknown + +$(call inherit-product-if-exists, frameworks/base/data/fonts/fonts.mk) +$(call inherit-product-if-exists, external/google-fonts/dancing-script/fonts.mk) +$(call inherit-product-if-exists, external/google-fonts/carrois-gothic-sc/fonts.mk) +$(call inherit-product-if-exists, external/google-fonts/coming-soon/fonts.mk) +$(call inherit-product-if-exists, external/google-fonts/cutive-mono/fonts.mk) +$(call inherit-product-if-exists, external/noto-fonts/fonts.mk) +$(call inherit-product-if-exists, external/roboto-fonts/fonts.mk) +$(call inherit-product-if-exists, external/hyphenation-patterns/patterns.mk) +$(call inherit-product-if-exists, frameworks/base/data/keyboards/keyboards.mk) +$(call inherit-product-if-exists, frameworks/webview/chromium/chromium.mk) +$(call inherit-product, $(SRC_TARGET_DIR)/product/core.mk) + +# Overrides +PRODUCT_BRAND := generic +PRODUCT_DEVICE := generic +PRODUCT_NAME := generic_no_telephony diff --git a/aosp/build/make/tools/buildinfo.sh b/aosp/build/make/tools/buildinfo.sh new file mode 100755 index 000000000..32167ddbf --- /dev/null +++ b/aosp/build/make/tools/buildinfo.sh @@ -0,0 +1,64 @@ +#!/bin/bash + +echo "# begin build properties" +echo "# autogenerated by buildinfo.sh" + +echo "ro.build.id=$BUILD_ID" +echo "ro.build.display.id=$BUILD_DISPLAY_ID" +echo "ro.build.version.incremental=$BUILD_NUMBER" +echo "ro.build.version.sdk=$PLATFORM_SDK_VERSION" +echo "ro.build.version.preview_sdk=$PLATFORM_PREVIEW_SDK_VERSION" +echo "ro.build.version.codename=$PLATFORM_VERSION_CODENAME" +echo "ro.build.version.all_codenames=$PLATFORM_VERSION_ALL_CODENAMES" +echo "ro.build.version.release=$PLATFORM_VERSION" +echo "ro.build.version.security_patch=$PLATFORM_SECURITY_PATCH" +echo "ro.build.version.base_os=$PLATFORM_BASE_OS" +echo "ro.build.version.min_supported_target_sdk=$PLATFORM_MIN_SUPPORTED_TARGET_SDK_VERSION" +echo "ro.build.date=`$DATE`" +echo "ro.build.date.utc=`$DATE +%s`" +echo "ro.build.type=$TARGET_BUILD_TYPE" +echo "ro.build.user=$USER" +echo "ro.build.host=Builder" +echo "ro.build.tags=$BUILD_VERSION_TAGS" +echo "ro.build.flavor=$TARGET_BUILD_FLAVOR" +if [ -n "$BOARD_BUILD_SYSTEM_ROOT_IMAGE" ] ; then + echo "ro.build.system_root_image=$BOARD_BUILD_SYSTEM_ROOT_IMAGE" +fi +if [ -n "$AB_OTA_UPDATER" ] ; then + echo "ro.build.ab_update=$AB_OTA_UPDATER" +fi +echo "ro.product.model=$PRODUCT_MODEL" +echo "ro.product.brand=$PRODUCT_BRAND" +echo "ro.product.name=$PRODUCT_NAME" +echo "ro.product.device=$TARGET_DEVICE" + +# These values are deprecated, use "ro.product.cpu.abilist" +# instead (see below). +echo "# ro.product.cpu.abi and ro.product.cpu.abi2 are obsolete," +echo "# use ro.product.cpu.abilist instead." +echo "ro.product.cpu.abi=$TARGET_CPU_ABI" +if [ -n "$TARGET_CPU_ABI2" ] ; then + echo "ro.product.cpu.abi2=$TARGET_CPU_ABI2" +fi +echo "ro.product.cpu.abilist=$TARGET_CPU_ABI_LIST" +echo "ro.product.cpu.abilist32=$TARGET_CPU_ABI_LIST_32_BIT" +echo "ro.product.cpu.abilist64=$TARGET_CPU_ABI_LIST_64_BIT" + +echo "ro.product.manufacturer=$PRODUCT_MANUFACTURER" +if [ -n "$PRODUCT_DEFAULT_LOCALE" ] ; then + echo "ro.product.locale=$PRODUCT_DEFAULT_LOCALE" +fi +echo "ro.wifi.channels=$PRODUCT_DEFAULT_WIFI_CHANNELS" + +echo "# ro.build.product is obsolete; use ro.product.device" +echo "ro.build.product=$TARGET_DEVICE" + +echo "# Do not try to parse description, fingerprint, or thumbprint" +echo "ro.build.description=$PRIVATE_BUILD_DESC" +echo "ro.build.fingerprint=$BUILD_FINGERPRINT" +if [ -n "$BUILD_THUMBPRINT" ] ; then + echo "ro.build.thumbprint=$BUILD_THUMBPRINT" +fi +echo "ro.build.characteristics=$TARGET_AAPT_CHARACTERISTICS" + +echo "# end build properties" diff --git a/aosp/build/soong/android/variable.go b/aosp/build/soong/android/variable.go new file mode 100644 index 000000000..12132ddb6 --- /dev/null +++ b/aosp/build/soong/android/variable.go @@ -0,0 +1,425 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package android + +import ( + "fmt" + "reflect" + "runtime" + "strings" + + "github.com/google/blueprint/proptools" +) + +func init() { + PreDepsMutators(func(ctx RegisterMutatorsContext) { + ctx.BottomUp("variable", variableMutator).Parallel() + }) +} + +type variableProperties struct { + Product_variables struct { + Platform_sdk_version struct { + Asflags []string + Cflags []string + } + + // unbundled_build is a catch-all property to annotate modules that don't build in one or + // more unbundled branches, usually due to dependencies missing from the manifest. + Unbundled_build struct { + Enabled *bool `android:"arch_variant"` + } `android:"arch_variant"` + + Brillo struct { + Cflags []string + Version_script *string `android:"arch_variant"` + } `android:"arch_variant"` + + Malloc_not_svelte struct { + Cflags []string + } + + Safestack struct { + Cflags []string `android:"arch_variant"` + } `android:"arch_variant"` + + Binder32bit struct { + Cflags []string + } + + Device_uses_hwc2 struct { + Cflags []string + } + + Override_rs_driver struct { + Cflags []string + } + + // treble_linker_namespaces is true when the system/vendor linker namespace separation is + // enabled. + Treble_linker_namespaces struct { + Cflags []string + } + // enforce_vintf_manifest is true when a device is required to have a vintf manifest. + Enforce_vintf_manifest struct { + Cflags []string + } + + // debuggable is true for eng and userdebug builds, and can be used to turn on additional + // debugging features that don't significantly impact runtime behavior. userdebug builds + // are used for dogfooding and performance testing, and should be as similar to user builds + // as possible. + Debuggable struct { + Cflags []string + Cppflags []string + Init_rc []string + } + + // eng is true for -eng builds, and can be used to turn on additionaly heavyweight debugging + // features. + Eng struct { + Cflags []string + Cppflags []string + } + + Pdk struct { + Enabled *bool `android:"arch_variant"` + } `android:"arch_variant"` + + Uml struct { + Cppflags []string + } + + Use_lmkd_stats_log struct { + Cflags []string + } + + Arc struct { + Cflags []string + Exclude_srcs []string + Include_dirs []string + Shared_libs []string + Static_libs []string + Srcs []string + } + + Large_system_property_node struct { + Cflags []string + } + } `android:"arch_variant"` +} + +var zeroProductVariables variableProperties + +type productVariables struct { + // Suffix to add to generated Makefiles + Make_suffix *string `json:",omitempty"` + + BuildId *string `json:",omitempty"` + BuildNumberFromFile *string `json:",omitempty"` + DateFromFile *string `json:",omitempty"` + + Platform_version_name *string `json:",omitempty"` + Platform_sdk_version *int `json:",omitempty"` + Platform_sdk_codename *string `json:",omitempty"` + Platform_sdk_final *bool `json:",omitempty"` + Platform_version_active_codenames []string `json:",omitempty"` + Platform_version_future_codenames []string `json:",omitempty"` + Platform_vndk_version *string `json:",omitempty"` + Platform_systemsdk_versions []string `json:",omitempty"` + + DeviceName *string `json:",omitempty"` + DeviceArch *string `json:",omitempty"` + DeviceArchVariant *string `json:",omitempty"` + DeviceCpuVariant *string `json:",omitempty"` + DeviceAbi *[]string `json:",omitempty"` + DeviceVndkVersion *string `json:",omitempty"` + DeviceSystemSdkVersions *[]string `json:",omitempty"` + + DeviceSecondaryArch *string `json:",omitempty"` + DeviceSecondaryArchVariant *string `json:",omitempty"` + DeviceSecondaryCpuVariant *string `json:",omitempty"` + DeviceSecondaryAbi *[]string `json:",omitempty"` + + HostArch *string `json:",omitempty"` + HostSecondaryArch *string `json:",omitempty"` + + CrossHost *string `json:",omitempty"` + CrossHostArch *string `json:",omitempty"` + CrossHostSecondaryArch *string `json:",omitempty"` + + ResourceOverlays *[]string `json:",omitempty"` + EnforceRROTargets *[]string `json:",omitempty"` + EnforceRROExcludedOverlays *[]string `json:",omitempty"` + + AAPTCharacteristics *string `json:",omitempty"` + AAPTConfig *[]string `json:",omitempty"` + AAPTPreferredConfig *string `json:",omitempty"` + AAPTPrebuiltDPI *[]string `json:",omitempty"` + + DefaultAppCertificate *string `json:",omitempty"` + + AppsDefaultVersionName *string `json:",omitempty"` + + Allow_missing_dependencies *bool `json:",omitempty"` + Unbundled_build *bool `json:",omitempty"` + Brillo *bool `json:",omitempty"` + Malloc_not_svelte *bool `json:",omitempty"` + Safestack *bool `json:",omitempty"` + HostStaticBinaries *bool `json:",omitempty"` + Binder32bit *bool `json:",omitempty"` + UseGoma *bool `json:",omitempty"` + Debuggable *bool `json:",omitempty"` + Eng *bool `json:",omitempty"` + Device_uses_hwc2 *bool `json:",omitempty"` + Treble_linker_namespaces *bool `json:",omitempty"` + Sepolicy_split *bool `json:",omitempty"` + Enforce_vintf_manifest *bool `json:",omitempty"` + Pdk *bool `json:",omitempty"` + Uml *bool `json:",omitempty"` + Use_lmkd_stats_log *bool `json:",omitempty"` + Arc *bool `json:",omitempty"` + MinimizeJavaDebugInfo *bool `json:",omitempty"` + + IntegerOverflowExcludePaths *[]string `json:",omitempty"` + + EnableCFI *bool `json:",omitempty"` + CFIExcludePaths *[]string `json:",omitempty"` + CFIIncludePaths *[]string `json:",omitempty"` + + VendorPath *string `json:",omitempty"` + OdmPath *string `json:",omitempty"` + ProductPath *string `json:",omitempty"` + + ClangTidy *bool `json:",omitempty"` + TidyChecks *string `json:",omitempty"` + + NativeCoverage *bool `json:",omitempty"` + CoveragePaths *[]string `json:",omitempty"` + CoverageExcludePaths *[]string `json:",omitempty"` + + DevicePrefer32BitExecutables *bool `json:",omitempty"` + HostPrefer32BitExecutables *bool `json:",omitempty"` + + SanitizeHost []string `json:",omitempty"` + SanitizeDevice []string `json:",omitempty"` + SanitizeDeviceDiag []string `json:",omitempty"` + SanitizeDeviceArch []string `json:",omitempty"` + + ArtUseReadBarrier *bool `json:",omitempty"` + + BtConfigIncludeDir *string `json:",omitempty"` + + Override_rs_driver *string `json:",omitempty"` + + DeviceKernelHeaders []string `json:",omitempty"` + DistDir *string `json:",omitempty"` + + ExtraVndkVersions []string `json:",omitempty"` + + NamespacesToExport []string `json:",omitempty"` + + PgoAdditionalProfileDirs []string `json:",omitempty"` + + VendorVars map[string]map[string]string `json:",omitempty"` + + Large_system_property_node *bool `json:",omitempty"` +} + +func boolPtr(v bool) *bool { + return &v +} + +func intPtr(v int) *int { + return &v +} + +func stringPtr(v string) *string { + return &v +} + +func (v *productVariables) SetDefaultConfig() { + *v = productVariables{ + Platform_sdk_version: intPtr(26), + Platform_version_active_codenames: []string{"P"}, + Platform_version_future_codenames: []string{"P"}, + + HostArch: stringPtr("x86_64"), + HostSecondaryArch: stringPtr("x86"), + DeviceName: stringPtr("generic_arm64"), + DeviceArch: stringPtr("arm64"), + DeviceArchVariant: stringPtr("armv8-a"), + DeviceCpuVariant: stringPtr("generic"), + DeviceAbi: &[]string{"arm64-v8a"}, + DeviceSecondaryArch: stringPtr("arm"), + DeviceSecondaryArchVariant: stringPtr("armv8-a"), + DeviceSecondaryCpuVariant: stringPtr("generic"), + DeviceSecondaryAbi: &[]string{"armeabi-v7a", "armeabi"}, + + AAPTConfig: &[]string{"normal", "large", "xlarge", "hdpi", "xhdpi", "xxhdpi"}, + AAPTPreferredConfig: stringPtr("xhdpi"), + AAPTCharacteristics: stringPtr("nosdcard"), + AAPTPrebuiltDPI: &[]string{"xhdpi", "xxhdpi"}, + + Malloc_not_svelte: boolPtr(true), + Safestack: boolPtr(false), + } + + if runtime.GOOS == "linux" { + v.CrossHost = stringPtr("windows") + v.CrossHostArch = stringPtr("x86") + v.CrossHostSecondaryArch = stringPtr("x86_64") + } +} + +func variableMutator(mctx BottomUpMutatorContext) { + var module Module + var ok bool + if module, ok = mctx.Module().(Module); !ok { + return + } + + // TODO: depend on config variable, create variants, propagate variants up tree + a := module.base() + variableValues := reflect.ValueOf(&a.variableProperties.Product_variables).Elem() + zeroValues := reflect.ValueOf(zeroProductVariables.Product_variables) + + for i := 0; i < variableValues.NumField(); i++ { + variableValue := variableValues.Field(i) + zeroValue := zeroValues.Field(i) + name := variableValues.Type().Field(i).Name + property := "product_variables." + proptools.PropertyNameForField(name) + + // Check that the variable was set for the product + val := reflect.ValueOf(mctx.Config().productVariables).FieldByName(name) + if !val.IsValid() || val.Kind() != reflect.Ptr || val.IsNil() { + continue + } + + val = val.Elem() + + // For bools, check that the value is true + if val.Kind() == reflect.Bool && val.Bool() == false { + continue + } + + // Check if any properties were set for the module + if reflect.DeepEqual(variableValue.Interface(), zeroValue.Interface()) { + continue + } + + a.setVariableProperties(mctx, property, variableValue, val.Interface()) + } +} + +func (a *ModuleBase) setVariableProperties(ctx BottomUpMutatorContext, + prefix string, productVariablePropertyValue reflect.Value, variableValue interface{}) { + + printfIntoProperties(ctx, prefix, productVariablePropertyValue, variableValue) + + err := proptools.AppendMatchingProperties(a.generalProperties, + productVariablePropertyValue.Addr().Interface(), nil) + if err != nil { + if propertyErr, ok := err.(*proptools.ExtendPropertyError); ok { + ctx.PropertyErrorf(propertyErr.Property, "%s", propertyErr.Err.Error()) + } else { + panic(err) + } + } +} + +func printfIntoPropertiesError(ctx BottomUpMutatorContext, prefix string, + productVariablePropertyValue reflect.Value, i int, err error) { + + field := productVariablePropertyValue.Type().Field(i).Name + property := prefix + "." + proptools.PropertyNameForField(field) + ctx.PropertyErrorf(property, "%s", err) +} + +func printfIntoProperties(ctx BottomUpMutatorContext, prefix string, + productVariablePropertyValue reflect.Value, variableValue interface{}) { + + for i := 0; i < productVariablePropertyValue.NumField(); i++ { + propertyValue := productVariablePropertyValue.Field(i) + kind := propertyValue.Kind() + if kind == reflect.Ptr { + if propertyValue.IsNil() { + continue + } + propertyValue = propertyValue.Elem() + } + switch propertyValue.Kind() { + case reflect.String: + err := printfIntoProperty(propertyValue, variableValue) + if err != nil { + printfIntoPropertiesError(ctx, prefix, productVariablePropertyValue, i, err) + } + case reflect.Slice: + for j := 0; j < propertyValue.Len(); j++ { + err := printfIntoProperty(propertyValue.Index(j), variableValue) + if err != nil { + printfIntoPropertiesError(ctx, prefix, productVariablePropertyValue, i, err) + } + } + case reflect.Bool: + // Nothing + case reflect.Struct: + printfIntoProperties(ctx, prefix, propertyValue, variableValue) + default: + panic(fmt.Errorf("unsupported field kind %q", propertyValue.Kind())) + } + } +} + +func printfIntoProperty(propertyValue reflect.Value, variableValue interface{}) error { + s := propertyValue.String() + + count := strings.Count(s, "%") + if count == 0 { + return nil + } + + if count > 1 { + return fmt.Errorf("product variable properties only support a single '%%'") + } + + if strings.Contains(s, "%d") { + switch v := variableValue.(type) { + case int: + // Nothing + case bool: + if v { + variableValue = 1 + } else { + variableValue = 0 + } + default: + return fmt.Errorf("unsupported type %T for %%d", variableValue) + } + } else if strings.Contains(s, "%s") { + switch variableValue.(type) { + case string: + // Nothing + default: + return fmt.Errorf("unsupported type %T for %%s", variableValue) + } + } else { + return fmt.Errorf("unsupported %% in product variable property") + } + + propertyValue.Set(reflect.ValueOf(fmt.Sprintf(s, variableValue))) + + return nil +} diff --git a/aosp/create_monbox_package.sh b/aosp/create_monbox_package.sh new file mode 100755 index 000000000..58c0b1281 --- /dev/null +++ b/aosp/create_monbox_package.sh @@ -0,0 +1,45 @@ +#!/bin/bash +basepath=$(cd `dirname $0`; pwd) +echo ${basepath} + +set -ex + +ramdisk=${basepath}/out/target/product/arm64/ramdisk.img +system=${basepath}/out/target/product/arm64/system.img +destdir=$1 + +if [ -z "$ramdisk" ] || [ -z "$system" ]; then + echo "Usage: $0 " + exit 1 +fi + +workdir=`mktemp -d` +rootfs=$workdir/rootfs + +mkdir -p $rootfs + +# Extract ramdisk and preserve ownership of files +(cd $rootfs ; cat $ramdisk | gzip -d | sudo cpio -i) + +mkdir $workdir/system +sudo mount -o loop,ro $system $workdir/system +sudo cp -ar $workdir/system/* $rootfs/system +sudo umount $workdir/system + +if [ -e $destdir/android.img ]; then + DATE=`date +%F_%R` + SAVETO=$destdir/android-old-$DATE.img + + echo "#########################################################" + echo "# WARNING: Old android.img still exists. " + echo "# Moving it to $SAVETO. " + echo "#########################################################" + + mv $destdir/android.img $SAVETO +fi + +sudo mksquashfs $rootfs $destdir/android.img -comp xz -no-xattrs +sudo chown $USER:$USER $destdir/android.img + +sudo rm -rf $workdir + diff --git a/aosp/device/generic/goldfish/audio/Android.mk b/aosp/device/generic/goldfish/audio/Android.mk new file mode 100644 index 000000000..83c8b7fb9 --- /dev/null +++ b/aosp/device/generic/goldfish/audio/Android.mk @@ -0,0 +1,58 @@ +# +# Copyright (C) 2011 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_VENDOR_MODULE := true +LOCAL_MODULE := audio.primary.goldfish_orig +LOCAL_MODULE_RELATIVE_PATH := hw +LOCAL_MODULE_TAGS := optional + +LOCAL_SHARED_LIBRARIES := libcutils liblog + +LOCAL_SRC_FILES := audio_hw.c + +LOCAL_C_INCLUDES += \ + external/tinyalsa/include \ + +LOCAL_SHARED_LIBRARIES += \ + libdl \ + libtinyalsa + +LOCAL_CFLAGS := -Wno-unused-parameter +LOCAL_HEADER_LIBRARIES := libhardware_headers + +include $(BUILD_SHARED_LIBRARY) + +include $(CLEAR_VARS) + +LOCAL_VENDOR_MODULE := true +LOCAL_MODULE := audio.primary.goldfish_legacy +LOCAL_MODULE_RELATIVE_PATH := hw +LOCAL_MODULE_TAGS := optional + +LOCAL_SHARED_LIBRARIES := libcutils liblog + +LOCAL_SRC_FILES := audio_hw_legacy.c + +LOCAL_SHARED_LIBRARIES += \ + libdl + +LOCAL_CFLAGS := -Wno-unused-parameter +LOCAL_HEADER_LIBRARIES := libhardware_headers + +include $(BUILD_SHARED_LIBRARY) diff --git a/aosp/device/generic/goldfish/camera/Android.mk b/aosp/device/generic/goldfish/camera/Android.mk new file mode 100644 index 000000000..5dbdff08d --- /dev/null +++ b/aosp/device/generic/goldfish/camera/Android.mk @@ -0,0 +1,129 @@ +# Copyright (C) 2011 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +ifneq ($(filter generic_x86 generic_x86_64 generic generic_arm64 generic_mips generic_mips64, $(TARGET_DEVICE)),) + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +# Emulator camera module######################################################## + +emulator_camera_module_relative_path := hw +emulator_camera_cflags := -fno-short-enums -DQEMU_HARDWARE +emulator_camera_cflags += -Wno-unused-parameter -Wno-missing-field-initializers +emulator_camera_clang_flags := -Wno-c++11-narrowing +emulator_camera_shared_libraries := \ + libbinder \ + libexif \ + liblog \ + libutils \ + libcutils \ + libEGL \ + libGLESv1_CM \ + libGLESv2 \ + libui \ + libdl \ + libjpeg \ + libcamera_metadata \ + libhardware + +emulator_camera_static_libraries := \ + android.hardware.camera.common@1.0-helper \ + libyuv_static + +emulator_camera_c_includes := external/libjpeg-turbo \ + external/libexif \ + external/libyuv/files/include \ + frameworks/native/include/media/hardware \ + $(LOCAL_PATH)/../include \ + $(LOCAL_PATH)/../../goldfish-opengl/system/OpenglSystemCommon \ + $(call include-path-for, camera) + +emulator_camera_src := \ + EmulatedCameraHal.cpp \ + EmulatedCameraFactory.cpp \ + EmulatedCameraHotplugThread.cpp \ + EmulatedBaseCamera.cpp \ + EmulatedCamera.cpp \ + EmulatedCameraDevice.cpp \ + EmulatedQemuCamera.cpp \ + EmulatedQemuCameraDevice.cpp \ + EmulatedFakeCamera.cpp \ + EmulatedFakeCameraDevice.cpp \ + EmulatedFakeRotatingCameraDevice.cpp \ + Converters.cpp \ + PreviewWindow.cpp \ + CallbackNotifier.cpp \ + QemuClient.cpp \ + JpegCompressor.cpp \ + EmulatedCamera2.cpp \ + EmulatedFakeCamera2.cpp \ + EmulatedQemuCamera2.cpp \ + fake-pipeline2/Scene.cpp \ + fake-pipeline2/Sensor.cpp \ + fake-pipeline2/JpegCompressor.cpp \ + EmulatedCamera3.cpp \ + EmulatedFakeCamera3.cpp \ + EmulatedQemuCamera3.cpp \ + qemu-pipeline3/QemuSensor.cpp \ + Exif.cpp \ + Thumbnail.cpp \ + WorkerThread.cpp \ + + +# Emulated camera - goldfish / vbox_x86 build################################### + +LOCAL_VENDOR_MODULE := true +LOCAL_MODULE_RELATIVE_PATH := ${emulator_camera_module_relative_path} +LOCAL_CFLAGS := ${emulator_camera_cflags} +LOCAL_CLANG_CFLAGS += ${emulator_camera_clang_flags} + +LOCAL_SHARED_LIBRARIES := ${emulator_camera_shared_libraries} +LOCAL_STATIC_LIBRARIES := ${emulator_camera_static_libraries} +LOCAL_C_INCLUDES += ${emulator_camera_c_includes} +LOCAL_SRC_FILES := ${emulator_camera_src} + +ifeq ($(TARGET_BOARD_PLATFORM),brilloemulator) +LOCAL_MODULE := camera.$(TARGET_BOARD_PLATFORM) +else ifeq ($(TARGET_PRODUCT),vbox_x86) +LOCAL_MODULE := camera.vbox_x86 +else +LOCAL_MODULE := camera.goldfish_orig +endif + +include $(BUILD_SHARED_LIBRARY) + +# Emulator camera - ranchu build################################################ + +include ${CLEAR_VARS} + +LOCAL_VENDOR_MODULE := true +LOCAL_MODULE_RELATIVE_PATH := ${emulator_camera_module_relative_path} +LOCAL_CFLAGS := ${emulator_camera_cflags} +LOCAL_CLANG_CFLAGS += ${emulator_camera_clang_flags} + +LOCAL_SHARED_LIBRARIES := ${emulator_camera_shared_libraries} +LOCAL_STATIC_LIBRARIES := ${emulator_camera_static_libraries} +LOCAL_C_INCLUDES += ${emulator_camera_c_includes} +LOCAL_SRC_FILES := ${emulator_camera_src} + +LOCAL_MODULE := camera.ranchu + +include $(BUILD_SHARED_LIBRARY) + +# Build all subdirectories ##################################################### +include $(call all-makefiles-under,$(LOCAL_PATH)) + +endif diff --git a/aosp/external/drm_gralloc/Android.mk b/aosp/external/drm_gralloc/Android.mk new file mode 100644 index 000000000..f6f1adbb4 --- /dev/null +++ b/aosp/external/drm_gralloc/Android.mk @@ -0,0 +1,183 @@ +# Copyright (C) 2010 Chia-I Wu +# Copyright (C) 2010-2011 LunarG Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. + +# Android.mk for drm_gralloc + +DRM_GPU_DRIVERS := $(strip $(filter-out swrast, $(BOARD_GPU_DRIVERS))) + +intel_drivers := i915 i965 i915g ilo +radeon_drivers := r300g r600g +rockchip_drivers := rockchip +nouveau_drivers := nouveau +vmwgfx_drivers := vmwgfx + +valid_drivers := \ + prebuilt \ + $(intel_drivers) \ + $(radeon_drivers) \ + $(rockchip_drivers) \ + $(nouveau_drivers) \ + $(vmwgfx_drivers) + +# warn about invalid drivers +invalid_drivers := $(filter-out $(valid_drivers), $(DRM_GPU_DRIVERS)) +ifneq ($(invalid_drivers),) +$(warning invalid GPU drivers: $(invalid_drivers)) +# tidy up +DRM_GPU_DRIVERS := $(filter-out $(invalid_drivers), $(DRM_GPU_DRIVERS)) +endif + +ifneq ($(filter $(vmwgfx_drivers), $(DRM_GPU_DRIVERS)),) +DRM_USES_PIPE := true +else +DRM_USES_PIPE := false +endif + +ifneq ($(strip $(DRM_GPU_DRIVERS)),) + +LOCAL_PATH := $(call my-dir) + + +# Use the PREBUILT libraries +ifeq ($(strip $(DRM_GPU_DRIVERS)),prebuilt) + +include $(CLEAR_VARS) +LOCAL_MODULE := libgralloc_drm +LOCAL_MODULE_TAGS := optional +LOCAL_SRC_FILES := ../../$(BOARD_GPU_DRIVER_BINARY) +LOCAL_MODULE_CLASS := SHARED_LIBRARIES +LOCAL_MODULE_SUFFIX := $(TARGET_SHLIB_SUFFIX) +include $(BUILD_PREBUILT) + +include $(CLEAR_VARS) +LOCAL_MODULE := gralloc.$(TARGET_PRODUCT)_orig +LOCAL_MODULE_TAGS := optional +LOCAL_MODULE_RELATIVE_PATH := hw +LOCAL_SRC_FILES := ../../$(BOARD_GPU_DRIVER_BINARY) +LOCAL_MODULE_CLASS := SHARED_LIBRARIES +LOCAL_MODULE_SUFFIX := $(TARGET_SHLIB_SUFFIX) +include $(BUILD_PREBUILT) + +# Use the sources +else + +include $(CLEAR_VARS) +LOCAL_MODULE := libgralloc_drm +LOCAL_MODULE_TAGS := optional + +LOCAL_SRC_FILES := \ + gralloc_drm.cpp + +LOCAL_C_INCLUDES := \ + external/libdrm \ + external/libdrm/include/drm + +LOCAL_SHARED_LIBRARIES := \ + libdrm \ + liblog \ + libcutils \ + libhardware_legacy \ + libutils + +ifneq ($(filter $(intel_drivers), $(DRM_GPU_DRIVERS)),) +LOCAL_SRC_FILES += gralloc_drm_intel.c +LOCAL_C_INCLUDES += external/libdrm/intel +LOCAL_CFLAGS += -DENABLE_INTEL +LOCAL_SHARED_LIBRARIES += libdrm_intel +endif + +ifneq ($(filter $(radeon_drivers), $(DRM_GPU_DRIVERS)),) +LOCAL_SRC_FILES += gralloc_drm_radeon.c +LOCAL_C_INCLUDES += external/libdrm/radeon +LOCAL_CFLAGS += -DENABLE_RADEON +LOCAL_SHARED_LIBRARIES += libdrm_radeon +endif + +ifneq ($(filter $(nouveau_drivers), $(DRM_GPU_DRIVERS)),) +LOCAL_SRC_FILES += gralloc_drm_nouveau.c +LOCAL_C_INCLUDES += external/libdrm/nouveau +LOCAL_CFLAGS += -DENABLE_NOUVEAU +LOCAL_SHARED_LIBRARIES += libdrm_nouveau +endif + +ifneq ($(filter $(rockchip_drivers), $(DRM_GPU_DRIVERS)),) +LOCAL_SRC_FILES += gralloc_drm_rockchip.c +LOCAL_CFLAGS += -DENABLE_ROCKCHIP +LOCAL_SHARED_LIBRARIES += libdrm_rockchip +endif + +ifeq ($(strip $(DRM_USES_PIPE)),true) +LOCAL_SRC_FILES += gralloc_drm_pipe.c +LOCAL_CFLAGS += -DENABLE_PIPE +LOCAL_C_INCLUDES += \ + external/mesa/include \ + external/mesa/src/gallium/include \ + external/mesa/src/gallium/winsys \ + external/mesa/src/gallium/drivers \ + external/mesa/src/gallium/auxiliary + +ifneq ($(filter r600g, $(DRM_GPU_DRIVERS)),) +LOCAL_CFLAGS += -DENABLE_PIPE_R600 +LOCAL_STATIC_LIBRARIES += \ + libmesa_pipe_r600 \ + libmesa_pipe_radeon \ + libmesa_winsys_radeon +endif +ifneq ($(filter vmwgfx, $(DRM_GPU_DRIVERS)),) +LOCAL_CFLAGS += -DENABLE_PIPE_VMWGFX +LOCAL_STATIC_LIBRARIES += \ + libmesa_pipe_svga \ + libmesa_winsys_svga +LOCAL_C_INCLUDES += \ + external/mesa/src/gallium/drivers/svga/include +endif + +LOCAL_STATIC_LIBRARIES += \ + libmesa_gallium +LOCAL_SHARED_LIBRARIES += libdl +endif # DRM_USES_PIPE +include $(BUILD_SHARED_LIBRARY) + + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := \ + gralloc.cpp + +LOCAL_C_INCLUDES := \ + external/libdrm \ + external/libdrm/include/drm + +LOCAL_SHARED_LIBRARIES := \ + libgralloc_drm \ + liblog \ + libutils + +# for glFlush/glFinish +LOCAL_SHARED_LIBRARIES += \ + libGLESv1_CM + +LOCAL_MODULE := gralloc.drm +LOCAL_MODULE_TAGS := optional +LOCAL_MODULE_RELATIVE_PATH := hw +include $(BUILD_SHARED_LIBRARY) + +endif # DRM_GPU_DRIVERS=prebuilt +endif # DRM_GPU_DRIVERS diff --git a/aosp/external/libdrm/Android.bp b/aosp/external/libdrm/Android.bp new file mode 100644 index 000000000..f59681574 --- /dev/null +++ b/aosp/external/libdrm/Android.bp @@ -0,0 +1,65 @@ +// +// Copyright © 2011-2012 Intel Corporation +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice (including the next +// paragraph) shall be included in all copies or substantial portions of the +// Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. +// + +subdirs = ["*"] +build = ["Android.sources.bp"] + +cc_defaults { + name: "libdrm_defaults", + cflags: [ + // XXX: Consider moving these to config.h analogous to autoconf. + "-DMAJOR_IN_SYSMACROS=1", + "-DHAVE_VISIBILITY=1", + "-DHAVE_LIBDRM_ATOMIC_PRIMITIVES=1", + + "-Wall", + "-Werror", + "-Wno-deprecated-declarations", + "-Wno-format", + "-Wno-gnu-variable-sized-type-not-at-end", + "-Wno-pointer-arith", + "-Wno-unused-parameter", + "-Wno-unused-variable", + "-Wno-missing-field-initializers", + ], + export_include_dirs: ["."], +} + +// Library for the device +cc_library { + name: "libdrm_orig", + vendor_available: true, + defaults: [ + "libdrm_defaults", + "libdrm_sources", + ], + + export_include_dirs: ["include/drm"], + + cflags: [ + "-Wno-enum-conversion", + "-Wno-pointer-arith", + "-Wno-sign-compare", + "-Wno-tautological-compare", + ], +} diff --git a/aosp/external/libdrm/amdgpu/Android.bp b/aosp/external/libdrm/amdgpu/Android.bp new file mode 100644 index 000000000..f8da0cd0f --- /dev/null +++ b/aosp/external/libdrm/amdgpu/Android.bp @@ -0,0 +1,11 @@ +build = ["Android.sources.bp"] + +cc_library_shared { + name: "libdrm_amdgpu_orig", + defaults: [ + "libdrm_defaults", + "libdrm_amdgpu_sources", + ], + vendor: true, + shared_libs: ["libdrm"], +} diff --git a/aosp/external/libdrm/radeon/Android.bp b/aosp/external/libdrm/radeon/Android.bp new file mode 100644 index 000000000..a0bf4fdab --- /dev/null +++ b/aosp/external/libdrm/radeon/Android.bp @@ -0,0 +1,11 @@ +build = ["Android.sources.bp"] + +cc_library_shared { + name: "libdrm_radeon_orig", + defaults: [ + "libdrm_defaults", + "libdrm_radeon_sources", + ], + vendor: true, + shared_libs: ["libdrm"], +} diff --git a/aosp/external/libjpeg-turbo/Android.bp b/aosp/external/libjpeg-turbo/Android.bp new file mode 100644 index 000000000..46bc337b3 --- /dev/null +++ b/aosp/external/libjpeg-turbo/Android.bp @@ -0,0 +1,235 @@ +// Set up common variables for usage across the libjpeg-turbo modules + +cc_defaults { + name: "libjpeg-defaults", + cflags: [ + "-O3", + "-fstrict-aliasing", + + "-Wno-sign-compare", + "-Wno-unused-parameter", + "-Werror", + ], + srcs: [ + "jcapimin.c", + "jcapistd.c", + "jaricom.c", + "jcarith.c", + "jccoefct.c", + "jccolor.c", + "jcdctmgr.c", + "jchuff.c", + "jcinit.c", + "jcmainct.c", + "jcmarker.c", + "jcmaster.c", + "jcomapi.c", + "jcparam.c", + "jcphuff.c", + "jcprepct.c", + "jcsample.c", + "jctrans.c", + "jdapimin.c", + "jdapistd.c", + "jdarith.c", + "jdatadst.c", + "jdatasrc.c", + "jdcoefct.c", + "jdcolor.c", + "jddctmgr.c", + "jdhuff.c", + "jdinput.c", + "jdmainct.c", + "jdmarker.c", + "jdmaster.c", + "jdmerge.c", + "jdphuff.c", + "jdpostct.c", + "jdsample.c", + "jdtrans.c", + "jerror.c", + "jfdctflt.c", + "jfdctfst.c", + "jfdctint.c", + "jidctflt.c", + "jidctfst.c", + "jidctint.c", + "jidctred.c", + "jmemmgr.c", + "jmemnobs.c", + "jquant1.c", + "jquant2.c", + "jutils.c", + "turbojpeg.c", + "jdatadst-tj.c", + "jdatasrc-tj.c", + "transupp.c", + ], + + arch: { + arm: { + // By default, the build system generates ARM target binaries in + // thumb mode, where each instruction is 16 bits wide. Defining + // this variable as arm forces the build system to generate object + // files in 32-bit arm mode. This is the same setting previously + // used by libjpeg and it provides a small performance benefit. + instruction_set: "arm", + // ARM v7 NEON + srcs: [ + "simd/jsimd_arm_neon.S", + "simd/jsimd_arm.c", + ], + }, + arm64: { + // ARM v8 64-bit NEON + srcs: [ + "simd/jsimd_arm64_neon.S", + "simd/jsimd_arm64.c", + ], + }, + x86: { + // x86 MMX and SSE2 + srcs: [ + "simd/jsimd_i386.c", + "simd/jccolor-mmx.asm", + "simd/jccolor-sse2.asm", + "simd/jcgray-mmx.asm", + "simd/jcgray-sse2.asm", + "simd/jchuff-sse2.asm", + "simd/jcsample-mmx.asm", + "simd/jcsample-sse2.asm", + "simd/jdcolor-mmx.asm", + "simd/jdcolor-sse2.asm", + "simd/jdmerge-mmx.asm", + "simd/jdmerge-sse2.asm", + "simd/jdsample-mmx.asm", + "simd/jdsample-sse2.asm", + "simd/jfdctflt-3dn.asm", + "simd/jfdctflt-sse.asm", + "simd/jfdctfst-mmx.asm", + "simd/jfdctfst-sse2.asm", + "simd/jfdctint-mmx.asm", + "simd/jfdctint-sse2.asm", + "simd/jidctflt-3dn.asm", + "simd/jidctflt-sse2.asm", + "simd/jidctflt-sse.asm", + "simd/jidctfst-mmx.asm", + "simd/jidctfst-sse2.asm", + "simd/jidctint-mmx.asm", + "simd/jidctint-sse2.asm", + "simd/jidctred-mmx.asm", + "simd/jidctred-sse2.asm", + "simd/jquant-3dn.asm", + "simd/jquantf-sse2.asm", + "simd/jquanti-sse2.asm", + "simd/jquant-mmx.asm", + "simd/jquant-sse.asm", + "simd/jsimdcpu.asm", + ], + asflags: [ + "-DPIC", + "-DELF", + ], + local_include_dirs: ["simd"], + }, + x86_64: { + // x86-64 SSE2 + srcs: [ + "simd/jsimd_x86_64.c", + "simd/jccolor-sse2-64.asm", + "simd/jcgray-sse2-64.asm", + "simd/jchuff-sse2-64.asm", + "simd/jcsample-sse2-64.asm", + "simd/jdcolor-sse2-64.asm", + "simd/jdmerge-sse2-64.asm", + "simd/jdsample-sse2-64.asm", + "simd/jfdctflt-sse-64.asm", + "simd/jfdctfst-sse2-64.asm", + "simd/jfdctint-sse2-64.asm", + "simd/jidctflt-sse2-64.asm", + "simd/jidctfst-sse2-64.asm", + "simd/jidctint-sse2-64.asm", + "simd/jidctred-sse2-64.asm", + "simd/jquantf-sse2-64.asm", + "simd/jquanti-sse2-64.asm", + ], + asflags: [ + "-D__x86_64__", + "-DPIC", + "-DELF", + ], + local_include_dirs: ["simd"], + }, + mips: { + srcs: ["jsimd_none.c"], + }, + mips64: { + srcs: ["jsimd_none.c"], + }, + }, +} + +// Also build as a shared library. +cc_library { + name: "libjpeg", + host_supported: true, + vendor_available: true, + target: { + // TODO(b/67474260) Turn this back on + darwin: { + enabled: false, + }, + }, + vndk: { + enabled: true, + }, + defaults: ["libjpeg-defaults"], + export_include_dirs: ["."], +} + +// Build static library against the NDK +cc_library_static { + name: "libjpeg_static_ndk", + defaults: ["libjpeg-defaults"], + export_include_dirs: ["."], + sdk_version: "17", +} + +// Definition for TJBench +cc_binary { + name: "tjbench", + + whole_static_libs: ["libjpeg"], + + multilib: { + lib32: { + stem: "tj32", + }, + lib64: { + stem: "tj64", + }, + }, + + compile_multilib: "both", + + cflags: [ + "-DBMP_SUPPORTED", + "-DPPM_SUPPORTED", + "-Wno-unused-parameter", + "-Werror", + ], + + srcs: [ + "tjbench.c", + "bmp.c", + "tjutil.c", + "rdbmp.c", + "rdppm.c", + "wrbmp.c", + "wrppm.c", + "turbojpeg.c", + "transupp.c", + "jdatadst-tj.c", + "jdatasrc-tj.c", + ], +} diff --git a/aosp/external/libopus/Android.bp b/aosp/external/libopus/Android.bp new file mode 100644 index 000000000..170ee3831 --- /dev/null +++ b/aosp/external/libopus/Android.bp @@ -0,0 +1,331 @@ +cc_library_shared { + name: "libopus_orig", + vendor_available: true, + vndk: { + enabled: true, + }, + + export_include_dirs: ["include"], + + local_include_dirs: [ + "src", + "silk", + "celt", + "silk/fixed", + ], + + srcs: [ + // CELT_SOURCES + "celt/bands.c", + "celt/celt.c", + "celt/celt_encoder.c", + "celt/celt_decoder.c", + "celt/cwrs.c", + "celt/entcode.c", + "celt/entdec.c", + "celt/entenc.c", + "celt/kiss_fft.c", + "celt/laplace.c", + "celt/mathops.c", + "celt/mdct.c", + "celt/modes.c", + "celt/pitch.c", + "celt/celt_lpc.c", + "celt/quant_bands.c", + "celt/rate.c", + "celt/vq.c", + + // SILK_SOURCES + "silk/CNG.c", + "silk/code_signs.c", + "silk/init_decoder.c", + "silk/decode_core.c", + "silk/decode_frame.c", + "silk/decode_parameters.c", + "silk/decode_indices.c", + "silk/decode_pulses.c", + "silk/decoder_set_fs.c", + "silk/dec_API.c", + "silk/enc_API.c", + "silk/encode_indices.c", + "silk/encode_pulses.c", + "silk/gain_quant.c", + "silk/interpolate.c", + "silk/LP_variable_cutoff.c", + "silk/NLSF_decode.c", + "silk/NSQ.c", + "silk/NSQ_del_dec.c", + "silk/PLC.c", + "silk/shell_coder.c", + "silk/tables_gain.c", + "silk/tables_LTP.c", + "silk/tables_NLSF_CB_NB_MB.c", + "silk/tables_NLSF_CB_WB.c", + "silk/tables_other.c", + "silk/tables_pitch_lag.c", + "silk/tables_pulses_per_block.c", + "silk/VAD.c", + "silk/control_audio_bandwidth.c", + "silk/quant_LTP_gains.c", + "silk/VQ_WMat_EC.c", + "silk/HP_variable_cutoff.c", + "silk/NLSF_encode.c", + "silk/NLSF_VQ.c", + "silk/NLSF_unpack.c", + "silk/NLSF_del_dec_quant.c", + "silk/process_NLSFs.c", + "silk/stereo_LR_to_MS.c", + "silk/stereo_MS_to_LR.c", + "silk/check_control_input.c", + "silk/control_SNR.c", + "silk/init_encoder.c", + "silk/control_codec.c", + "silk/A2NLSF.c", + "silk/ana_filt_bank_1.c", + "silk/biquad_alt.c", + "silk/bwexpander_32.c", + "silk/bwexpander.c", + "silk/debug.c", + "silk/decode_pitch.c", + "silk/inner_prod_aligned.c", + "silk/lin2log.c", + "silk/log2lin.c", + "silk/LPC_analysis_filter.c", + "silk/LPC_fit.c", + "silk/LPC_inv_pred_gain.c", + "silk/table_LSF_cos.c", + "silk/NLSF2A.c", + "silk/NLSF_stabilize.c", + "silk/NLSF_VQ_weights_laroia.c", + "silk/pitch_est_tables.c", + "silk/resampler.c", + "silk/resampler_down2_3.c", + "silk/resampler_down2.c", + "silk/resampler_private_AR2.c", + "silk/resampler_private_down_FIR.c", + "silk/resampler_private_IIR_FIR.c", + "silk/resampler_private_up2_HQ.c", + "silk/resampler_rom.c", + "silk/sigm_Q15.c", + "silk/sort.c", + "silk/sum_sqr_shift.c", + "silk/stereo_decode_pred.c", + "silk/stereo_encode_pred.c", + "silk/stereo_find_predictor.c", + "silk/stereo_quant_pred.c", + + // SILK_SOURCES_FIXED + "silk/fixed/LTP_analysis_filter_FIX.c", + "silk/fixed/LTP_scale_ctrl_FIX.c", + "silk/fixed/corrMatrix_FIX.c", + "silk/fixed/encode_frame_FIX.c", + "silk/fixed/find_LPC_FIX.c", + "silk/fixed/find_LTP_FIX.c", + "silk/fixed/find_pitch_lags_FIX.c", + "silk/fixed/find_pred_coefs_FIX.c", + "silk/fixed/noise_shape_analysis_FIX.c", + "silk/fixed/process_gains_FIX.c", + "silk/fixed/regularize_correlations_FIX.c", + "silk/fixed/residual_energy16_FIX.c", + "silk/fixed/residual_energy_FIX.c", + "silk/fixed/warped_autocorrelation_FIX.c", + "silk/fixed/apply_sine_window_FIX.c", + "silk/fixed/autocorr_FIX.c", + "silk/fixed/burg_modified_FIX.c", + "silk/fixed/k2a_FIX.c", + "silk/fixed/k2a_Q16_FIX.c", + "silk/fixed/pitch_analysis_core_FIX.c", + "silk/fixed/vector_ops_FIX.c", + "silk/fixed/schur64_FIX.c", + "silk/fixed/schur_FIX.c", + + // OPUS_SOURCES + "src/opus.c", + "src/opus_decoder.c", + "src/opus_encoder.c", + "src/opus_multistream.c", + "src/opus_multistream_encoder.c", + "src/opus_multistream_decoder.c", + "src/repacketizer.c", + + // OPUS_SOURCES_FLOAT + "src/analysis.c", + "src/mlp.c", + "src/mlp_data.c", + ], + + cflags: [ + "-DNULL=0", + "-DSOCKLEN_T=socklen_t", + "-DLOCALE_NOT_USED", + "-D_LARGEFILE_SOURCE=1", + "-D_FILE_OFFSET_BITS=64", + "-Drestrict=", + "-D__EMX__", + "-DOPUS_BUILD", + "-DFIXED_POINT", + "-DUSE_ALLOCA", + "-DHAVE_LRINT", + "-DHAVE_LRINTF", + "-O2", + "-fno-math-errno", + "-Wall", + "-Werror", + ], + cppflags: [ + "-DBSD=1", + "-ffast-math", + "-O2", + "-funroll-loops", + ], + + arch: { + arm: { + srcs: [ + // CELT_SOURCES_ARM + "celt/arm/armcpu.c", + "celt/arm/arm_celt_map.c", + + // DSP, MEDIA and NEON instructions are in the same assembler + // file - thus we need to include it even if NEON is not + // supported on target platform. + // CELT_SOURCES_ARM_ASM + "celt/arm/celt_pitch_xcorr_arm_gnu.s", + + // CELT_AM_SOURCES_ARM_ASM + "celt/arm/armopts_gnu.s", + ], + + cflags: [ + "-DOPUS_ARM_ASM", + "-DOPUS_ARM_INLINE_ASM", + "-DOPUS_ARM_MAY_HAVE_EDSP", + "-DOPUS_ARM_INLINE_EDSP", + "-DOPUS_ARM_MAY_HAVE_MEDIA", + "-DOPUS_ARM_INLINE_MEDIA", + "-DOPUS_ARM_MAY_HAVE_NEON", + "-DOPUS_HAVE_RTCD", + ], + + // Note: OPUS enhanced DSP/NEON implementation is not yet + // compatible with arm64. Only add the appropriate defines for + // 32-bit arm architecture. + neon: { + srcs: [ + // CELT_SOURCES_ARM_NEON_INTR + "celt/arm/celt_neon_intr.c", + "celt/arm/pitch_neon_intr.c", + + // SILK_SOURCES_ARM_NEON_INTR, + "silk/arm/arm_silk_map.c", + "silk/arm/biquad_alt_neon_intr.c", + "silk/arm/LPC_inv_pred_gain_neon_intr.c", + "silk/arm/NSQ_del_dec_neon_intr.c", + "silk/arm/NSQ_neon.c", + + // SILK_SOURCES_FIXED_ARM_NEON_INTR, + "silk/fixed/arm/warped_autocorrelation_FIX_neon_intr.c", + ], + + cflags: [ + "-DOPUS_ARM_MAY_HAVE_NEON", + "-DOPUS_ARM_MAY_HAVE_NEON_INTR", + "-DOPUS_ARM_PRESUME_NEON", + "-DOPUS_ARM_INLINE_NEON", + ], + }, + + }, + + x86: { + ssse3: { + srcs: [ + // CELT_SOURCES_SSE + "celt/x86/x86cpu.c", + "celt/x86/x86_celt_map.c", + "celt/x86/pitch_sse.c", + + // CELT_SOURCES_SSE2 + "celt/x86/pitch_sse2.c", + "celt/x86/vq_sse2.c", + ], + + cflags: [ + "-DOPUS_X86_MAY_HAVE_SSE", + "-DOPUS_X86_PRESUME_SSE", + "-DOPUS_X86_MAY_HAVE_SSE2", + "-DOPUS_X86_PRESUME_SSE2", + ], + }, + + sse4_1: { + srcs: [ + // CELT_SOURCES_SSE4_1 + "celt/x86/celt_lpc_sse.c", + "celt/x86/pitch_sse4_1.c", + + // SILK_SOURCES_SSE4_1 + "silk/x86/NSQ_sse.c", + "silk/x86/NSQ_del_dec_sse.c", + "silk/x86/x86_silk_map.c", + "silk/x86/VAD_sse.c", + "silk/x86/VQ_WMat_EC_sse.c", + + // SILK_SOURCES_FIXED_SSE4_1 + "silk/fixed/x86/vector_ops_FIX_sse.c", + "silk/fixed/x86/burg_modified_FIX_sse.c", + ], + + cflags: [ + "-DOPUS_X86_MAY_HAVE_SSE4_1", + "-DOPUS_X86_PRESUME_SSE4_1", + ], + }, + }, + + x86_64: { + ssse3: { + srcs: [ + // CELT_SOURCES_SSE + "celt/x86/x86cpu.c", + "celt/x86/x86_celt_map.c", + "celt/x86/pitch_sse.c", + + // CELT_SOURCES_SSE2 + "celt/x86/pitch_sse2.c", + ], + + cflags: [ + "-DOPUS_X86_MAY_HAVE_SSE", + "-DOPUS_X86_PRESUME_SSE", + "-DOPUS_X86_MAY_HAVE_SSE2", + "-DOPUS_X86_PRESUME_SSE2", + ], + }, + + sse4_1: { + srcs: [ + // CELT_SOURCES_SSE4_1 + "celt/x86/celt_lpc_sse.c", + "celt/x86/pitch_sse4_1.c", + + // SILK_SOURCES_SSE4_1 + "silk/x86/NSQ_sse.c", + "silk/x86/NSQ_del_dec_sse.c", + "silk/x86/x86_silk_map.c", + "silk/x86/VAD_sse.c", + "silk/x86/VQ_WMat_EC_sse.c", + + // SILK_SOURCES_FIXED_SSE4_1 + "silk/fixed/x86/vector_ops_FIX_sse.c", + "silk/fixed/x86/burg_modified_FIX_sse.c", + ], + + cflags: [ + "-DOPUS_X86_MAY_HAVE_SSE4_1", + "-DOPUS_X86_PRESUME_SSE4_1", + ], + }, + }, + }, +} diff --git a/aosp/external/mesa3d/src/egl/Android.mk b/aosp/external/mesa3d/src/egl/Android.mk new file mode 100644 index 000000000..1644f8558 --- /dev/null +++ b/aosp/external/mesa3d/src/egl/Android.mk @@ -0,0 +1,75 @@ +# Mesa 3-D graphics library +# +# Copyright (C) 2010-2011 Chia-I Wu +# Copyright (C) 2010-2011 LunarG Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. + +# Android.mk for libGLES_mesa + +LOCAL_PATH := $(call my-dir) + +include $(LOCAL_PATH)/Makefile.sources + +# --------------------------------------- +# Build libGLES_mesa +# --------------------------------------- + +include $(CLEAR_VARS) + +LOCAL_SRC_FILES := \ + $(LIBEGL_C_FILES) \ + $(dri2_backend_core_FILES) \ + drivers/dri2/platform_android.c + +LOCAL_CFLAGS := \ + -D_EGL_NATIVE_PLATFORM=_EGL_PLATFORM_ANDROID \ + -D_EGL_BUILT_IN_DRIVER_DRI2 \ + -DHAVE_ANDROID_PLATFORM + +LOCAL_C_INCLUDES := \ + $(MESA_TOP)/src/egl/main \ + $(MESA_TOP)/src/egl/drivers/dri2 \ + +LOCAL_STATIC_LIBRARIES := \ + libmesa_loader + +LOCAL_SHARED_LIBRARIES := \ + libdl \ + libhardware \ + liblog \ + libcutils \ + libsync + +ifeq ($(strip $(MESA_BUILD_CLASSIC)),true) +# require i915_dri and/or i965_dri +LOCAL_REQUIRED_MODULES += \ + $(addsuffix _dri, $(filter i915 i965, $(MESA_GPU_DRIVERS))) +endif # MESA_BUILD_CLASSIC + +ifeq ($(strip $(MESA_BUILD_GALLIUM)),true) +LOCAL_REQUIRED_MODULES += gallium_dri +endif # MESA_BUILD_GALLIUM + + +LOCAL_MODULE := libGLES_mesa_orig +LOCAL_MODULE_RELATIVE_PATH := egl + +include $(MESA_COMMON_MK) +include $(BUILD_SHARED_LIBRARY) diff --git a/aosp/external/mesa3d/src/gallium/targets/dri/Android.mk b/aosp/external/mesa3d/src/gallium/targets/dri/Android.mk new file mode 100644 index 000000000..222a4e5c3 --- /dev/null +++ b/aosp/external/mesa3d/src/gallium/targets/dri/Android.mk @@ -0,0 +1,124 @@ +# Mesa 3-D graphics library +# +# Copyright (C) 2015 Chih-Wei Huang +# Copyright (C) 2015 Android-x86 Open Source Project +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. + +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) + +LOCAL_MODULE := gallium_dri_orig + +LOCAL_MODULE_RELATIVE_PATH := $(MESA_DRI_MODULE_REL_PATH) +LOCAL_SRC_FILES := target.c + +LOCAL_CFLAGS := + +LOCAL_SHARED_LIBRARIES := \ + libdl \ + libglapi \ + libexpat \ + +ifneq ($(filter freedreno,$(MESA_GPU_DRIVERS)),) +LOCAL_CFLAGS += -DGALLIUM_FREEDRENO +gallium_DRIVERS += libmesa_winsys_freedreno libmesa_pipe_freedreno +LOCAL_SHARED_LIBRARIES += libdrm_freedreno +endif +ifneq ($(filter i915g,$(MESA_GPU_DRIVERS)),) +gallium_DRIVERS += libmesa_winsys_i915 libmesa_pipe_i915 +LOCAL_SHARED_LIBRARIES += libdrm_intel +LOCAL_CFLAGS += -DGALLIUM_I915 +endif +ifneq ($(filter ilo,$(MESA_GPU_DRIVERS)),) +gallium_DRIVERS += libmesa_winsys_intel libmesa_pipe_ilo +LOCAL_SHARED_LIBRARIES += libdrm_intel +LOCAL_CFLAGS += -DGALLIUM_ILO +endif +ifneq ($(filter nouveau,$(MESA_GPU_DRIVERS)),) +gallium_DRIVERS += libmesa_winsys_nouveau libmesa_pipe_nouveau +LOCAL_CFLAGS += -DGALLIUM_NOUVEAU +LOCAL_SHARED_LIBRARIES += libdrm_nouveau +endif +ifneq ($(filter r%,$(MESA_GPU_DRIVERS)),) +ifneq ($(filter r300g,$(MESA_GPU_DRIVERS)),) +gallium_DRIVERS += libmesa_pipe_r300 +LOCAL_CFLAGS += -DGALLIUM_R300 +endif +ifneq ($(filter r600g,$(MESA_GPU_DRIVERS)),) +gallium_DRIVERS += libmesa_pipe_r600 +LOCAL_CFLAGS += -DGALLIUM_R600 +endif +ifneq ($(filter radeonsi,$(MESA_GPU_DRIVERS)),) +gallium_DRIVERS += libmesa_pipe_radeonsi libmesa_winsys_amdgpu libmesa_amd_common +LOCAL_SHARED_LIBRARIES += libLLVM libdrm_amdgpu +LOCAL_CFLAGS += -DGALLIUM_RADEONSI +endif +gallium_DRIVERS += libmesa_winsys_radeon libmesa_pipe_radeon libmesa_amdgpu_addrlib +LOCAL_SHARED_LIBRARIES += libdrm_radeon +endif +ifneq ($(filter swrast,$(MESA_GPU_DRIVERS)),) +gallium_DRIVERS += libmesa_pipe_softpipe libmesa_winsys_sw_dri +LOCAL_CFLAGS += -DGALLIUM_SOFTPIPE +endif +ifneq ($(filter vc4,$(MESA_GPU_DRIVERS)),) +LOCAL_CFLAGS += -DGALLIUM_VC4 +gallium_DRIVERS += libmesa_winsys_vc4 libmesa_pipe_vc4 +endif +ifneq ($(filter virgl,$(MESA_GPU_DRIVERS)),) +LOCAL_CFLAGS += -DGALLIUM_VIRGL +gallium_DRIVERS += libmesa_winsys_virgl libmesa_winsys_virgl_vtest libmesa_pipe_virgl +endif +ifneq ($(filter vmwgfx,$(MESA_GPU_DRIVERS)),) +gallium_DRIVERS += libmesa_winsys_svga libmesa_pipe_svga +LOCAL_CFLAGS += -DGALLIUM_VMWGFX +endif +ifneq ($(filter nouveau r600g,$(MESA_GPU_DRIVERS)),) +LOCAL_SHARED_LIBRARIES += libc++ +endif + +LOCAL_WHOLE_STATIC_LIBRARIES := \ + $(gallium_DRIVERS) \ + libmesa_st_dri \ + libmesa_st_mesa \ + libmesa_glsl \ + libmesa_compiler \ + libmesa_nir \ + libmesa_dri_common \ + libmesa_megadriver_stub \ + libmesa_gallium \ + libmesa_pipe_loader \ + libmesa_util \ + libmesa_loader \ + +LOCAL_STATIC_LIBRARIES := + +ifeq ($(MESA_ENABLE_LLVM),true) +LOCAL_STATIC_LIBRARIES += \ + libLLVMR600CodeGen \ + libLLVMR600Desc \ + libLLVMR600Info \ + libLLVMR600AsmPrinter \ + libelf +LOCAL_LDLIBS += -lgcc +endif + +include $(GALLIUM_COMMON_MK) +#include $(BUILD_SHARED_LIBRARY) diff --git a/aosp/external/mesa3d/src/gbm/Android.mk b/aosp/external/mesa3d/src/gbm/Android.mk new file mode 100644 index 000000000..c0afd597c --- /dev/null +++ b/aosp/external/mesa3d/src/gbm/Android.mk @@ -0,0 +1,43 @@ +# +# Copyright (C) 2016 Linaro, Ltd., Rob Herring +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. +# + +LOCAL_PATH := $(call my-dir) + +include $(LOCAL_PATH)/Makefile.sources + +include $(CLEAR_VARS) + +LOCAL_EXPORT_C_INCLUDE_DIRS := \ + $(LOCAL_PATH)/main + +LOCAL_C_INCLUDES := \ + $(LOCAL_PATH)/main + +LOCAL_STATIC_LIBRARIES := libmesa_loader +LOCAL_MODULE := libgbm_orig + +LOCAL_SRC_FILES := \ + $(gbm_core_FILES) \ + $(gbm_dri_FILES) + +include $(MESA_COMMON_MK) +include $(BUILD_SHARED_LIBRARY) diff --git a/aosp/external/mesa3d/src/mapi/Android.mk b/aosp/external/mesa3d/src/mapi/Android.mk new file mode 100644 index 000000000..9cef9c2e8 --- /dev/null +++ b/aosp/external/mesa3d/src/mapi/Android.mk @@ -0,0 +1,78 @@ +# Mesa 3-D graphics library +# +# Copyright (C) 2010-2011 Chia-I Wu +# Copyright (C) 2010-2011 LunarG Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. + +# Android.mk for glapi + +LOCAL_PATH := $(call my-dir) + +mapi_abi_headers := + +# --------------------------------------- +# Build libglapi +# --------------------------------------- + +include $(CLEAR_VARS) + +abi_header := shared-glapi/glapi_mapi_tmp.h + +LOCAL_SRC_FILES := \ + entry.c \ + mapi_glapi.c \ + stub.c \ + table.c \ + u_current.c \ + u_execmem.c + +LOCAL_CFLAGS := \ + -DMAPI_MODE_GLAPI \ + -DMAPI_ABI_HEADER=\"$(abi_header)\" + +LOCAL_C_INCLUDES := \ + $(MESA_TOP)/src/mapi + +LOCAL_MODULE := libglapi_orig + +LOCAL_MODULE_CLASS := SHARED_LIBRARIES +intermediates := $(call local-generated-sources-dir) +abi_header := $(intermediates)/$(abi_header) +LOCAL_GENERATED_SOURCES := $(abi_header) + +$(abi_header): PRIVATE_PRINTER := shared-glapi + +mapi_abi_headers += $(abi_header) + +include $(MESA_COMMON_MK) +include $(BUILD_SHARED_LIBRARY) + + +mapi_abi_deps := \ + $(wildcard $(LOCAL_PATH)/glapi/gen/*.py) \ + $(wildcard $(LOCAL_PATH)/glapi/gen/*.xml) \ + $(LOCAL_PATH)/mapi_abi.py + +$(mapi_abi_headers): PRIVATE_SCRIPT := $(MESA_PYTHON2) $(LOCAL_PATH)/mapi_abi.py +$(mapi_abi_headers): PRIVATE_APIXML := $(LOCAL_PATH)/glapi/gen/gl_and_es_API.xml +$(mapi_abi_headers): $(mapi_abi_deps) + @mkdir -p $(dir $@) + @echo "target $(PRIVATE_PRINTER): $(PRIVATE_MODULE) <= $(PRIVATE_APIXML)" + $(hide) $(PRIVATE_SCRIPT) --printer $(PRIVATE_PRINTER) --mode lib $(PRIVATE_APIXML) > $@ diff --git a/aosp/external/mtpd/Android.bp b/aosp/external/mtpd/Android.bp new file mode 100644 index 000000000..f298afa5a --- /dev/null +++ b/aosp/external/mtpd/Android.bp @@ -0,0 +1,34 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +cc_binary { + name: "mtpd_orig", + srcs: [ + "mtpd.c", + "l2tp.c", + "pptp.c" + ], + shared_libs: [ + "libcrypto", + "libcutils", + "liblog", + "libnetd_client", + ], + cflags: [ + "-DANDROID_CHANGES", + "-Wall", + "-Werror", + ], + init_rc: ["mtpd.rc"], +} diff --git a/aosp/external/noto-fonts/Android.mk b/aosp/external/noto-fonts/Android.mk new file mode 100644 index 000000000..059373687 --- /dev/null +++ b/aosp/external/noto-fonts/Android.mk @@ -0,0 +1,348 @@ +# Copyright (C) 2013 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +NOTO_DIR := $(call my-dir) + +include $(call all-makefiles-under,$(NOTO_DIR)) + +# We have to use BUILD_PREBUILT instead of PRODUCT_COPY_FILES, +# to copy over the NOTICE file. +############################################################################# +# $(1): The source file name in LOCAL_PATH. +# It also serves as the module name and the dest file name. +############################################################################# +define build-one-font-module +$(eval include $(CLEAR_VARS))\ +$(eval LOCAL_MODULE := $(1))\ +$(eval LOCAL_SRC_FILES := $(1))\ +$(eval LOCAL_MODULE_CLASS := ETC)\ +$(eval LOCAL_MODULE_TAGS := optional)\ +$(eval LOCAL_MODULE_PATH := $(TARGET_OUT)/fonts)\ +$(eval include $(BUILD_PREBUILT)) +endef + + +############################################################################# +# First "build" the Noto CJK fonts, which have a different directory and +# copyright holder. These are not included in MINIMAL_FONT_FOOTPRINT builds. +############################################################################# +ifneq ($(MINIMAL_FONT_FOOTPRINT),true) +LOCAL_PATH := $(NOTO_DIR)/cjk + +font_src_files := \ + NotoSansCJK-Regular.ttc + +$(foreach f, $(font_src_files), $(call build-one-font-module, $(f))) +font_src_files := + +endif # !MINIMAL_FONT_FOOTPRINT + +############################################################################# +# Similary "build" the Noto CJK fonts for serif family. +# These are not included in SMALLER_FONT_FOOTPRINT builds. +############################################################################# +ifeq ($(filter true,$(EXCLUDE_SERIF_FONTS) $(SMALLER_FONT_FOOTPRINT)),) +LOCAL_PATH := $(NOTO_DIR)/cjk + +font_src_files := \ + NotoSerifCJK-Regular.ttc + +$(foreach f, $(font_src_files), $(call build-one-font-module, $(f))) +font_src_files := + +endif # !EXCLUDE_SERIF_FONTS && !SMALLER_FONT_FOOTPRINT + +############################################################################# +# Now "build" the Noto Color Emoji font, which is in its own directory. It is +# not included in the MINIMAL_FONT_FOOTPRINT builds. +############################################################################# +ifneq ($(MINIMAL_FONT_FOOTPRINT),true) +LOCAL_PATH := $(NOTO_DIR)/emoji + +font_src_files := \ + NotoColorEmoji.ttf + +$(foreach f, $(font_src_files), $(call build-one-font-module, $(f))) +font_src_files := + +endif # !MINIMAL_FONT_FOOTPRINT + +############################################################################# +# Now "build" the rest of the fonts, which live in a separate subdirectory. +############################################################################# +LOCAL_PATH := $(NOTO_DIR)/other + +############################################################################# +# The following fonts are included in all builds. +############################################################################# +font_src_files := \ + NotoSerif-Regular.ttf \ + NotoSerif-Bold.ttf \ + NotoSerif-Italic.ttf \ + NotoSerif-BoldItalic.ttf + +############################################################################# +# The following fonts are excluded from SMALLER_FONT_FOOTPRINT builds. +############################################################################# +ifneq ($(SMALLER_FONT_FOOTPRINT),true) +font_src_files += \ + NotoKufiArabic-Bold.ttf \ + NotoKufiArabic-Regular.ttf \ + NotoNastaliqUrdu-Regular.ttf \ + NotoSansAdlam-Regular.ttf \ + NotoSansAdlamUnjoined-Regular.ttf \ + NotoSansAhom-Regular.otf \ + NotoSansAnatolianHieroglyphs-Regular.otf \ + NotoSansAvestan-Regular.ttf \ + NotoSansBalinese-Regular.ttf \ + NotoSansBamum-Regular.ttf \ + NotoSansBassaVah-Regular.otf \ + NotoSansBatak-Regular.ttf \ + NotoSansBengali-Bold.ttf \ + NotoSansBengali-Regular.ttf \ + NotoSansBengaliUI-Bold.ttf \ + NotoSansBengaliUI-Regular.ttf \ + NotoSansBhaiksuki-Regular.otf \ + NotoSans-Bold.ttf \ + NotoSans-BoldItalic.ttf \ + NotoSansBrahmi-Regular.ttf \ + NotoSansBuginese-Regular.ttf \ + NotoSansBuhid-Regular.ttf \ + NotoSansCanadianAboriginal-Regular.ttf \ + NotoSansCarian-Regular.ttf \ + NotoSansChakma-Regular.ttf \ + NotoSansCham-Bold.ttf \ + NotoSansCham-Regular.ttf \ + NotoSansCherokee-Regular.ttf \ + NotoSansCoptic-Regular.ttf \ + NotoSansCuneiform-Regular.ttf \ + NotoSansCypriot-Regular.ttf \ + NotoSansDeseret-Regular.ttf \ + NotoSansEgyptianHieroglyphs-Regular.ttf \ + NotoSansElbasan-Regular.otf \ + NotoSansEthiopic-Bold.ttf \ + NotoSansEthiopic-Regular.ttf \ + NotoSansGlagolitic-Regular.ttf \ + NotoSansGothic-Regular.ttf \ + NotoSansGujarati-Bold.ttf \ + NotoSansGujarati-Regular.ttf \ + NotoSansGujaratiUI-Bold.ttf \ + NotoSansGujaratiUI-Regular.ttf \ + NotoSansGurmukhi-Bold.ttf \ + NotoSansGurmukhi-Regular.ttf \ + NotoSansGurmukhiUI-Bold.ttf \ + NotoSansGurmukhiUI-Regular.ttf \ + NotoSansHanunoo-Regular.ttf \ + NotoSansHatran-Regular.otf \ + NotoSansImperialAramaic-Regular.ttf \ + NotoSansInscriptionalPahlavi-Regular.ttf \ + NotoSansInscriptionalParthian-Regular.ttf \ + NotoSans-Italic.ttf \ + NotoSansJavanese-Regular.ttf \ + NotoSansKaithi-Regular.ttf \ + NotoSansKannada-Bold.ttf \ + NotoSansKannada-Regular.ttf \ + NotoSansKannadaUI-Bold.ttf \ + NotoSansKannadaUI-Regular.ttf \ + NotoSansKayahLi-Regular.ttf \ + NotoSansKharoshthi-Regular.ttf \ + NotoSansKhmerUI-Bold.ttf \ + NotoSansKhmerUI-Regular.ttf \ + NotoSansLao-Bold.ttf \ + NotoSansLao-Regular.ttf \ + NotoSansLaoUI-Bold.ttf \ + NotoSansLaoUI-Regular.ttf \ + NotoSansLepcha-Regular.ttf \ + NotoSansLimbu-Regular.ttf \ + NotoSansLinearA-Regular.otf \ + NotoSansLinearB-Regular.ttf \ + NotoSansLisu-Regular.ttf \ + NotoSansLycian-Regular.ttf \ + NotoSansLydian-Regular.ttf \ + NotoSansMalayalam-Bold.ttf \ + NotoSansMalayalam-Regular.ttf \ + NotoSansMalayalamUI-Bold.ttf \ + NotoSansMalayalamUI-Regular.ttf \ + NotoSansMandaic-Regular.ttf \ + NotoSansManichaean-Regular.otf \ + NotoSansMarchen-Regular.otf \ + NotoSansMeeteiMayek-Regular.ttf \ + NotoSansMeroitic-Regular.otf \ + NotoSansMiao-Regular.otf \ + NotoSansMongolian-Regular.ttf \ + NotoSansMro-Regular.otf \ + NotoSansMultani-Regular.otf \ + NotoSansMyanmar-Bold.ttf \ + NotoSansMyanmar-Regular.ttf \ + NotoSansMyanmarUI-Bold.ttf \ + NotoSansMyanmarUI-Regular.ttf \ + NotoSansNabataean-Regular.otf \ + NotoSansNewa-Regular.otf \ + NotoSansNewTaiLue-Regular.ttf \ + NotoSansNKo-Regular.ttf \ + NotoSansOgham-Regular.ttf \ + NotoSansOlChiki-Regular.ttf \ + NotoSansOldItalic-Regular.ttf \ + NotoSansOldNorthArabian-Regular.otf \ + NotoSansOldPermic-Regular.otf \ + NotoSansOldPersian-Regular.ttf \ + NotoSansOldSouthArabian-Regular.ttf \ + NotoSansOldTurkic-Regular.ttf \ + NotoSansOriya-Bold.ttf \ + NotoSansOriya-Regular.ttf \ + NotoSansOriyaUI-Bold.ttf \ + NotoSansOriyaUI-Regular.ttf \ + NotoSansOsage-Regular.ttf \ + NotoSansOsmanya-Regular.ttf \ + NotoSansPahawhHmong-Regular.otf \ + NotoSansPalmyrene-Regular.otf \ + NotoSansPauCinHau-Regular.otf \ + NotoSansPhagsPa-Regular.ttf \ + NotoSansPhoenician-Regular.ttf \ + NotoSans-Regular.ttf \ + NotoSansRejang-Regular.ttf \ + NotoSansRunic-Regular.ttf \ + NotoSansSamaritan-Regular.ttf \ + NotoSansSaurashtra-Regular.ttf \ + NotoSansSharada-Regular.otf \ + NotoSansShavian-Regular.ttf \ + NotoSansSinhala-Bold.ttf \ + NotoSansSinhala-Regular.ttf \ + NotoSansSinhalaUI-Bold.otf \ + NotoSansSinhalaUI-Regular.otf \ + NotoSansSoraSompeng-Regular.otf \ + NotoSansSundanese-Regular.ttf \ + NotoSansSylotiNagri-Regular.ttf \ + NotoSansSymbols-Regular.ttf \ + NotoSansSyriacEastern-Regular.ttf \ + NotoSansSyriacEstrangela-Regular.ttf \ + NotoSansSyriacWestern-Regular.ttf \ + NotoSansTagalog-Regular.ttf \ + NotoSansTagbanwa-Regular.ttf \ + NotoSansTaiLe-Regular.ttf \ + NotoSansTaiTham-Regular.ttf \ + NotoSansTaiViet-Regular.ttf \ + NotoSansTamil-Bold.ttf \ + NotoSansTamil-Regular.ttf \ + NotoSansTamilUI-Bold.ttf \ + NotoSansTamilUI-Regular.ttf \ + NotoSansTelugu-Bold.ttf \ + NotoSansTelugu-Regular.ttf \ + NotoSansTeluguUI-Bold.ttf \ + NotoSansTeluguUI-Regular.ttf \ + NotoSansThaana-Bold.ttf \ + NotoSansThaana-Regular.ttf \ + NotoSansTibetan-Bold.ttf \ + NotoSansTibetan-Regular.ttf \ + NotoSansTifinagh-Regular.ttf \ + NotoSansUgaritic-Regular.ttf \ + NotoSansUI-Bold.ttf \ + NotoSansUI-BoldItalic.ttf \ + NotoSansUI-Italic.ttf \ + NotoSansUI-Regular.ttf \ + NotoSansVai-Regular.ttf \ + NotoSansYi-Regular.ttf +endif # !SMALLER_FONT_FOOTPRINT + +############################################################################# +# The following fonts are excluded from MINIMAL_FONT_FOOTPRINT builds. +############################################################################# +ifneq ($(MINIMAL_FONT_FOOTPRINT),true) +font_src_files += \ + NotoNaskhArabic-Regular.ttf \ + NotoNaskhArabic-Bold.ttf \ + NotoNaskhArabicUI-Regular.ttf \ + NotoNaskhArabicUI-Bold.ttf \ + NotoSansArmenian-Regular.ttf \ + NotoSansArmenian-Bold.ttf \ + NotoSansDevanagari-Regular.ttf \ + NotoSansDevanagari-Bold.ttf \ + NotoSansDevanagariUI-Regular.ttf \ + NotoSansDevanagariUI-Bold.ttf \ + NotoSansGeorgian-Regular.ttf \ + NotoSansGeorgian-Bold.ttf \ + NotoSansHebrew-Regular.ttf \ + NotoSansHebrew-Bold.ttf \ + NotoSansSymbols-Regular-Subsetted.ttf \ + NotoSansSymbols-Regular-Subsetted2.ttf \ + NotoSansThai-Regular.ttf \ + NotoSansThai-Bold.ttf \ + NotoSansThaiUI-Regular.ttf \ + NotoSansThaiUI-Bold.ttf +endif # !MINIMAL_FONT_FOOTPRINT + +ifeq ($(filter true,$(EXCLUDE_SERIF_FONTS) $(SMALLER_FONT_FOOTPRINT)),) +font_src_files += \ + NotoSerifArmenian-Bold.ttf \ + NotoSerifArmenian-Regular.ttf \ + NotoSerifBengali-Bold.ttf \ + NotoSerifBengali-Regular.ttf \ + NotoSerifDevanagari-Bold.ttf \ + NotoSerifDevanagari-Regular.ttf \ + NotoSerifEthiopic-Bold.otf \ + NotoSerifEthiopic-Regular.otf \ + NotoSerifGeorgian-Bold.ttf \ + NotoSerifGeorgian-Regular.ttf \ + NotoSerifGujarati-Bold.ttf \ + NotoSerifGujarati-Regular.ttf \ + NotoSerifGurmukhi-Bold.otf \ + NotoSerifGurmukhi-Regular.otf \ + NotoSerifHebrew-Bold.ttf \ + NotoSerifHebrew-Regular.ttf \ + NotoSerifKannada-Bold.ttf \ + NotoSerifKannada-Regular.ttf \ + NotoSerifKhmer-Bold.otf \ + NotoSerifKhmer-Regular.otf \ + NotoSerifLao-Bold.ttf \ + NotoSerifLao-Regular.ttf \ + NotoSerifMalayalam-Bold.ttf \ + NotoSerifMalayalam-Regular.ttf \ + NotoSerifMyanmar-Bold.otf \ + NotoSerifMyanmar-Regular.otf \ + NotoSerifSinhala-Bold.otf \ + NotoSerifSinhala-Regular.otf \ + NotoSerifTamil-Bold.ttf \ + NotoSerifTamil-Regular.ttf \ + NotoSerifTelugu-Bold.ttf \ + NotoSerifTelugu-Regular.ttf \ + NotoSerifThai-Bold.ttf \ + NotoSerifThai-Regular.ttf +endif # !EXCLUDE_SERIF_FONTS && !SMALLER_FONT_FOOTPRINT + +$(foreach f, $(font_src_files), $(call build-one-font-module, $(f))) + +############################################################################# +# Now "build" the variable fonts, which live in a separate subdirectory. +# The only variable fonts are for Khmer Sans, which is excluded in +# SMALLER_FONT_FOOTPRINT build. +############################################################################# + +ifneq ($(SMALLER_FONT_FOOTPRINT),true) + +LOCAL_PATH := $(NOTO_DIR)/other-vf + +font_src_files := \ + NotoSansKhmer-VF.ttf + +$(foreach f, $(font_src_files), $(call build-one-font-module, $(f))) + +endif # !SMALLER_FONT_FOOTPRINT + +NOTO_DIR := +build-one-font-module := +font_src_files := + + + + diff --git a/aosp/external/ppp/pppd/Android.mk b/aosp/external/ppp/pppd/Android.mk new file mode 100644 index 000000000..caf721b51 --- /dev/null +++ b/aosp/external/ppp/pppd/Android.mk @@ -0,0 +1,46 @@ +LOCAL_PATH:= $(call my-dir) +include $(CLEAR_VARS) + +LOCAL_SRC_FILES:= \ + auth.c \ + ccp.c \ + chap-md5.c \ + chap-new.c \ + chap_ms.c \ + demand.c \ + eap.c \ + ecp.c \ + eui64.c \ + fsm.c \ + ipcp.c \ + ipv6cp.c \ + lcp.c \ + magic.c \ + main.c \ + options.c \ + pppcrypt.c \ + pppox.c \ + session.c \ + sys-linux.c \ + tty.c \ + upap.c \ + utils.c + +# options.c:623:21: error: passing 'const char *' to parameter of type 'char *' discards qualifiers. +# [-Werror,-Wincompatible-pointer-types-discards-qualifiers] +LOCAL_CLANG_CFLAGS += -Wno-incompatible-pointer-types-discards-qualifiers + +LOCAL_SHARED_LIBRARIES := \ + libcutils liblog libcrypto + +LOCAL_C_INCLUDES := \ + $(LOCAL_PATH)/include + +LOCAL_CFLAGS := -DCHAPMS=1 -DMPPE=1 -DINET6=1 -DUSE_OPENSSL=1 -Wno-unused-parameter -Wno-empty-body -Wno-missing-field-initializers -Wno-attributes -Wno-sign-compare -Wno-pointer-sign -Werror + +# Turn off warnings for now until this is fixed upstream. b/18632512 +LOCAL_CFLAGS += -Wno-unused-variable + +LOCAL_MODULE:= pppd_orig + +include $(BUILD_EXECUTABLE) diff --git a/aosp/external/toybox/Android.mk b/aosp/external/toybox/Android.mk index 3e00e4c00..71e036e2d 100644 --- a/aosp/external/toybox/Android.mk +++ b/aosp/external/toybox/Android.mk @@ -402,7 +402,7 @@ ALL_TOOLS := \ ############################################ include $(CLEAR_VARS) -LOCAL_MODULE := toybox +LOCAL_MODULE := toybox_orig LOCAL_SRC_FILES := $(common_SRC_FILES) LOCAL_CFLAGS := $(common_CFLAGS) LOCAL_SHARED_LIBRARIES := $(toybox_libraries) @@ -417,7 +417,7 @@ include $(BUILD_EXECUTABLE) ############################################ include $(CLEAR_VARS) -LOCAL_MODULE := toybox_vendor +LOCAL_MODULE := toybox_vendor_orig LOCAL_VENDOR_MODULE := true LOCAL_SRC_FILES := $(common_SRC_FILES) LOCAL_CFLAGS := $(common_CFLAGS) diff --git a/aosp/hardware/akm/AK8975_FS/libsensors/Android.mk b/aosp/hardware/akm/AK8975_FS/libsensors/Android.mk new file mode 100644 index 000000000..325db8324 --- /dev/null +++ b/aosp/hardware/akm/AK8975_FS/libsensors/Android.mk @@ -0,0 +1,45 @@ +# Copyright (C) 2008 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +LOCAL_PATH := $(call my-dir) + +# HAL module implemenation, not prelinked, and stored in +# hw/..so +include $(CLEAR_VARS) + +LOCAL_MODULE := sensors_ori.default + +LOCAL_MODULE_RELATIVE_PATH := hw + +LOCAL_MODULE_TAGS := optional + +LOCAL_CFLAGS := -DLOG_TAG=\"Sensors\" \ + -Wall \ + -Werror \ + -Wno-unused-parameter \ + -DSENSORHAL_ACC_ADXL346 +# -DSENSORHAL_ACC_KXTF9 + +LOCAL_SRC_FILES := \ + SensorBase.cpp \ + InputEventReader.cpp \ + AkmSensor.cpp \ + sensors.cpp \ + AdxlSensor.cpp +# KionixSensor.cpp + +LOCAL_SHARED_LIBRARIES := liblog libcutils libdl + +include $(BUILD_SHARED_LIBRARY) diff --git a/aosp/prebuilts/sdk/current/support/v7/preference/res/values-zh-rCN/values-zh-rCN.xml b/aosp/prebuilts/sdk/current/support/v7/preference/res/values-zh-rCN/values-zh-rCN.xml new file mode 100644 index 000000000..76a412363 --- /dev/null +++ b/aosp/prebuilts/sdk/current/support/v7/preference/res/values-zh-rCN/values-zh-rCN.xml @@ -0,0 +1,7 @@ + + + "高级" + "%1$s%2$s" + "关闭" + "开启" + \ No newline at end of file diff --git a/aosp/system/bt/main/Android.bp b/aosp/system/bt/main/Android.bp new file mode 100644 index 000000000..5c6b6be8f --- /dev/null +++ b/aosp/system/bt/main/Android.bp @@ -0,0 +1,123 @@ + +// Bluetooth main HW module / shared library for target +// ======================================================== +cc_library_shared { + name: "libbluetooth_orig", + defaults: ["fluoride_defaults"], + header_libs: ["libbluetooth_headers"], + export_header_lib_headers: ["libbluetooth_headers"], + srcs: [ + // platform specific + "bte_conf.cc", + "bte_init.cc", + "bte_init_cpp_logging.cc", + "bte_logmsg.cc", + "bte_main.cc", + "stack_config.cc", + ], + include_dirs: [ + "system/bt", + "system/bt/bta/include", + "system/bt/bta/sys", + "system/bt/bta/dm", + "system/bt/btcore/include", + "system/bt/internal_include", + "system/bt/stack/include", + "system/bt/stack/l2cap", + "system/bt/stack/a2dp", + "system/bt/stack/btm", + "system/bt/stack/avdt", + "system/bt/udrv/include", + "system/bt/btif/include", + "system/bt/btif/co", + "system/bt/hci/include", + "system/bt/vnd/include", + "system/bt/embdrv/sbc/encoder/include", + "system/bt/embdrv/sbc/decoder/include", + "system/bt/utils/include", + ], + logtags: ["../EventLogTags.logtags"], + shared_libs: [ + "android.hardware.bluetooth@1.0", + "android.hardware.bluetooth.a2dp@1.0", + "libaudioclient", + "libcutils", + "libdl", + "libhidlbase", + "libhidltransport", + "libhwbinder", + "liblog", + "libprotobuf-cpp-lite", + "libutils", + "libtinyxml2", + "libz", + "libcrypto", + "android.hardware.keymaster@4.0", + "android.hardware.keymaster@3.0", + "libkeymaster4support", + "libkeystore_aidl", + "libkeystore_binder", + "libkeystore_parcelables", + "libstatslog", + ], + static_libs: [ + "libbt-sbc-decoder", + "libbt-sbc-encoder", + "libFraunhoferAAC", + "libg722codec", + "libudrv-uipc", + ], + whole_static_libs: [ + "libbt-bta", + "libbtdevice", + "libbtif", + "libbt-hci", + "libbt-stack", + "libbt-utils", + "libbtcore", + "libosi", + "libbt-protos-lite", + ], + // Shared library link options. + // References to global symbols and functions should bind to the library + // itself. This is to avoid issues with some of the unit/system tests + // that might link statically with some of the code in the library, and + // also dlopen(3) the shared library. + ldflags: ["-Wl,-Bsymbolic,-Bsymbolic-functions"], + required: [ + "bt_did.conf", + "bt_stack.conf", + "libldacBT_enc", + "libldacBT_abr", + ], + cflags: [ + "-DBUILDCFG", + ], +} + +cc_library_static { + name: "libbluetooth-for-tests", + defaults: ["fluoride_defaults"], + + srcs: [ + "bte_conf.cc", + "bte_init.cc", + "bte_init_cpp_logging.cc", + "bte_logmsg.cc", + "bte_main.cc", + "stack_config.cc", + ], + include_dirs: [ + "system/bt", + "system/bt/bta/include", + "system/bt/btcore/include", + "system/bt/btif/include", + "system/bt/hci/include", + "system/bt/internal_include", + "system/bt/stack/include", + "system/bt/utils/include", + ], + cflags: [ + "-DBUILDCFG", + ], +} diff --git a/aosp/system/core/bootstat/Android.bp b/aosp/system/core/bootstat/Android.bp new file mode 100644 index 000000000..d7761775f --- /dev/null +++ b/aosp/system/core/bootstat/Android.bp @@ -0,0 +1,97 @@ +// +// Copyright (C) 2016 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +bootstat_lib_src_files = [ + "boot_event_record_store.cpp", +] + +cc_defaults { + name: "bootstat_defaults", + + cflags: [ + "-Wall", + "-Wextra", + "-Werror", + ], + shared_libs: [ + "libbase", + "libcutils", + "liblog", + "libmetricslogger", + ], +} + +// bootstat static library +// ----------------------------------------------------------------------------- +cc_library_static { + name: "libbootstat", + defaults: ["bootstat_defaults"], + srcs: bootstat_lib_src_files, +} + +// bootstat static library, debug +// ----------------------------------------------------------------------------- +cc_library_static { + name: "libbootstat_debug", + defaults: ["bootstat_defaults"], + host_supported: true, + srcs: bootstat_lib_src_files, + + target: { + host: { + cflags: ["-UNDEBUG"], + }, + }, +} + +// bootstat binary +// ----------------------------------------------------------------------------- +cc_binary { + name: "bootstat_orig", + defaults: ["bootstat_defaults"], + static_libs: ["libbootstat"], + shared_libs: [ + "liblogcat", + "libstatslog" + ], + init_rc: ["bootstat.rc"], + product_variables: { + pdk: { + enabled: false, + }, + debuggable: { + init_rc: ["bootstat-debug.rc"], + }, + }, + srcs: ["bootstat.cpp"], +} + +// Native tests +// ----------------------------------------------------------------------------- +cc_test { + name: "bootstat_tests", + test_suites: ["device-tests"], + defaults: ["bootstat_defaults"], + host_supported: true, + static_libs: [ + "libbootstat_debug", + "libgmock", + ], + srcs: [ + "boot_event_record_store_test.cpp", + "testrunner.cpp", + ], +} diff --git a/aosp/system/core/debuggerd/crasher/Android.bp b/aosp/system/core/debuggerd/crasher/Android.bp new file mode 100644 index 000000000..b073d486b --- /dev/null +++ b/aosp/system/core/debuggerd/crasher/Android.bp @@ -0,0 +1,84 @@ +cc_defaults { + name: "crasher-defaults", + + cflags: [ + "-W", + "-Wall", + "-Wextra", + "-Wunused", + "-Werror", + "-O0", + "-fstack-protector-all", + "-Wno-free-nonheap-object", + "-Wno-date-time", + ], + srcs: ["crasher.cpp"], + arch: { + arm: { + srcs: ["arm/crashglue.S"], + + neon: { + asflags: ["-DHAS_VFP_D32"], + }, + }, + arm64: { + srcs: ["arm64/crashglue.S"], + }, + mips: { + srcs: ["mips/crashglue.S"], + }, + mips64: { + srcs: ["mips64/crashglue.S"], + }, + x86: { + srcs: ["x86/crashglue.S"], + }, + x86_64: { + srcs: ["x86_64/crashglue.S"], + }, + }, + compile_multilib: "both", +} + +cc_binary { + name: "crasher", + + defaults: ["crasher-defaults"], + shared_libs: [ + "libbase", + "liblog", + ], + static_libs: [ + "libseccomp_policy", + ], + multilib: { + lib32: { + stem: "crasher", + }, + lib64: { + stem: "crasher64", + }, + }, +} + +cc_binary { + name: "static_crasher", + + defaults: ["crasher-defaults"], + cppflags: ["-DSTATIC_CRASHER"], + static_executable: true, + static_libs: [ + "libdebuggerd_handler", + "libbase", + "liblog", + "libseccomp_policy", + ], + multilib: { + lib32: { + stem: "static_crasher", + }, + lib64: { + stem: "static_crasher64", + }, + }, +} diff --git a/aosp/system/core/fastboot/Android.mk b/aosp/system/core/fastboot/Android.mk new file mode 100644 index 000000000..f56fb9c7a --- /dev/null +++ b/aosp/system/core/fastboot/Android.mk @@ -0,0 +1,127 @@ +# Copyright (C) 2007 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +LOCAL_PATH:= $(call my-dir) + +include $(LOCAL_PATH)/../platform_tools_tool_version.mk + +include $(CLEAR_VARS) + +LOCAL_CFLAGS += -DFASTBOOT_VERSION="\"$(tool_version)\"" + +LOCAL_C_INCLUDES := \ + $(LOCAL_PATH)/../adb \ + +LOCAL_HEADER_LIBRARIES := bootimg_headers + +LOCAL_SRC_FILES := \ + bootimg_utils.cpp \ + engine.cpp \ + fastboot.cpp \ + fs.cpp\ + protocol.cpp \ + socket.cpp \ + tcp.cpp \ + udp.cpp \ + util.cpp \ + +LOCAL_MODULE := fastboot +LOCAL_MODULE_TAGS := debug +LOCAL_MODULE_HOST_OS := darwin linux windows +LOCAL_CFLAGS += -Wall -Wextra -Werror -Wunreachable-code +LOCAL_REQUIRED_MODULES := mke2fs make_f2fs + +LOCAL_SRC_FILES_linux := usb_linux.cpp +LOCAL_STATIC_LIBRARIES_linux := libselinux +LOCAL_REQUIRED_MODULES_linux := e2fsdroid mke2fs.conf sload_f2fs + +LOCAL_SRC_FILES_darwin := usb_osx.cpp +LOCAL_STATIC_LIBRARIES_darwin := libselinux +LOCAL_REQUIRED_MODULES_darwin := e2fsdroid mke2fs.conf sload_f2fs +LOCAL_LDLIBS_darwin := -lpthread -framework CoreFoundation -framework IOKit -framework Carbon +LOCAL_CFLAGS_darwin := -Wno-unused-parameter + +LOCAL_SRC_FILES_windows := usb_windows.cpp +LOCAL_SHARED_LIBRARIES_windows := AdbWinApi +LOCAL_REQUIRED_MODULES_windows := AdbWinUsbApi +LOCAL_LDLIBS_windows := -lws2_32 +LOCAL_C_INCLUDES_windows := development/host/windows/usb/api + +LOCAL_STATIC_LIBRARIES := \ + libziparchive \ + libsparse \ + libutils \ + liblog \ + libz \ + libdiagnose_usb \ + libbase \ + libcutils \ + libgtest_host \ + +LOCAL_CXX_STL := libc++_static + +# Don't add anything here, we don't want additional shared dependencies +# on the host fastboot tool, and shared libraries that link against libc++ +# will violate ODR +LOCAL_SHARED_LIBRARIES := + +#include $(BUILD_HOST_EXECUTABLE) + +my_dist_files := $(LOCAL_BUILT_MODULE) +my_dist_files += $(HOST_OUT_EXECUTABLES)/mke2fs$(HOST_EXECUTABLE_SUFFIX) +my_dist_files += $(HOST_OUT_EXECUTABLES)/e2fsdroid$(HOST_EXECUTABLE_SUFFIX) +my_dist_files += $(HOST_OUT_EXECUTABLES)/make_f2fs$(HOST_EXECUTABLE_SUFFIX) +my_dist_files += $(HOST_OUT_EXECUTABLES)/sload_f2fs$(HOST_EXECUTABLE_SUFFIX) +$(call dist-for-goals,dist_files sdk win_sdk,$(my_dist_files)) +ifdef HOST_CROSS_OS +# Archive fastboot.exe for win_sdk build. +$(call dist-for-goals,win_sdk,$(ALL_MODULES.host_cross_fastboot.BUILT)) +endif +my_dist_files := + +ifeq ($(HOST_OS),linux) +include $(CLEAR_VARS) +LOCAL_SRC_FILES := usbtest.cpp usb_linux.cpp util.cpp +LOCAL_MODULE := usbtest +LOCAL_CFLAGS := -Werror +LOCAL_STATIC_LIBRARIES := libbase +#include $(BUILD_HOST_EXECUTABLE) +endif + +# fastboot_test +# ========================================================= +include $(CLEAR_VARS) + +LOCAL_MODULE := fastboot_test +LOCAL_MODULE_HOST_OS := darwin linux windows + +LOCAL_SRC_FILES := \ + socket.cpp \ + socket_mock.cpp \ + socket_test.cpp \ + tcp.cpp \ + tcp_test.cpp \ + udp.cpp \ + udp_test.cpp \ + +LOCAL_STATIC_LIBRARIES := libbase libcutils + +LOCAL_CFLAGS += -Wall -Wextra -Werror -Wunreachable-code + +LOCAL_LDLIBS_darwin := -lpthread -framework CoreFoundation -framework IOKit -framework Carbon +LOCAL_CFLAGS_darwin := -Wno-unused-parameter + +LOCAL_LDLIBS_windows := -lws2_32 + +#include $(BUILD_HOST_NATIVE_TEST) diff --git a/aosp/system/core/init/Android.bp b/aosp/system/core/init/Android.bp new file mode 100644 index 000000000..d86a45f45 --- /dev/null +++ b/aosp/system/core/init/Android.bp @@ -0,0 +1,258 @@ +// +// Copyright (C) 2017 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +cc_defaults { + name: "init_defaults", + cpp_std: "experimental", + sanitize: { + misc_undefined: ["signed-integer-overflow"], + }, + cflags: [ + "-DLOG_UEVENTS=0", + "-Wall", + "-Wextra", + "-Wno-unused-parameter", + "-Werror", + "-DALLOW_LOCAL_PROP_OVERRIDE=0", + "-DALLOW_PERMISSIVE_SELINUX=0", + "-DREBOOT_BOOTLOADER_ON_PANIC=0", + "-DWORLD_WRITABLE_KMSG=0", + "-DDUMP_ON_UMOUNT_FAILURE=0", + "-DSHUTDOWN_ZERO_TIMEOUT=0", + ], + product_variables: { + debuggable: { + cppflags: [ + "-UALLOW_LOCAL_PROP_OVERRIDE", + "-DALLOW_LOCAL_PROP_OVERRIDE=1", + "-UALLOW_PERMISSIVE_SELINUX", + "-DALLOW_PERMISSIVE_SELINUX=1", + "-UREBOOT_BOOTLOADER_ON_PANIC", + "-DREBOOT_BOOTLOADER_ON_PANIC=1", + "-UWORLD_WRITABLE_KMSG", + "-DWORLD_WRITABLE_KMSG=1", + "-UDUMP_ON_UMOUNT_FAILURE", + "-DDUMP_ON_UMOUNT_FAILURE=1", + ], + }, + eng: { + cppflags: [ + "-USHUTDOWN_ZERO_TIMEOUT", + "-DSHUTDOWN_ZERO_TIMEOUT=1", + ], + }, + uml: { + cppflags: ["-DUSER_MODE_LINUX"], + }, + }, + static_libs: [ + "libbootloader_message", + "libfs_mgr", + "libfec", + "libfec_rs", + "libhidl-gen-utils", + "libsquashfs_utils", + "liblogwrap", + "libext4_utils", + "libcutils", + "libbase", + "libc", + "libseccomp_policy", + "libselinux", + "liblog", + "libcrypto_utils", + "libcrypto", + "libc++_static", + "libdl", + "libsparse", + "libz", + "libprocessgroup_static", + "libavb", + "libkeyutils", + "libprotobuf-cpp-lite", + "libpropertyinfoserializer", + "libpropertyinfoparser", + ], +} + +cc_library_static { + name: "libinit", + defaults: ["init_defaults"], + srcs: [ + "action.cpp", + "action_manager.cpp", + "action_parser.cpp", + "bootchart.cpp", + "builtins.cpp", + "capabilities.cpp", + "descriptors.cpp", + "devices.cpp", + "firmware_handler.cpp", + "import_parser.cpp", + "init.cpp", + "init_first_stage.cpp", + "keychords.cpp", + "log.cpp", + "parser.cpp", + "persistent_properties.cpp", + "persistent_properties.proto", + "property_service.cpp", + "property_type.cpp", + "reboot.cpp", + "security.cpp", + "selinux.cpp", + "service.cpp", + "sigchld_handler.cpp", + "subcontext.cpp", + "subcontext.proto", + "rlimit_parser.cpp", + "tokenizer.cpp", + "uevent_listener.cpp", + "ueventd.cpp", + "ueventd_parser.cpp", + "util.cpp", + "watchdogd.cpp", + ], + whole_static_libs: ["libcap"], + header_libs: ["bootimg_headers"], + proto: { + type: "lite", + export_proto_headers: true, + }, +} + +/* +This is not yet ready, see the below TODOs for what is missing + +cc_binary { + // TODO: Missing, + //LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT) + //LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_UNSTRIPPED) + + name: "init", + defaults: ["init_defaults"], + required: [ + "e2fsdroid", + "mke2fs", + "sload_f2fs", + "make_f2fs", + ], + static_executable: true, + srcs: ["main.cpp"], + symlinks: [ + "sbin/ueventd", + "sbin/watchdogd", + ], +} +*/ + +// Tests +// ------------------------------------------------------------------------------ + +cc_test { + name: "init_tests", + defaults: ["init_defaults"], + static_executable: true, + srcs: [ + "devices_test.cpp", + "init_test.cpp", + "persistent_properties_test.cpp", + "property_service_test.cpp", + "property_type_test.cpp", + "result_test.cpp", + "rlimit_parser_test.cpp", + "service_test.cpp", + "subcontext_test.cpp", + "ueventd_test.cpp", + "util_test.cpp", + ], + static_libs: ["libinit"], +} + +cc_benchmark { + name: "init_benchmarks", + static_executable: true, + defaults: ["init_defaults"], + srcs: [ + "subcontext_benchmark.cpp", + ], + static_libs: ["libinit"], +} + +// Host Verifier +// ------------------------------------------------------------------------------ + +genrule { + name: "generated_stub_builtin_function_map", + out: ["generated_stub_builtin_function_map.h"], + srcs: ["builtins.cpp"], + cmd: "sed -n '/Builtin-function-map start/{:a;n;/Builtin-function-map end/q;p;ba}' $(in) | sed -e 's/do_[^}]*/do_stub/g' > $(out)", +} + +cc_binary { + name: "host_init_verifier", + host_supported: true, + cpp_std: "experimental", + cflags: [ + "-Wall", + "-Wextra", + "-Wno-unused-parameter", + "-Werror", + ], + static_libs: [ + "libbase", + "libselinux", + ], + whole_static_libs: ["libcap"], + shared_libs: [ + "libprotobuf-cpp-lite", + "libhidl-gen-utils", + "libprocessgroup", + "liblog", + "libcutils", + ], + srcs: [ + "action.cpp", + "action_manager.cpp", + "action_parser.cpp", + "capabilities.cpp", + "descriptors.cpp", + "import_parser.cpp", + "host_init_parser.cpp", + "host_init_stubs.cpp", + "parser.cpp", + "rlimit_parser.cpp", + "tokenizer.cpp", + "service.cpp", + "subcontext.cpp", + "subcontext.proto", + "util.cpp", + ], + proto: { + type: "lite", + }, + generated_headers: ["generated_stub_builtin_function_map"], + target: { + android: { + enabled: false, + }, + darwin: { + enabled: false, + }, + }, +} + +subdirs = ["*"] diff --git a/aosp/system/core/init/Android.mk b/aosp/system/core/init/Android.mk new file mode 100644 index 000000000..92e46bd13 --- /dev/null +++ b/aosp/system/core/init/Android.mk @@ -0,0 +1,93 @@ +# Copyright 2005 The Android Open Source Project + +LOCAL_PATH:= $(call my-dir) + +# -- + +ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT))) +init_options += \ + -DALLOW_LOCAL_PROP_OVERRIDE=1 \ + -DALLOW_PERMISSIVE_SELINUX=1 \ + -DREBOOT_BOOTLOADER_ON_PANIC=1 \ + -DWORLD_WRITABLE_KMSG=1 \ + -DDUMP_ON_UMOUNT_FAILURE=1 +else +init_options += \ + -DALLOW_LOCAL_PROP_OVERRIDE=0 \ + -DALLOW_PERMISSIVE_SELINUX=0 \ + -DREBOOT_BOOTLOADER_ON_PANIC=0 \ + -DWORLD_WRITABLE_KMSG=0 \ + -DDUMP_ON_UMOUNT_FAILURE=0 +endif + +ifneq (,$(filter eng,$(TARGET_BUILD_VARIANT))) +init_options += \ + -DSHUTDOWN_ZERO_TIMEOUT=1 +else +init_options += \ + -DSHUTDOWN_ZERO_TIMEOUT=0 +endif + +init_options += -DLOG_UEVENTS=0 + +init_cflags += \ + $(init_options) \ + -Wall -Wextra \ + -Wno-unused-parameter \ + -Werror \ + -std=gnu++1z \ + +# -- + +include $(CLEAR_VARS) +LOCAL_CPPFLAGS := $(init_cflags) +LOCAL_SRC_FILES := main.cpp + +LOCAL_MODULE:= init_orig + +LOCAL_FORCE_STATIC_EXECUTABLE := true +LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT) +LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_UNSTRIPPED) + +LOCAL_STATIC_LIBRARIES := \ + libinit \ + libbootloader_message \ + libfs_mgr \ + libfec \ + libfec_rs \ + libhidl-gen-utils \ + libsquashfs_utils \ + liblogwrap \ + libext4_utils \ + libcutils \ + libbase \ + libc \ + libseccomp_policy \ + libselinux \ + liblog \ + libcrypto_utils \ + libcrypto \ + libc++_static \ + libdl \ + libsparse \ + libz \ + libprocessgroup_static \ + libavb \ + libkeyutils \ + libprotobuf-cpp-lite \ + libpropertyinfoserializer \ + libpropertyinfoparser \ + +LOCAL_REQUIRED_MODULES := \ + e2fsdroid \ + mke2fs \ + sload_f2fs \ + make_f2fs \ + +# Create symlinks. +LOCAL_POST_INSTALL_CMD := $(hide) mkdir -p $(TARGET_ROOT_OUT)/sbin; \ + ln -sf ../init $(TARGET_ROOT_OUT)/sbin/ueventd; \ + ln -sf ../init $(TARGET_ROOT_OUT)/sbin/watchdogd + +LOCAL_SANITIZE := signed-integer-overflow +include $(BUILD_EXECUTABLE) diff --git a/aosp/system/core/init/prepare_filesystem.cpp b/aosp/system/core/init/prepare_filesystem.cpp new file mode 100644 index 000000000..6f2fa98af --- /dev/null +++ b/aosp/system/core/init/prepare_filesystem.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved. + * Description: prepare filesystem + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "log.h" +#include "init.h" + +namespace android { +namespace init { +static void getfilename(const std::string &dirname, std::vector &filename) +{ + DIR *dp; + struct dirent *dirp; + if ((dp = opendir(dirname.c_str())) == NULL) { + return; + } + + while ((dirp = readdir(dp)) != NULL) { + if (strcmp(dirp->d_name, ".") && strcmp(dirp->d_name, "..")) { + filename.push_back(dirname + '/' + dirp->d_name); + } + } + closedir(dp); + return; +} +void prepare_filesystem(void) +{ + struct stat buffer; + std::vector filename = {"uinput", "binder", "ashmem"}; + int result = 0; + + if (stat("/dev/dri/renderD128", &buffer) != 0) { + exit(0); + } + mkdir("/dev/input", 0755); + getfilename("/dev/dri", filename); + for (auto f : filename) { + if (stat(f.c_str(), &buffer) == 0) { + chown(f.c_str(), AID_SYSTEM, AID_SYSTEM); + chmod(f.c_str(), 0666); + } + } + if (lstat("/etc", &buffer) == 0 && (!S_ISLNK(buffer.st_mode))) { + result = system("rm -rf /etc"); + if (result != 0) { + LOG(ERROR) << "rm -rf /etc excute failed\n"; + } + } + if (stat("/hook.sh", &buffer) == 0) { + result = system("sh /hook.sh"); + if (result != 0) { + LOG(ERROR) << "hook.sh excute failed\n"; + } + } + std::ofstream kmsg("/dev/kmsg"); + kmsg.close(); + return; +} +} // namespace init +} // namespace android diff --git a/aosp/system/core/libprocessgroup/Android.bp b/aosp/system/core/libprocessgroup/Android.bp new file mode 100644 index 000000000..4751e4f20 --- /dev/null +++ b/aosp/system/core/libprocessgroup/Android.bp @@ -0,0 +1,13 @@ +cc_library { + srcs: ["processgroup.cpp"], + name: "libprocessgroup_orig", + host_supported: true, + shared_libs: ["libbase"], + export_include_dirs: ["include"], + cflags: [ + "-Wall", + "-Werror", + "-Wno-unused-parameter", + "-Wno-unused-function", + ], +} diff --git a/aosp/system/core/libsuspend/Android.bp b/aosp/system/core/libsuspend/Android.bp new file mode 100644 index 000000000..024c8a974 --- /dev/null +++ b/aosp/system/core/libsuspend/Android.bp @@ -0,0 +1,27 @@ +// Copyright 2012 The Android Open Source Project + +cc_library { + name: "libsuspend_orig", + vendor_available: true, + vndk: { + enabled: true, + }, + + srcs: [ + "autosuspend.c", + "autosuspend_wakeup_count.cpp", + ], + export_include_dirs: ["include"], + local_include_dirs: ["include"], + shared_libs: [ + "libbase", + "liblog", + "libcutils", + ], + cflags: [ + "-Werror", + // "-DLOG_NDEBUG=0", + "-Wno-unused-parameter", + "-Wno-unused-function", + ], +} diff --git a/aosp/system/core/lmkd/Android.bp b/aosp/system/core/lmkd/Android.bp new file mode 100644 index 000000000..bee8f28ad --- /dev/null +++ b/aosp/system/core/lmkd/Android.bp @@ -0,0 +1,51 @@ +cc_binary { + name: "lmkd_orig", + + srcs: ["lmkd.c"], + shared_libs: [ + "liblog", + "libcutils", + "libprocessgroup", + ], + static_libs: [ + "libstatslogc", + "libstatssocket", + ], + local_include_dirs: ["include"], + cflags: ["-Werror", "-DLMKD_TRACE_KILLS", "-DCPH_LMKD"], + init_rc: ["lmkd.rc"], + product_variables: { + use_lmkd_stats_log: { + cflags: [ + "-DLMKD_LOG_STATS" + ], + }, + }, +} + +cc_library_static { + name: "libstatslogc", + srcs: ["statslog.c"], + cflags: [ + "-Wall", + "-Werror", + ], + shared_libs: [ + "liblog", + ], + static_libs: ["libstatssocket",], +} + +cc_library_static { + name: "liblmkd_utils", + srcs: ["liblmkd_utils.c"], + shared_libs: [ + "libcutils", + ], + export_include_dirs: ["include"], + cppflags: [ + "-g", + "-Wall", + "-Werror", + ] +} diff --git a/aosp/system/core/logd/Android.bp b/aosp/system/core/logd/Android.bp new file mode 100644 index 000000000..8bca56400 --- /dev/null +++ b/aosp/system/core/logd/Android.bp @@ -0,0 +1,78 @@ +// Copyright (C) 2017 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// This is what we want to do: +// event_logtags = $(shell +// sed -n +// "s/^\([0-9]*\)[ \t]*$1[ \t].*/-D`echo $1 | tr a-z A-Z`_LOG_TAG=\1/p" +// $(LOCAL_PATH)/$2/event.logtags) +// event_flag := $(call event_logtags,auditd) +// event_flag += $(call event_logtags,logd) +// event_flag += $(call event_logtags,tag_def) +// so make sure we do not regret hard-coding it as follows: +event_flag = [ + "-DAUDITD_LOG_TAG=1003", + "-DCHATTY_LOG_TAG=1004", + "-DTAG_DEF_LOG_TAG=1005", + "-DLIBLOG_LOG_TAG=1006", +] + +cc_library_static { + name: "liblogd", + + srcs: [ + "LogCommand.cpp", + "CommandListener.cpp", + "LogListener.cpp", + "LogReader.cpp", + "FlushCommand.cpp", + "LogBuffer.cpp", + "LogBufferElement.cpp", + "LogBufferInterface.cpp", + "LogTimes.cpp", + "LogStatistics.cpp", + "LogWhiteBlackList.cpp", + "libaudit.c", + "LogAudit.cpp", + "LogKlog.cpp", + "LogTags.cpp", + ], + logtags: ["event.logtags"], + + shared_libs: ["libbase"], + + export_include_dirs: ["."], + + cflags: ["-Werror"] + event_flag, +} + +cc_binary { + name: "logd_orig", + init_rc: ["logd.rc"], + + srcs: ["main.cpp"], + + static_libs: ["liblogd"], + + shared_libs: [ + "libsysutils", + "liblog", + "libcutils", + "libbase", + "libpackagelistparser", + "libcap", + ], + + cflags: ["-Werror"], +} diff --git a/aosp/system/core/reboot/Android.bp b/aosp/system/core/reboot/Android.bp new file mode 100644 index 000000000..ea1af5642 --- /dev/null +++ b/aosp/system/core/reboot/Android.bp @@ -0,0 +1,11 @@ +// Copyright 2013 The Android Open Source Project + +cc_binary { + name: "reboot_orig", + srcs: ["reboot.c"], + shared_libs: [ + "libcutils", + "liblog", + ], + cflags: ["-Werror"], +} diff --git a/aosp/system/core/rootdir/etc/public.libraries.android.txt b/aosp/system/core/rootdir/etc/public.libraries.android.txt new file mode 100644 index 000000000..9cee09f32 --- /dev/null +++ b/aosp/system/core/rootdir/etc/public.libraries.android.txt @@ -0,0 +1,27 @@ +# See https://android.googlesource.com/platform/ndk/+/master/docs/PlatformApis.md +libandroid.so +libaaudio.so +libc.so +libcamera2ndk.so +libdl.so +libEGL.so +libGLESv1_CM.so +libGLESv2.so +libGLESv3.so +libicui18n.so +libicuuc.so +libjnigraphics.so +liblog.so +libmediandk.so +libm.so +libnativewindow.so +libneuralnetworks.so +libOpenMAXAL.so +libOpenSLES.so +libRS.so +libstdc++.so +libsync.so +libvulkan.so +libwebviewchromium_plat_support.so +libz.so +libCPHMediaEngine.so diff --git a/aosp/system/core/rootdir/init.environ.rc.in b/aosp/system/core/rootdir/init.environ.rc.in new file mode 100644 index 000000000..e20c69406 --- /dev/null +++ b/aosp/system/core/rootdir/init.environ.rc.in @@ -0,0 +1,14 @@ +# set up the global environment +on init + export ANDROID_BOOTLOGO 1 + export ANDROID_ROOT /system + export ANDROID_ASSETS /system/app + export ANDROID_DATA /data + export ANDROID_STORAGE /storage + export EXTERNAL_STORAGE /sdcard + export ASEC_MOUNTPOINT /mnt/asec + export BOOTCLASSPATH %BOOTCLASSPATH% + export SYSTEMSERVERCLASSPATH %SYSTEMSERVERCLASSPATH% + export ANTISIMULATOR true + %EXPORT_GLOBAL_ASAN_OPTIONS% + %EXPORT_GLOBAL_GCOV_OPTIONS% diff --git a/aosp/system/core/rootdir/init.rc b/aosp/system/core/rootdir/init.rc new file mode 100644 index 000000000..27bd774eb --- /dev/null +++ b/aosp/system/core/rootdir/init.rc @@ -0,0 +1,911 @@ +# Copyright (C) 2012 The Android Open Source Project +# +# IMPORTANT: Do not create world writable files or directories. +# This is a common source of Android security bugs. +# + +import /init.environ.rc +import /init.usb.rc +import /vendor/etc/init/hw/init.${ro.hardware}.rc +#import /init.usb.configfs.rc +import /init.${ro.zygote}.rc +import /init.wifi.rc +import /init.custom.rc + +on early-init + mount debugfs debugfs /sys/kernel/debug + mount none /sys/kernel/tracing /sys/kernel/debug/tracing bind + chmod 0755 /sys/kernel/debug +on init + +on boot + setprop ARGH ARGH + +# fake some battery state + setprop status.battery.state Slow + setprop status.battery.level 5 + setprop status.battery.level_raw 50 + setprop status.battery.level_scale 9 + +# set up the GPU caching + setprop ro.hwui.texture_cache_size 72 + setprop ro.hwui.layer_cache_size 48 + setprop ro.hwui.r_buffer_cache_size 8 + setprop ro.hwui.path_cache_size 32 + setprop ro.hwui.gradient_cache_size 1 + setprop ro.hwui.drop_shadow_cache_size 6 + setprop ro.hwui.texture_cache_flushrate 0.4 + setprop ro.hwui.text_small_cache_width 1024 + setprop ro.hwui.text_small_cache_height 1024 + setprop ro.hwui.text_large_cache_width 2048 + setprop ro.hwui.text_large_cache_height 1024 + +# disable some daemons the emulator doesn't want + stop dund + stop akmd + +# start essential services + start board-logcat + start uinput + +# enable Google-specific location features, +# like NetworkLocationProvider and LocationCollector + setprop ro.com.google.locationfeatures 1 + + +on fs + mount_all /fstab.board + +service uinput /system/bin/uinput + class core + socket vinput stream 0666 root root + user root + group root + +# -Q is a special logcat option that forces the +# program to check wether it runs on the emulator +# if it does, it redirects its output to the device +# named by the androidboot.console kernel option +# if not, is simply exits immediately + +service board-logcat /system/bin/logcat -Q + oneshot + +on early-init + # Set init and its forked children's oom_adj. + write /proc/1/oom_score_adj -1000 + + # Disable sysrq from keyboard + write /proc/sys/kernel/sysrq 0 + + # Set the security context of /adb_keys if present. + restorecon /adb_keys + + # Set the security context of /postinstall if present. + restorecon /postinstall + + # Mount cgroup mount point for cpu accounting + mount cgroup none /acct nodev noexec nosuid cpuacct + # fix EulerOS cgroup cpu,cpuacct subsys mounting + # mount cgroup none /acct nodev noexec nosuid cpu,cpuacct + mkdir /acct/uid + + # root memory control cgroup, used by lmkd + mkdir /dev/memcg 0700 root system + mount cgroup none /dev/memcg nodev noexec nosuid memory + # app mem cgroups, used by activity manager, lmkd and zygote + mkdir /dev/memcg/apps/ 0755 system system + # cgroup for system_server and surfaceflinger + mkdir /dev/memcg/system 0550 system system + + # handling cold boot events + write /dev/.coldboot_done "" + +on init + sysclktz 0 + setrlimit 4 0 0 + + # Mix device-specific information into the entropy pool + copy /proc/cmdline /dev/urandom + copy /default.prop /dev/urandom + + symlink /system/bin /bin + symlink /system/etc /etc + + # Backward compatibility. + symlink /sys/kernel/debug /d + + # Link /vendor to /system/vendor for devices without a vendor partition. + symlink /system/vendor /vendor + + # Create energy-aware scheduler tuning nodes + mkdir /dev/stune + mount cgroup none /dev/stune nodev noexec nosuid schedtune + mkdir /dev/stune/foreground + mkdir /dev/stune/background + mkdir /dev/stune/top-app + mkdir /dev/stune/rt + chown system system /dev/stune + chown system system /dev/stune/foreground + chown system system /dev/stune/background + chown system system /dev/stune/top-app + chown system system /dev/stune/rt + chown system system /dev/stune/tasks + chown system system /dev/stune/foreground/tasks + chown system system /dev/stune/background/tasks + chown system system /dev/stune/top-app/tasks + chown system system /dev/stune/rt/tasks + chmod 0664 /dev/stune/tasks + chmod 0664 /dev/stune/foreground/tasks + chmod 0664 /dev/stune/background/tasks + chmod 0664 /dev/stune/top-app/tasks + chmod 0664 /dev/stune/rt/tasks + + restorecon_recursive /mnt + + mount configfs none /config nodev noexec nosuid + chmod 0770 /config/sdcardfs + chown system package_info /config/sdcardfs + + mkdir /mnt/secure 0700 root root + mkdir /mnt/secure/asec 0700 root root + mkdir /mnt/asec 0755 root system + mkdir /mnt/obb 0755 root system + mkdir /mnt/media_rw 0750 root media_rw + mkdir /mnt/user 0755 root root + mkdir /mnt/user/0 0755 root root + mkdir /mnt/expand 0771 system system + mkdir /mnt/appfuse 0711 root root + + # Storage views to support runtime permissions + mkdir /mnt/runtime 0700 root root + mkdir /mnt/runtime/default 0755 root root + mkdir /mnt/runtime/default/self 0755 root root + mkdir /mnt/runtime/read 0755 root root + mkdir /mnt/runtime/read/self 0755 root root + mkdir /mnt/runtime/write 0755 root root + mkdir /mnt/runtime/write/self 0755 root root + + # Symlink to keep legacy apps working in multi-user world + symlink /storage/self/primary /sdcard + symlink /storage/self/primary /mnt/sdcard + symlink /mnt/user/0/primary /mnt/runtime/default/self/primary + + write /proc/sys/kernel/panic_on_oops 1 + write /proc/sys/kernel/hung_task_timeout_secs 0 + write /proc/cpu/alignment 4 + + # scheduler tunables + # Disable auto-scaling of scheduler tunables with hotplug. The tunables + # will vary across devices in unpredictable ways if allowed to scale with + # cpu cores. + write /proc/sys/kernel/sched_tunable_scaling 0 + write /proc/sys/kernel/sched_latency_ns 10000000 + write /proc/sys/kernel/sched_wakeup_granularity_ns 2000000 + write /proc/sys/kernel/sched_child_runs_first 0 + + write /proc/sys/kernel/randomize_va_space 2 + write /proc/sys/vm/mmap_min_addr 32768 + write /proc/sys/net/ipv4/ping_group_range "0 2147483647" + write /proc/sys/net/unix/max_dgram_qlen 600 + write /proc/sys/kernel/sched_rt_runtime_us 950000 + write /proc/sys/kernel/sched_rt_period_us 1000000 + + # Assign reasonable ceiling values for socket rcv/snd buffers. + # These should almost always be overridden by the target per the + # the corresponding technology maximums. + write /proc/sys/net/core/rmem_max 262144 + write /proc/sys/net/core/wmem_max 262144 + + # reflect fwmark from incoming packets onto generated replies + write /proc/sys/net/ipv4/fwmark_reflect 1 + write /proc/sys/net/ipv6/fwmark_reflect 1 + + # set fwmark on accepted sockets + write /proc/sys/net/ipv4/tcp_fwmark_accept 1 + + # disable icmp redirects + write /proc/sys/net/ipv4/conf/all/accept_redirects 0 + write /proc/sys/net/ipv6/conf/all/accept_redirects 0 + + # /proc/net/fib_trie leaks interface IP addresses + chmod 0400 /proc/net/fib_trie + + # Create cgroup mount points for process groups + mkdir /dev/cpuctl + mount cgroup none /dev/cpuctl nodev noexec nosuid cpu + # fix EulerOS cgroup cpu,cpuacct subsys mounting + # mount cgroup none /dev/cpuctl nodev noexec nosuid cpu,cpuacct + chown system system /dev/cpuctl + chown system system /dev/cpuctl/tasks + chmod 0666 /dev/cpuctl/tasks + write /dev/cpuctl/cpu.rt_period_us 1000000 + write /dev/cpuctl/cpu.rt_runtime_us 950000 + + # sets up initial cpusets for ActivityManager + mkdir /dev/cpuset + mount cpuset none /dev/cpuset nodev noexec nosuid + + # this ensures that the cpusets are present and usable, but the device's + # init.rc must actually set the correct cpus + mkdir /dev/cpuset/foreground + copy /dev/cpuset/cpus /dev/cpuset/foreground/cpus + copy /dev/cpuset/mems /dev/cpuset/foreground/mems + mkdir /dev/cpuset/background + copy /dev/cpuset/cpus /dev/cpuset/background/cpus + copy /dev/cpuset/mems /dev/cpuset/background/mems + + # system-background is for system tasks that should only run on + # little cores, not on bigs + # to be used only by init, so don't change system-bg permissions + mkdir /dev/cpuset/system-background + copy /dev/cpuset/cpus /dev/cpuset/system-background/cpus + copy /dev/cpuset/mems /dev/cpuset/system-background/mems + + # restricted is for system tasks that are being throttled + # due to screen off. + mkdir /dev/cpuset/restricted + copy /dev/cpuset/cpus /dev/cpuset/restricted/cpus + copy /dev/cpuset/mems /dev/cpuset/restricted/mems + + mkdir /dev/cpuset/top-app + copy /dev/cpuset/cpus /dev/cpuset/top-app/cpus + copy /dev/cpuset/mems /dev/cpuset/top-app/mems + + # change permissions for all cpusets we'll touch at runtime + chown system system /dev/cpuset + chown system system /dev/cpuset/foreground + chown system system /dev/cpuset/background + chown system system /dev/cpuset/system-background + chown system system /dev/cpuset/top-app + chown system system /dev/cpuset/restricted + chown system system /dev/cpuset/tasks + chown system system /dev/cpuset/foreground/tasks + chown system system /dev/cpuset/background/tasks + chown system system /dev/cpuset/system-background/tasks + chown system system /dev/cpuset/top-app/tasks + chown system system /dev/cpuset/restricted/tasks + + # set system-background to 0775 so SurfaceFlinger can touch it + chmod 0775 /dev/cpuset/system-background + + chmod 0664 /dev/cpuset/foreground/tasks + chmod 0664 /dev/cpuset/background/tasks + chmod 0664 /dev/cpuset/system-background/tasks + chmod 0664 /dev/cpuset/top-app/tasks + chmod 0664 /dev/cpuset/restricted/tasks + chmod 0664 /dev/cpuset/tasks + + + # qtaguid will limit access to specific data based on group memberships. + # net_bw_acct grants impersonation of socket owners. + # net_bw_stats grants access to other apps' detailed tagged-socket stats. + chown root net_bw_acct /proc/net/xt_qtaguid/ctrl + chown root net_bw_stats /proc/net/xt_qtaguid/stats + + # Allow everybody to read the xt_qtaguid resource tracking misc dev. + # This is needed by any process that uses socket tagging. + chmod 0644 /dev/xt_qtaguid + + mkdir /dev/cg2_bpf + mount cgroup2 cg2_bpf /dev/cg2_bpf nodev noexec nosuid + chown root root /dev/cg2_bpf + chmod 0600 /dev/cg2_bpf + mount bpf bpf /sys/fs/bpf nodev noexec nosuid + + # Create location for fs_mgr to store abbreviated output from filesystem + # checker programs. + mkdir /dev/fscklogs 0770 root system + + # pstore/ramoops previous console log + mount pstore pstore /sys/fs/pstore nodev noexec nosuid + chown system log /sys/fs/pstore/console-ramoops + chmod 0440 /sys/fs/pstore/console-ramoops + chown system log /sys/fs/pstore/console-ramoops-0 + chmod 0440 /sys/fs/pstore/console-ramoops-0 + chown system log /sys/fs/pstore/pmsg-ramoops-0 + chmod 0440 /sys/fs/pstore/pmsg-ramoops-0 + + # mkdir gps + mkdir /data/gps/ 0755 system system + + # enable armv8_deprecated instruction hooks + write /proc/sys/abi/swp 1 + + # Linux's execveat() syscall may construct paths containing /dev/fd + # expecting it to point to /proc/self/fd + symlink /proc/self/fd /dev/fd + + export DOWNLOAD_CACHE /data/cache + + # set RLIMIT_NICE to allow priorities from 19 to -20 + setrlimit nice 40 40 + + # Allow up to 32K FDs per process + setrlimit nofile 32768 32768 + + # This allows the ledtrig-transient properties to be created here so + # that they can be chown'd to system:system later on boot + write /sys/class/leds/vibrator/trigger "transient" + + restorecon /sys/class/power_supply/battery/voltage_now + restorecon /proc/version + +# Healthd can trigger a full boot from charger mode by signaling this +# property when the power button is held. +on property:sys.boot_from_charger_mode=1 + class_stop charger + trigger late-init + +on load_persist_props_action + load_persist_props + init_kernel_drivers + start logd + start logd-reinit + +# Indicate to fw loaders that the relevant mounts are up. +on firmware_mounts_complete + rm /dev/.booting + +# Mount filesystems and start core system services. +on late-init + trigger early-fs + + # Mount fstab in init.{$device}.rc by mount_all command. Optional parameter + # '--early' can be specified to skip entries with 'latemount'. + # /system and /vendor must be mounted by the end of the fs stage, + # while /data is optional. + trigger fs + trigger post-fs + + # Mount fstab in init.{$device}.rc by mount_all with '--late' parameter + # to only mount entries with 'latemount'. This is needed if '--early' is + # specified in the previous mount_all command on the fs stage. + # With /system mounted and properties form /system + /factory available, + # some services can be started. + trigger late-fs + + # Now we can mount /data. File encryption requires keymaster to decrypt + # /data, which in turn can only be loaded when system properties are present. + trigger post-fs-data + + # Now we can start zygote for devices with file based encryption + trigger zygote-start + + # Load persist properties and override properties (if enabled) from /data. + trigger load_persist_props_action + + # Remove a file to wake up anything waiting for firmware. + trigger firmware_mounts_complete + + trigger early-boot + trigger boot + +on post-fs + # Load properties from + # /system/build.prop, + # /odm/build.prop, + # /vendor/build.prop and + # /factory/factory.prop + load_system_props + # start essential services + start logd + start servicemanager + start hwservicemanager + start vndservicemanager + start kauditd + + # Once everything is setup, no need to modify /. + # The bind+ro combination avoids modifying any other mount flags. + mount rootfs rootfs / rw remount + # Mount shared so changes propagate into child namespaces + mount rootfs rootfs / shared rec + # Mount default storage into root namespace + mount none /mnt/runtime/default /storage bind rec + mount none none /storage slave rec + mount none /system/vendor/sbin /sbin bind + + # Make sure /sys/kernel/debug (if present) is labeled properly + # Note that tracefs may be mounted under debug, so we need to cross filesystems + restorecon --recursive --cross-filesystems /sys/kernel/debug + + # We chown/chmod /cache again so because mount is run as root + defaults + chown system cache /cache + chmod 0770 /cache + # We restorecon /cache in case the cache partition has been reset. + restorecon_recursive /cache + + # Create /cache/recovery in case it's not there. It'll also fix the odd + # permissions if created by the recovery system. + mkdir /cache/recovery 0770 system cache + + # Backup/restore mechanism uses the cache partition + mkdir /cache/backup_stage 0700 system system + mkdir /cache/backup 0700 system system + + #change permissions on vmallocinfo so we can grab it from bugreports + chown root log /proc/vmallocinfo + chmod 0440 /proc/vmallocinfo + + chown root log /proc/slabinfo + chmod 0440 /proc/slabinfo + + #change permissions on kmsg & sysrq-trigger so bugreports can grab kthread stacks + chown root system /proc/kmsg + chmod 0440 /proc/kmsg + chown root system /proc/sysrq-trigger + chmod 0220 /proc/sysrq-trigger + chown system log /proc/last_kmsg + chmod 0440 /proc/last_kmsg + + # make the selinux kernel policy world-readable + chmod 0444 /sys/fs/selinux/policy + + # create the lost+found directories, so as to enforce our permissions + mkdir /cache/lost+found 0770 root root + + restorecon_recursive /metadata + mkdir /metadata/vold + chmod 0700 /metadata/vold + +on late-fs + # Ensure that tracefs has the correct permissions. + # This does not work correctly if it is called in post-fs. + chmod 0755 /sys/kernel/debug/tracing + + # HALs required before storage encryption can get unlocked (FBE/FDE) + class_start early_hal + +on post-fs-data + # We chown/chmod /data again so because mount is run as root + defaults + chown system system /data + chmod 0771 /data + # We restorecon /data in case the userdata partition has been reset. + restorecon /data + + # Make sure we have the device encryption key. + start vold + installkey /data + + # Start bootcharting as soon as possible after the data partition is + # mounted to collect more data. + mkdir /data/bootchart 0755 shell shell + bootchart start + + # Avoid predictable entropy pool. Carry over entropy from previous boot. + copy /data/system/entropy.dat /dev/urandom + + # create basic filesystem structure + mkdir /data/misc 01771 system misc + # mounted by agent, we can write directly + write /data/misc/init/phone_status "booting" + mkdir /data/misc/recovery 0770 system log + copy /data/misc/recovery/ro.build.fingerprint /data/misc/recovery/ro.build.fingerprint.1 + chmod 0440 /data/misc/recovery/ro.build.fingerprint.1 + chown system log /data/misc/recovery/ro.build.fingerprint.1 + write /data/misc/recovery/ro.build.fingerprint ${ro.build.fingerprint} + chmod 0440 /data/misc/recovery/ro.build.fingerprint + chown system log /data/misc/recovery/ro.build.fingerprint + mkdir /data/misc/recovery/proc 0770 system log + copy /data/misc/recovery/proc/version /data/misc/recovery/proc/version.1 + chmod 0440 /data/misc/recovery/proc/version.1 + chown system log /data/misc/recovery/proc/version.1 + copy /proc/version /data/misc/recovery/proc/version + chmod 0440 /data/misc/recovery/proc/version + chown system log /data/misc/recovery/proc/version + mkdir /data/misc/bluedroid 02770 bluetooth bluetooth + # Fix the access permissions and group ownership for 'bt_config.conf' + chmod 0660 /data/misc/bluedroid/bt_config.conf + chown bluetooth bluetooth /data/misc/bluedroid/bt_config.conf + mkdir /data/misc/bluetooth 0770 bluetooth bluetooth + mkdir /data/misc/bluetooth/logs 0770 bluetooth bluetooth + mkdir /data/misc/keystore 0700 keystore keystore + mkdir /data/misc/gatekeeper 0700 system system + mkdir /data/misc/keychain 0771 system system + mkdir /data/misc/net 0750 root shell + mkdir /data/misc/radio 0770 system radio + mkdir /data/misc/sms 0770 system radio + mkdir /data/misc/carrierid 0770 system radio + mkdir /data/misc/apns 0770 system radio + mkdir /data/misc/zoneinfo 0775 system system + mkdir /data/misc/network_watchlist 0774 system system + mkdir /data/misc/textclassifier 0771 system system + mkdir /data/misc/vpn 0770 system vpn + mkdir /data/misc/shared_relro 0771 shared_relro shared_relro + mkdir /data/misc/systemkeys 0700 system system + mkdir /data/misc/wifi 0770 wifi wifi + mkdir /data/misc/wifi/sockets 0770 wifi wifi + mkdir /data/misc/wifi/wpa_supplicant 0770 wifi wifi + mkdir /data/misc/ethernet 0770 system system + mkdir /data/misc/dhcp 0770 dhcp dhcp + mkdir /data/misc/user 0771 root root + mkdir /data/misc/perfprofd 0775 root root + # give system access to wpa_supplicant.conf for backup and restore + chmod 0660 /data/misc/wifi/wpa_supplicant.conf + mkdir /data/local 0751 root root + mkdir /data/misc/media 0700 media media + mkdir /data/misc/audioserver 0700 audioserver audioserver + mkdir /data/misc/cameraserver 0700 cameraserver cameraserver + mkdir /data/misc/vold 0700 root root + mkdir /data/misc/boottrace 0771 system shell + mkdir /data/misc/update_engine 0700 root root + mkdir /data/misc/update_engine_log 02750 root log + mkdir /data/misc/trace 0700 root root + # create location to store surface and window trace files + mkdir /data/misc/wmtrace 0700 system system + # profile file layout + mkdir /data/misc/profiles 0771 system system + mkdir /data/misc/profiles/cur 0771 system system + mkdir /data/misc/profiles/ref 0771 system system + mkdir /data/misc/profman 0770 system shell + mkdir /data/misc/gcov 0770 root root + + mkdir /data/vendor 0771 root root + mkdir /data/vendor_ce 0771 root root + mkdir /data/vendor_de 0771 root root + mkdir /data/vendor/hardware 0771 root root + + # For security reasons, /data/local/tmp should always be empty. + # Do not place files or directories in /data/local/tmp + mkdir /data/local/tmp 0771 shell shell + mkdir /data/local/traces 0777 shell shell + mkdir /data/data 0771 system system + mkdir /data/app-private 0771 system system + mkdir /data/app-ephemeral 0771 system system + mkdir /data/app-asec 0700 root root + mkdir /data/app-lib 0771 system system + mkdir /data/app 0771 system system + mkdir /data/property 0700 root root + mkdir /data/tombstones 0771 system system + mkdir /data/vendor/tombstones 0771 root root + mkdir /data/vendor/tombstones/wifi 0771 wifi wifi + + # create dalvik-cache, so as to enforce our permissions + mkdir /data/dalvik-cache 0771 root root + # create the A/B OTA directory, so as to enforce our permissions + mkdir /data/ota 0771 root root + + # create the OTA package directory. It will be accessed by GmsCore (cache + # group), update_engine and update_verifier. + mkdir /data/ota_package 0770 system cache + + # create resource-cache and double-check the perms + mkdir /data/resource-cache 0771 system system + chown system system /data/resource-cache + chmod 0771 /data/resource-cache + + # create the lost+found directories, so as to enforce our permissions + mkdir /data/lost+found 0770 root root + + # create directory for DRM plug-ins - give drm the read/write access to + # the following directory. + mkdir /data/drm 0770 drm drm + + # create directory for MediaDrm plug-ins - give drm the read/write access to + # the following directory. + mkdir /data/mediadrm 0770 mediadrm mediadrm + + mkdir /data/anr 0775 system system + + # NFC: create data/nfc for nv storage + mkdir /data/nfc 0770 nfc nfc + mkdir /data/nfc/param 0770 nfc nfc + + # Create all remaining /data root dirs so that they are made through init + # and get proper encryption policy installed + mkdir /data/backup 0700 system system + mkdir /data/ss 0700 system system + + mkdir /data/system 0775 system system + mkdir /data/system/heapdump 0700 system system + mkdir /data/system/users 0775 system system + + mkdir /data/system_de 0770 system system + mkdir /data/system_ce 0770 system system + + mkdir /data/misc_de 01771 system misc + mkdir /data/misc_ce 01771 system misc + + mkdir /data/user 0711 system system + mkdir /data/user_de 0711 system system + symlink /data/data /data/user/0 + + mkdir /data/media 0770 media_rw media_rw + mkdir /data/media/obb 0770 media_rw media_rw + + mkdir /data/cache 0770 system cache + mkdir /data/cache/recovery 0770 system cache + mkdir /data/cache/backup_stage 0700 system system + mkdir /data/cache/backup 0700 system system + + # for logcat + mkdir /data/log 0700 root root + + init_user0 + + # Set SELinux security contexts on upgrade or policy update. + restorecon --recursive --skip-ce /data + + # Check any timezone data in /data is newer than the copy in /system, delete if not. + exec - system system -- /system/bin/tzdatacheck /system/usr/share/zoneinfo /data/misc/zoneinfo + + # If there is no post-fs-data action in the init..rc file, you + # must uncomment this line, otherwise encrypted filesystems + # won't work. + # Set indication (checked by vold) that we have finished this action + #setprop vold.post_fs_data_done 1 + + # shareApp fs + exec /system/bin/buildOverlayfs.sh + +# It is recommended to put unnecessary data/ initialization from post-fs-data +# to start-zygote in device's init.rc to unblock zygote start. +on zygote-start && property:ro.crypto.state=unencrypted + # A/B update verifier that marks a successful boot. + #exec_start update_verifier_nonencrypted + start netd + start zygote + start zygote_secondary + +on zygote-start && property:ro.crypto.state=unsupported + # A/B update verifier that marks a successful boot. + #exec_start update_verifier_nonencrypted + start netd + start zygote + start zygote_secondary + +on zygote-start && property:ro.crypto.state=encrypted && property:ro.crypto.type=file + # A/B update verifier that marks a successful boot. + #exec_start update_verifier_nonencrypted + start netd + start zygote + start zygote_secondary + +on boot + # basic network init + ifup lo + hostname localhost + domainname localdomain + + # IPsec SA default expiration length + write /proc/sys/net/core/xfrm_acq_expires 3600 + + # Memory management. Basic kernel parameters, and allow the high + # level system server to be able to adjust the kernel OOM driver + # parameters to match how it is managing things. + write /proc/sys/vm/overcommit_memory 1 + write /proc/sys/vm/min_free_order_shift 4 + chown root system /sys/module/lowmemorykiller/parameters/adj + chmod 0664 /sys/module/lowmemorykiller/parameters/adj + chown root system /sys/module/lowmemorykiller/parameters/minfree + chmod 0664 /sys/module/lowmemorykiller/parameters/minfree + + # Tweak background writeout + write /proc/sys/vm/dirty_expire_centisecs 200 + write /proc/sys/vm/dirty_background_ratio 5 + + # Permissions for System Server and daemons. + chown radio system /sys/android_power/state + chown radio system /sys/android_power/request_state + chown radio system /sys/android_power/acquire_full_wake_lock + chown radio system /sys/android_power/acquire_partial_wake_lock + chown radio system /sys/android_power/release_wake_lock + chown system system /sys/power/autosleep + chown system system /sys/power/state + chown system system /sys/power/wakeup_count + chown radio wakelock /sys/power/wake_lock + chown radio wakelock /sys/power/wake_unlock + chmod 0660 /sys/power/state + chmod 0660 /sys/power/wake_lock + chmod 0660 /sys/power/wake_unlock + + chown system system /sys/devices/system/cpu/cpufreq/interactive/timer_rate + chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/timer_rate + chown system system /sys/devices/system/cpu/cpufreq/interactive/timer_slack + chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/timer_slack + chown system system /sys/devices/system/cpu/cpufreq/interactive/min_sample_time + chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/min_sample_time + chown system system /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq + chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/hispeed_freq + chown system system /sys/devices/system/cpu/cpufreq/interactive/target_loads + chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/target_loads + chown system system /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load + chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/go_hispeed_load + chown system system /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay + chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/above_hispeed_delay + chown system system /sys/devices/system/cpu/cpufreq/interactive/boost + chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/boost + chown system system /sys/devices/system/cpu/cpufreq/interactive/boostpulse + chown system system /sys/devices/system/cpu/cpufreq/interactive/input_boost + chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/input_boost + chown system system /sys/devices/system/cpu/cpufreq/interactive/boostpulse_duration + chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/boostpulse_duration + chown system system /sys/devices/system/cpu/cpufreq/interactive/io_is_busy + chmod 0660 /sys/devices/system/cpu/cpufreq/interactive/io_is_busy + + # Assume SMP uses shared cpufreq policy for all CPUs + chown system system /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq + chmod 0660 /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq + + chown system system /sys/class/leds/vibrator/trigger + chown system system /sys/class/leds/vibrator/activate + chown system system /sys/class/leds/vibrator/brightness + chown system system /sys/class/leds/vibrator/duration + chown system system /sys/class/leds/vibrator/state + chown system system /sys/class/timed_output/vibrator/enable + chown system system /sys/class/leds/keyboard-backlight/brightness + chown system system /sys/class/leds/lcd-backlight/brightness + chown system system /sys/class/leds/button-backlight/brightness + chown system system /sys/class/leds/jogball-backlight/brightness + chown system system /sys/class/leds/red/brightness + chown system system /sys/class/leds/green/brightness + chown system system /sys/class/leds/blue/brightness + chown system system /sys/class/leds/red/device/grpfreq + chown system system /sys/class/leds/red/device/grppwm + chown system system /sys/class/leds/red/device/blink + chown system system /sys/module/sco/parameters/disable_esco + chown system system /sys/kernel/ipv4/tcp_wmem_min + chown system system /sys/kernel/ipv4/tcp_wmem_def + chown system system /sys/kernel/ipv4/tcp_wmem_max + chown system system /sys/kernel/ipv4/tcp_rmem_min + chown system system /sys/kernel/ipv4/tcp_rmem_def + chown system system /sys/kernel/ipv4/tcp_rmem_max + chown root radio /proc/cmdline + + # Define default initial receive window size in segments. + setprop net.tcp.default_init_rwnd 60 + + start cph_logger + # Start standard binderized HAL daemons + class_start hal + + class_start core + +#on nonencrypted + class_start main + class_start late_start + +on property:sys.init_log_level=* + loglevel ${sys.init_log_level} + +on charger + class_start charger + +on property:vold.decrypt=trigger_reset_main + class_reset main + +on property:vold.decrypt=trigger_load_persist_props + load_persist_props + start logd + start logd-reinit + +on property:vold.decrypt=trigger_post_fs_data + trigger post-fs-data + trigger zygote-start + +on property:vold.decrypt=trigger_restart_min_framework + # A/B update verifier that marks a successful boot. + exec_start update_verifier + class_start main + +on property:vold.decrypt=trigger_restart_framework + stop surfaceflinger + start surfaceflinger + # A/B update verifier that marks a successful boot. + exec_start update_verifier + class_start main + class_start late_start + +on property:vold.decrypt=trigger_shutdown_framework + class_reset late_start + class_reset main + +on property:sys.boot_completed=1 + bootchart stop + +# system server cannot write to /proc/sys files, +# and chown/chmod does not work for /proc/sys/ entries. +# So proxy writes through init. +on property:sys.sysctl.extra_free_kbytes=* + write /proc/sys/vm/extra_free_kbytes ${sys.sysctl.extra_free_kbytes} + +# "tcp_default_init_rwnd" Is too long! +on property:sys.sysctl.tcp_def_init_rwnd=* + write /proc/sys/net/ipv4/tcp_default_init_rwnd ${sys.sysctl.tcp_def_init_rwnd} + +on property:security.perf_harden=0 + write /proc/sys/kernel/perf_event_paranoid 1 + +on property:security.perf_harden=1 + write /proc/sys/kernel/perf_event_paranoid 3 + +# on shutdown +# In device's init.rc, this trigger can be used to do device-specific actions +# before shutdown. e.g disable watchdog and mask error handling +on shutdown + write /data/misc/init/phone_status "shutting down" + +## Daemon processes to be run by init. +## +service console /system/bin/sh + class core + console + disabled + user shell + group shell log readproc + seclabel u:r:shell:s0 + setenv HOSTNAME console + +on property:ro.debuggable=1 + # Give writes to anyone for the trace folder on debug builds. + # The folder is used to store method traces. + chmod 0773 /data/misc/trace + # Give reads to anyone for the window trace folder on debug builds. + chmod 0775 /data/misc/wmtrace + #start console + +service flash_recovery /system/bin/install-recovery.sh + class main + oneshot + +service mtpd /system/bin/mtpd + socket mtpd stream 600 system system + user root + group vpn net_admin net_raw + disabled + oneshot + +on property:sys.boot_completed=1 + write /data/misc/init/phone_status "running" + start configphone + +on property:com.cph.config_phone_done=1 && property:com.cph.enable_rootfs_ro=1 + mount rootfs rootfs / ro remount + +service cph_logger /system/bin/cph_logger.sh + user root + group root + seclabel u:r:shell:s0 + +service configphone /system/bin/config_phone.sh + user root + group root + oneshot + disabled + seclabel u:r:shell:s0 + +on property:ro.serialno=* + setprop ro.boot.serialno ${ro.serialno} + +on property:ro.baseband=* + #setprop ro.boot.baseband ${ro.baseband} + setprop ro.boot.baseband "" + +on property:ro.bootloader=* + #setprop ro.boot.bootloader ${ro.bootloader} + setprop ro.boot.bootloader "" + +on property:ro.hardware=* + setprop ro.boot.hardware ${ro.hardware} + +on property:ro.build.date.utc=* + setprop ro.bootimage.build.date.utc ${ro.build.date.utc} + start configBuildDate + +service configBuildDate /system/bin/configBuildDate.sh + user root + group root + oneshot + disabled + seclabel u:r:shell:s0 + +on property:ro.build.date=* + setprop ro.bootimage.build.date ${ro.build.date} + +service kauditd /system/bin/kauditd --daemon + user root + group root + seclabel u:r:shell:s0 + +on property:sys.action.shutdown=1 + exec_background - root root -- /system/bin/am broadcast -a android.intent.action.ACTION_SHUTDOWN diff --git a/aosp/system/core/rootdir/init.usb.configfs.rc b/aosp/system/core/rootdir/init.usb.configfs.rc new file mode 100644 index 000000000..8ff0caa52 --- /dev/null +++ b/aosp/system/core/rootdir/init.usb.configfs.rc @@ -0,0 +1,140 @@ +#on property:sys.usb.config=none && property:sys.usb.configfs=1 +# write /config/usb_gadget/g1/UDC "none" +# stop adbd +# setprop sys.usb.ffs.ready 0 +# write /config/usb_gadget/g1/bDeviceClass 0 +# write /config/usb_gadget/g1/bDeviceSubClass 0 +# write /config/usb_gadget/g1/bDeviceProtocol 0 +# rm /config/usb_gadget/g1/configs/b.1/f1 +# rm /config/usb_gadget/g1/configs/b.1/f2 +# rm /config/usb_gadget/g1/configs/b.1/f3 +# rmdir /config/usb_gadget/g1/functions/rndis.gs4 +# setprop sys.usb.state ${sys.usb.config} + +on property:init.svc.adbd=stopped + setprop sys.usb.ffs.ready 0 + +on property:sys.usb.config=adb && property:sys.usb.configfs=1 + start watchdogd + +on property:sys.usb.ffs.ready=1 && property:sys.usb.config=adb && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "adb" + symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f1 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=mtp && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "mtp" + symlink /config/usb_gadget/g1/functions/mtp.gs0 /config/usb_gadget/g1/configs/b.1/f1 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=mtp,adb && property:sys.usb.configfs=1 + start watchdogd + +on property:sys.usb.ffs.ready=1 && property:sys.usb.config=mtp,adb && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "mtp_adb" + symlink /config/usb_gadget/g1/functions/mtp.gs0 /config/usb_gadget/g1/configs/b.1/f1 + symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f2 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=ptp && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "ptp" + symlink /config/usb_gadget/g1/functions/ptp.gs1 /config/usb_gadget/g1/configs/b.1/f1 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=ptp,adb && property:sys.usb.configfs=1 + start watchdogd + +on property:sys.usb.ffs.ready=1 && property:sys.usb.config=ptp,adb && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "ptp_adb" + symlink /config/usb_gadget/g1/functions/ptp.gs1 /config/usb_gadget/g1/configs/b.1/f1 + symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f2 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=accessory && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "accessory" + symlink /config/usb_gadget/g1/functions/accessory.gs2 /config/usb_gadget/g1/configs/b.1/f1 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=accessory,adb && property:sys.usb.configfs=1 + start watchdogd + +on property:sys.usb.ffs.ready=1 && property:sys.usb.config=accessory,adb && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "accessory_adb" + symlink /config/usb_gadget/g1/functions/accessory.gs2 /config/usb_gadget/g1/configs/b.1/f1 + symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f2 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=audio_source && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "audiosource" + symlink /config/usb_gadget/g1/functions/audio_source.gs3 /config/usb_gadget/g1/configs/b.1/f1 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=audio_source,adb && property:sys.usb.configfs=1 + start watchdogd + +on property:sys.usb.ffs.ready=1 && property:sys.usb.config=audio_source,adb && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "audiosource_adb" + symlink /config/usb_gadget/g1/functions/audio_source.gs3 /config/usb_gadget/g1/configs/b.1/f1 + symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f2 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=accessory,audio_source && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "accessory_audiosource" + symlink /config/usb_gadget/g1/functions/accessory.gs2 /config/usb_gadget/g1/configs/b.1/f1 + symlink /config/usb_gadget/g1/functions/audio_source.gs3 /config/usb_gadget/g1/configs/b.1/f2 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=accessory,audio_source,adb && property:sys.usb.configfs=1 + start watchdogd + +on property:sys.usb.ffs.ready=1 && property:sys.usb.config=accessory,audio_source,adb && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "accessory_audiosource_adb" + symlink /config/usb_gadget/g1/functions/accessory.gs2 /config/usb_gadget/g1/configs/b.1/f1 + symlink /config/usb_gadget/g1/functions/audio_source.gs3 /config/usb_gadget/g1/configs/b.1/f2 + symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f3 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=midi && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "midi" + symlink /config/usb_gadget/g1/functions/midi.gs5 /config/usb_gadget/g1/configs/b.1/f1 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=midi,adb && property:sys.usb.configfs=1 + start watchdogd + +on property:sys.usb.ffs.ready=1 && property:sys.usb.config=midi,adb && property:sys.usb.configfs=1 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "midi_adb" + symlink /config/usb_gadget/g1/functions/midi.gs5 /config/usb_gadget/g1/configs/b.1/f1 + symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f2 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=rndis && property:sys.usb.configfs=1 + mkdir /config/usb_gadget/g1/functions/rndis.gs4 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "rndis" + symlink /config/usb_gadget/g1/functions/rndis.gs4 /config/usb_gadget/g1/configs/b.1/f1 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} + +on property:sys.usb.config=rndis,adb && property:sys.usb.configfs=1 + start watchdogd + +on property:sys.usb.ffs.ready=1 && property:sys.usb.config=rndis,adb && property:sys.usb.configfs=1 + mkdir /config/usb_gadget/g1/functions/rndis.gs4 + write /config/usb_gadget/g1/configs/b.1/strings/0x409/configuration "rndis_adb" + symlink /config/usb_gadget/g1/functions/rndis.gs4 /config/usb_gadget/g1/configs/b.1/f1 + symlink /config/usb_gadget/g1/functions/ffs.adb /config/usb_gadget/g1/configs/b.1/f2 + write /config/usb_gadget/g1/UDC ${sys.usb.controller} + setprop sys.usb.state ${sys.usb.config} diff --git a/aosp/system/core/rootdir/init.usb.rc b/aosp/system/core/rootdir/init.usb.rc new file mode 100644 index 000000000..1e964b140 --- /dev/null +++ b/aosp/system/core/rootdir/init.usb.rc @@ -0,0 +1,136 @@ +# Copyright (C) 2012 The Android Open Source Project +# +# USB configuration common for all android devices +# + +on post-fs-data + chown system system /sys/class/android_usb/android0/f_mass_storage/lun/file + chmod 0660 /sys/class/android_usb/android0/f_mass_storage/lun/file + chown system system /sys/class/android_usb/android0/f_rndis/ethaddr + chmod 0660 /sys/class/android_usb/android0/f_rndis/ethaddr + mkdir /data/misc/adb 02750 system shell + mkdir /data/adb 0700 root root + +# adbd is controlled via property triggers in init..usb.rc +service watchdogd /system/bin/watchdogd --root_seclabel=u:r:su:s0 + class core + socket watchdogd stream 660 system system + disabled + seclabel u:r:adbd:s0 + +on boot + setprop sys.usb.configfs 0 + start watchdogd + +# Used to disable USB when switching states +# modify by lzl +#on property:sys.usb.config=none && property:sys.usb.configfs=0 +# stop adbd +# write /sys/class/android_usb/android0/enable 0 +# write /sys/class/android_usb/android0/bDeviceClass 0 +# setprop sys.usb.state ${sys.usb.config} + +# adb only USB configuration +# This is the fallback configuration if the +# USB manager fails to set a standard configuration +on property:sys.usb.config=adb && property:sys.usb.configfs=0 + write /sys/class/android_usb/android0/enable 0 + write /sys/class/android_usb/android0/idVendor 18d1 + write /sys/class/android_usb/android0/idProduct 4EE7 + write /sys/class/android_usb/android0/functions ${sys.usb.config} + write /sys/class/android_usb/android0/enable 1 + start watchdogd + setprop sys.usb.state ${sys.usb.config} + +# USB accessory configuration +on property:sys.usb.config=accessory && property:sys.usb.configfs=0 + write /sys/class/android_usb/android0/enable 0 + write /sys/class/android_usb/android0/idVendor 18d1 + write /sys/class/android_usb/android0/idProduct 2d00 + write /sys/class/android_usb/android0/functions ${sys.usb.config} + write /sys/class/android_usb/android0/enable 1 + setprop sys.usb.state ${sys.usb.config} + +# USB accessory configuration, with adb +on property:sys.usb.config=accessory,adb && property:sys.usb.configfs=0 + write /sys/class/android_usb/android0/enable 0 + write /sys/class/android_usb/android0/idVendor 18d1 + write /sys/class/android_usb/android0/idProduct 2d01 + write /sys/class/android_usb/android0/functions ${sys.usb.config} + write /sys/class/android_usb/android0/enable 1 + start watchdogd + setprop sys.usb.state ${sys.usb.config} + +# audio accessory configuration +on property:sys.usb.config=audio_source && property:sys.usb.configfs=0 + write /sys/class/android_usb/android0/enable 0 + write /sys/class/android_usb/android0/idVendor 18d1 + write /sys/class/android_usb/android0/idProduct 2d02 + write /sys/class/android_usb/android0/functions ${sys.usb.config} + write /sys/class/android_usb/android0/enable 1 + setprop sys.usb.state ${sys.usb.config} + +# audio accessory configuration, with adb +on property:sys.usb.config=audio_source,adb && property:sys.usb.configfs=0 + write /sys/class/android_usb/android0/enable 0 + write /sys/class/android_usb/android0/idVendor 18d1 + write /sys/class/android_usb/android0/idProduct 2d03 + write /sys/class/android_usb/android0/functions ${sys.usb.config} + write /sys/class/android_usb/android0/enable 1 + start watchdogd + setprop sys.usb.state ${sys.usb.config} + +# USB and audio accessory configuration +on property:sys.usb.config=accessory,audio_source && property:sys.usb.configfs=0 + write /sys/class/android_usb/android0/enable 0 + write /sys/class/android_usb/android0/idVendor 18d1 + write /sys/class/android_usb/android0/idProduct 2d04 + write /sys/class/android_usb/android0/functions ${sys.usb.config} + write /sys/class/android_usb/android0/enable 1 + setprop sys.usb.state ${sys.usb.config} + +# USB and audio accessory configuration, with adb +on property:sys.usb.config=accessory,audio_source,adb && property:sys.usb.configfs=0 + write /sys/class/android_usb/android0/enable 0 + write /sys/class/android_usb/android0/idVendor 18d1 + write /sys/class/android_usb/android0/idProduct 2d05 + write /sys/class/android_usb/android0/functions ${sys.usb.config} + write /sys/class/android_usb/android0/enable 1 + start watchdogd + setprop sys.usb.state ${sys.usb.config} + +# Used to set USB configuration at boot and to switch the configuration +# when changing the default configuration +on boot && property:persist.sys.usb.config=* + setprop sys.usb.config ${persist.sys.usb.config} + +# +# USB type C +# + +# USB mode changes +on property:sys.usb.typec.mode=dfp + write /sys/class/dual_role_usb/otg_default/mode ${sys.usb.typec.mode} + setprop sys.usb.typec.state ${sys.usb.typec.mode} + +on property:sys.usb.typec.mode=ufp + write /sys/class/dual_role_usb/otg_default/mode ${sys.usb.typec.mode} + setprop sys.usb.typec.state ${sys.usb.typec.mode} + +# USB data role changes +on property:sys.usb.typec.data_role=device + write /sys/class/dual_role_usb/otg_default/data_role ${sys.usb.typec.data_role} + setprop sys.usb.typec.state ${sys.usb.typec.data_role} + +on property:sys.usb.typec.data_role=host + write /sys/class/dual_role_usb/otg_default/data_role ${sys.usb.typec.data_role} + setprop sys.usb.typec.state ${sys.usb.typec.data_role} + +# USB power role changes +on property:sys.usb.typec.power_role=source + write /sys/class/dual_role_usb/otg_default/power_role ${sys.usb.typec.power_role} + setprop sys.usb.typec.state ${sys.usb.typec.power_role} + +on property:sys.usb.typec.power_role=sink + write /sys/class/dual_role_usb/otg_default/power_role ${sys.usb.typec.power_role} + setprop sys.usb.typec.state ${sys.usb.typec.power_role} diff --git a/aosp/system/core/rootdir/init.zygote32.rc b/aosp/system/core/rootdir/init.zygote32.rc new file mode 100644 index 000000000..f1516e07d --- /dev/null +++ b/aosp/system/core/rootdir/init.zygote32.rc @@ -0,0 +1,14 @@ +service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server + class main + priority -20 + user root + group root readproc reserved_disk + socket zygote stream 660 root system + #onrestart write /sys/android_power/request_state wake + #onrestart write /sys/power/state on + onrestart restart audioserver + onrestart restart cameraserver + onrestart restart media + onrestart restart netd + onrestart restart wificond + writepid /dev/cpuset/foreground/tasks diff --git a/aosp/system/core/rootdir/init.zygote32_64.rc b/aosp/system/core/rootdir/init.zygote32_64.rc new file mode 100644 index 000000000..457493280 --- /dev/null +++ b/aosp/system/core/rootdir/init.zygote32_64.rc @@ -0,0 +1,23 @@ +service zygote /system/bin/app_process32 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote + class main + priority -20 + user root + group root readproc reserved_disk + socket zygote stream 660 root system + #onrestart write /sys/android_power/request_state wake + #onrestart write /sys/power/state on + onrestart restart audioserver + onrestart restart cameraserver + onrestart restart media + onrestart restart netd + onrestart restart wificond + #writepid /dev/cpuset/foreground/tasks + +service zygote_secondary /system/bin/app_process64 -Xzygote /system/bin --zygote --socket-name=zygote_secondary + class main + priority -20 + user root + group root readproc reserved_disk + socket zygote_secondary stream 660 root system + onrestart restart zygote + #writepid /dev/cpuset/foreground/tasks diff --git a/aosp/system/core/rootdir/init.zygote64.rc b/aosp/system/core/rootdir/init.zygote64.rc new file mode 100644 index 000000000..46d5756d4 --- /dev/null +++ b/aosp/system/core/rootdir/init.zygote64.rc @@ -0,0 +1,14 @@ +service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server + class main + priority -20 + user root + group root readproc reserved_disk + socket zygote stream 660 root system + #onrestart write /sys/android_power/request_state wake + #onrestart write /sys/power/state on + onrestart restart audioserver + onrestart restart cameraserver + onrestart restart media + onrestart restart netd + onrestart restart wificond + #writepid /dev/cpuset/foreground/tasks diff --git a/aosp/system/core/rootdir/init.zygote64_32.rc b/aosp/system/core/rootdir/init.zygote64_32.rc new file mode 100644 index 000000000..1193c0bc6 --- /dev/null +++ b/aosp/system/core/rootdir/init.zygote64_32.rc @@ -0,0 +1,23 @@ +service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote + class main + priority -20 + user root + group root readproc reserved_disk + socket zygote stream 660 root system + #onrestart write /sys/android_power/request_state wake + #onrestart write /sys/power/state on + onrestart restart audioserver + onrestart restart cameraserver + onrestart restart media + onrestart restart netd + onrestart restart wificond + writepid /dev/cpuset/foreground/tasks + +service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary --enable-lazy-preload + class main + priority -20 + user root + group root readproc reserved_disk + socket zygote_secondary stream 660 root system + onrestart restart zygote + writepid /dev/cpuset/foreground/tasks diff --git a/aosp/system/core/rootdir/ueventd.rc b/aosp/system/core/rootdir/ueventd.rc new file mode 100644 index 000000000..35806d825 --- /dev/null +++ b/aosp/system/core/rootdir/ueventd.rc @@ -0,0 +1,141 @@ +subsystem adf + devname uevent_devname + +subsystem graphics + devname uevent_devpath + dirname /dev/graphics + +subsystem drm + devname uevent_devpath + dirname /dev/dri + +subsystem oncrpc + devname uevent_devpath + dirname /dev/oncrpc + +subsystem adsp + devname uevent_devpath + dirname /dev/adsp + +subsystem msm_camera + devname uevent_devpath + dirname /dev/msm_camera + +subsystem input + devname uevent_devpath + dirname /dev/input + +subsystem mtd + devname uevent_devpath + dirname /dev/mtd + +subsystem sound + devname uevent_devpath + dirname /dev/snd + +# ueventd can only set permissions on device nodes and their associated +# sysfs attributes, not on arbitrary paths. +# +# format for /dev rules: devname mode uid gid +# format for /sys rules: nodename attr mode uid gid +# shortcut: "mtd@NN" expands to "/dev/mtd/mtdNN" + +/dev/null 0666 root root +/dev/zero 0666 root root +/dev/full 0666 root root +/dev/ptmx 0666 root root +/dev/tty 0666 root root +/dev/random 0666 root root +/dev/urandom 0666 root root +# Make HW RNG readable by group system to let EntropyMixer read it. +/dev/hw_random 0440 root system +/dev/ashmem 0666 root root +/dev/binder 0666 root root +/dev/hwbinder 0666 root root +/dev/vndbinder 0666 root root + +/dev/pmsg0 0222 root log + +# the msm hw3d client device node is world writable/readable. +/dev/msm_hw3dc 0666 root root + +# gpu driver for adreno200 is globally accessible +/dev/kgsl 0666 root root + +# kms driver for drm based gpu +/dev/dri/* 0666 root graphics + +# these should not be world writable +/dev/diag 0660 radio radio +/dev/diag_arm9 0660 radio radio +/dev/ttyMSM0 0600 bluetooth bluetooth +/dev/uhid 0660 uhid uhid +/dev/uinput 0660 system bluetooth +/dev/alarm 0664 system radio +/dev/rtc0 0640 system system +/dev/tty0 0660 root system +/dev/graphics/* 0660 root graphics +/dev/msm_hw3dm 0660 system graphics +/dev/input/* 0660 root input +/dev/v4l-touch* 0660 root input +/dev/eac 0660 root audio +/dev/cam 0660 root camera +/dev/pmem 0660 system graphics +/dev/pmem_adsp* 0660 system audio +/dev/pmem_camera* 0660 system camera +/dev/oncrpc/* 0660 root system +/dev/adsp/* 0660 system audio +/dev/snd/* 0660 system audio +/dev/mt9t013 0660 system system +/dev/msm_camera/* 0660 system system +/dev/akm8976_daemon 0640 compass system +/dev/akm8976_aot 0640 compass system +/dev/akm8973_daemon 0640 compass system +/dev/akm8973_aot 0640 compass system +/dev/bma150 0640 compass system +/dev/cm3602 0640 compass system +/dev/akm8976_pffd 0640 compass system +/dev/lightsensor 0640 system system +/dev/msm_pcm_out* 0660 system audio +/dev/msm_pcm_in* 0660 system audio +/dev/msm_pcm_ctl* 0660 system audio +/dev/msm_snd* 0660 system audio +/dev/msm_mp3* 0660 system audio +/dev/audience_a1026* 0660 system audio +/dev/tpa2018d1* 0660 system audio +/dev/msm_audpre 0660 system audio +/dev/msm_audio_ctl 0660 system audio +/dev/htc-acoustic 0660 system audio +/dev/vdec 0660 system audio +/dev/q6venc 0660 system audio +/dev/snd/dsp 0660 system audio +/dev/snd/dsp1 0660 system audio +/dev/snd/mixer 0660 system audio +/dev/smd0 0640 radio radio +/dev/qmi 0640 radio radio +/dev/qmi0 0640 radio radio +/dev/qmi1 0640 radio radio +/dev/qmi2 0640 radio radio +/dev/bus/usb/* 0660 root usb +/dev/mtp_usb 0660 root mtp +/dev/usb_accessory 0660 root usb +/dev/tun 0660 system vpn + +# CDMA radio interface MUX +/dev/ts0710mux* 0640 radio radio +/dev/ppp 0660 radio vpn + +# sysfs properties +/sys/devices/platform/trusty.* trusty_version 0440 root log +/sys/devices/virtual/input/input* enable 0660 root input +/sys/devices/virtual/input/input* poll_delay 0660 root input +/sys/devices/virtual/usb_composite/* enable 0664 root system +/sys/devices/system/cpu/cpu* cpufreq/scaling_max_freq 0664 system system +/sys/devices/system/cpu/cpu* cpufreq/scaling_min_freq 0664 system system + +# DVB API device nodes +/dev/dvb* 0660 root system + +# These settings are specific to running under the Android emulator +/dev/ttyS* 0666 system system +/proc 0666 system system diff --git a/aosp/system/core/storaged/storaged.rc b/aosp/system/core/storaged/storaged.rc new file mode 100644 index 000000000..250bc635c --- /dev/null +++ b/aosp/system/core/storaged/storaged.rc @@ -0,0 +1,8 @@ +service storaged /system/bin/storaged + class main + #capabilities DAC_READ_SEARCH + priority 10 + file /d/mmc0/mmc0:0001/ext_csd r + writepid /dev/cpuset/system-background/tasks + user root + group package_info diff --git a/aosp/system/hwservicemanager/Android.bp b/aosp/system/hwservicemanager/Android.bp new file mode 100644 index 000000000..981aac8e1 --- /dev/null +++ b/aosp/system/hwservicemanager/Android.bp @@ -0,0 +1,47 @@ +// Copyright (C) 2016 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +cc_binary { + name: "hwservicemanager_orig", + init_rc: [ + "hwservicemanager.rc", + ], + srcs: [ + "AccessControl.cpp", + "HidlService.cpp", + "ServiceManager.cpp", + "service.cpp", + "TokenManager.cpp", + "Vintf.cpp", + ], + cflags: [ + "-Wall", + "-Wextra", + "-Werror", + ], + shared_libs: [ + "android.hidl.token@1.0", + "libbase", + "libcrypto", // for TokenManager + "libcutils", + "libhidlbase", + "libhidltransport", + "libhidl-gen-utils", + "libhwbinder", + "liblog", + "libselinux", + "libutils", + "libvintf", + ], +} diff --git a/aosp/system/libhidl/vintfdata/manifest.xml b/aosp/system/libhidl/vintfdata/manifest.xml new file mode 100644 index 000000000..a13090798 --- /dev/null +++ b/aosp/system/libhidl/vintfdata/manifest.xml @@ -0,0 +1,152 @@ + + + android.hidl.manager + hwbinder + 1.1 + + IServiceManager + default + + + + android.hidl.allocator + hwbinder + 1.0 + + IAllocator + ashmem + + + + android.hidl.memory + passthrough + 1.0 + + IMapper + ashmem + + + + android.hidl.token + hwbinder + 1.0 + + ITokenManager + default + + + + android.frameworks.displayservice + hwbinder + 1.0 + + IDisplayService + default + + + + android.frameworks.schedulerservice + hwbinder + 1.0 + + ISchedulingPolicyService + default + + + + android.frameworks.sensorservice + hwbinder + 1.0 + + ISensorManager + default + + + + android.system.net.netd + hwbinder + 1.1 + + INetd + default + + + + android.system.wifi.keystore + hwbinder + 1.0 + + IKeystore + default + + + + android.hardware.wifi + hwbinder + 1.0 + + IWifi + default + + + + android.hardware.wifi.hostapd + hwbinder + 1.0 + + IHostapd + default + + + + android.hardware.wifi.supplicant + hwbinder + 1.0 + + ISupplicant + default + + + + android.hardware.wifi.offload + hwbinder + 1.0 + + IOffload + default + + + + android.hardware.graphics.composer + hwbinder + 2.1 + + IComposer + vr + + + + android.hardware.health + hwbinder + 2.0 + + IHealth + + backup + + + + netutils-wrapper + + 1.0 + + diff --git a/aosp/system/libhwbinder/Android.bp b/aosp/system/libhwbinder/Android.bp new file mode 100644 index 000000000..8b0926e28 --- /dev/null +++ b/aosp/system/libhwbinder/Android.bp @@ -0,0 +1,108 @@ +// Copyright (C) 2009 The Android Open Source Project +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +subdirs = [ + "vts/performance", +] + +cc_defaults { + name: "libhwbinder_defaults", + shared_libs: [ + "libbase", + "liblog", + "libcutils", + "libutils", + "libselinux", + ], + export_shared_lib_headers: [ + "libbase", + "libutils", + ], + export_include_dirs: ["include"], + include_dirs: ["frameworks/native/include"], + + vendor_available: true, + vndk: { + enabled: true, + support_system_process: true, + }, + clang: true, + sanitize: { + misc_undefined: ["integer"], + }, + srcs: [ + "Binder.cpp", + "BpHwBinder.cpp", + "BufferedTextOutput.cpp", + "Debug.cpp", + "IInterface.cpp", + "IPCThreadState.cpp", + "Parcel.cpp", + "ProcessState.cpp", + "Static.cpp", + "TextOutput.cpp", + ], + + product_variables: { + binder32bit: { + cflags: ["-DBINDER_IPC_32BIT=1"], + }, + }, + + cflags: [ + "-Wall", + "-Werror", + ], +} + +cc_library { + name: "libhwbinder", + defaults: [ + "libhwbinder_defaults", + "hwbinder_pgo", + "hwbinder_lto" + ], +} + +// Explicitly provide a no lto, no PGO variant, to workaround the issue that we +// can't detect non-lto users of the module in Android.mk. +// http://b/77320844 +cc_library { + name: "libhwbinder_noltopgo", + defaults: [ + "libhwbinder_defaults", + ], +} + +// Provide pgo property to build hwbinder with PGO +cc_defaults { + name: "hwbinder_pgo", + pgo: { + instrumentation: true, + profile_file: "hwbinder/hwbinder.profdata", + benchmarks: ["hwbinder"], + enable_profile_use: true, + }, +} +// Provide lto property to build hwbinder with LTO +cc_defaults { + name: "hwbinder_lto", + target: { + android: { + lto: { + thin: true, + }, + }, + }, +} diff --git a/aosp/system/netd/server/Android.mk b/aosp/system/netd/server/Android.mk new file mode 100644 index 000000000..bcbfec081 --- /dev/null +++ b/aosp/system/netd/server/Android.mk @@ -0,0 +1,234 @@ +# Copyright (C) 2014 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +LOCAL_PATH := $(call my-dir) + +### +### netd service AIDL interface. +### +include $(CLEAR_VARS) + +LOCAL_CFLAGS := -Wall -Werror -Wthread-safety +LOCAL_MODULE := libnetdaidl_static +LOCAL_SHARED_LIBRARIES := \ + libbinder \ + libutils +LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/binder +LOCAL_AIDL_INCLUDES := $(LOCAL_PATH)/binder frameworks/native/aidl/binder +LOCAL_C_INCLUDES := $(LOCAL_PATH)/binder +LOCAL_SRC_FILES := \ + binder/android/net/INetd.aidl \ + binder/android/net/UidRange.cpp + +include $(BUILD_STATIC_LIBRARY) + +include $(CLEAR_VARS) + +LOCAL_CFLAGS := -Wall -Werror -Wthread-safety +LOCAL_MODULE := libnetdaidl +LOCAL_SHARED_LIBRARIES := \ + libbinder \ + libutils +LOCAL_WHOLE_STATIC_LIBRARIES := libnetdaidl_static +LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/binder + +include $(BUILD_SHARED_LIBRARY) + +### +### netd daemon. +### +include $(CLEAR_VARS) + +LOCAL_C_INCLUDES := \ + $(call include-path-for, libhardware_legacy)/hardware_legacy \ + bionic/libc/dns/include \ + external/mdnsresponder/mDNSShared \ + system/netd/include \ + +LOCAL_CPPFLAGS := -Wall -Werror -Wthread-safety -Wnullable-to-nonnull-conversion +LOCAL_MODULE := netd_orig + +# Bug: http://b/29823425 Disable -Wvarargs for Clang update to r271374 +LOCAL_CPPFLAGS += -Wno-varargs \ + +ifeq ($(TARGET_ARCH), x86) +ifneq ($(TARGET_PRODUCT), gce_x86_phone) + LOCAL_CPPFLAGS += -D NETLINK_COMPAT32 +endif +endif + +LOCAL_INIT_RC := netd.rc + +LOCAL_SHARED_LIBRARIES := \ + android.system.net.netd@1.0 \ + android.system.net.netd@1.1 \ + libbinder \ + libbpf \ + libcrypto \ + libcutils \ + libdl \ + libhidlbase \ + libhidltransport \ + liblog \ + liblogwrap \ + libmdnssd \ + libnetdaidl \ + libnetutils \ + libnetdutils \ + libselinux \ + libssl \ + libsysutils \ + libbase \ + libutils \ + libpcap \ + libqtaguid \ + +LOCAL_SRC_FILES := \ + BandwidthController.cpp \ + ClatdController.cpp \ + CommandListener.cpp \ + Controllers.cpp \ + DnsProxyListener.cpp \ + DummyNetwork.cpp \ + DumpWriter.cpp \ + EventReporter.cpp \ + FirewallController.cpp \ + FwmarkServer.cpp \ + IdletimerController.cpp \ + InterfaceController.cpp \ + IptablesRestoreController.cpp \ + LocalNetwork.cpp \ + MDnsSdListener.cpp \ + NetdCommand.cpp \ + NetdConstants.cpp \ + NetdHwService.cpp \ + NetdNativeService.cpp \ + NetlinkHandler.cpp \ + NetlinkManager.cpp \ + NetlinkCommands.cpp \ + NetlinkListener.cpp \ + Network.cpp \ + NetworkController.cpp \ + NFLogListener.cpp \ + PhysicalNetwork.cpp \ + PppController.cpp \ + ResolverController.cpp \ + RouteController.cpp \ + SockDiag.cpp \ + StrictController.cpp \ + TetherController.cpp \ + TrafficController.cpp \ + UidRanges.cpp \ + VirtualNetwork.cpp \ + WakeupController.cpp \ + XfrmController.cpp \ + TcpSocketMonitor.cpp \ + main.cpp \ + oem_iptables_hook.cpp \ + binder/android/net/UidRange.cpp \ + binder/android/net/metrics/INetdEventListener.aidl \ + dns/DnsTlsDispatcher.cpp \ + dns/DnsTlsQueryMap.cpp \ + dns/DnsTlsTransport.cpp \ + dns/DnsTlsServer.cpp \ + dns/DnsTlsSessionCache.cpp \ + dns/DnsTlsSocket.cpp \ + +LOCAL_AIDL_INCLUDES := $(LOCAL_PATH)/binder + +include $(BUILD_EXECUTABLE) + + +### +### ndc binary. +### +include $(CLEAR_VARS) + +LOCAL_CFLAGS := -Wall -Werror -Wthread-safety +LOCAL_SANITIZE := unsigned-integer-overflow +LOCAL_CLANG := true +LOCAL_MODULE := ndc +LOCAL_SHARED_LIBRARIES := libcutils +LOCAL_SRC_FILES := ndc.cpp + +include $(BUILD_EXECUTABLE) + +### +### netd unit tests. +### +include $(CLEAR_VARS) +LOCAL_MODULE := netd_unit_test +LOCAL_COMPATIBILITY_SUITE := device-tests +LOCAL_SANITIZE := unsigned-integer-overflow +LOCAL_CFLAGS := -Wall -Werror -Wunused-parameter -Wthread-safety +# Bug: http://b/29823425 Disable -Wvarargs for Clang update to r271374 +LOCAL_CFLAGS += -Wno-varargs + +LOCAL_C_INCLUDES := \ + bionic/libc/dns/include \ + system/netd/include \ + system/netd/server \ + system/netd/server/binder \ + system/netd/tests \ + system/core/logwrapper/include \ + +LOCAL_SRC_FILES := \ + InterfaceController.cpp InterfaceControllerTest.cpp \ + Controllers.cpp ControllersTest.cpp \ + NetdConstants.cpp IptablesBaseTest.cpp \ + IptablesRestoreController.cpp IptablesRestoreControllerTest.cpp \ + BandwidthController.cpp BandwidthControllerTest.cpp \ + FirewallControllerTest.cpp FirewallController.cpp \ + IdletimerController.cpp IdletimerControllerTest.cpp \ + NetlinkCommands.cpp NetlinkManager.cpp \ + RouteController.cpp RouteControllerTest.cpp \ + SockDiagTest.cpp SockDiag.cpp \ + StrictController.cpp StrictControllerTest.cpp \ + TetherController.cpp TetherControllerTest.cpp \ + TrafficController.cpp TrafficControllerTest.cpp \ + XfrmController.cpp XfrmControllerTest.cpp \ + TcpSocketMonitor.cpp \ + UidRanges.cpp \ + NetlinkListener.cpp \ + WakeupController.cpp WakeupControllerTest.cpp \ + NFLogListener.cpp NFLogListenerTest.cpp \ + binder/android/net/UidRange.cpp \ + binder/android/net/metrics/INetdEventListener.aidl \ + ../tests/tun_interface.cpp \ + dns/DnsTlsDispatcher.cpp \ + dns/DnsTlsTransport.cpp \ + dns/DnsTlsServer.cpp \ + dns/DnsTlsSessionCache.cpp \ + dns/DnsTlsSocket.cpp \ + +LOCAL_MODULE_TAGS := tests +LOCAL_STATIC_LIBRARIES := libgmock libpcap +LOCAL_SHARED_LIBRARIES := \ + libbpf \ + libnetdaidl \ + libbase \ + libbinder \ + libcrypto \ + libcutils \ + liblog \ + liblogwrap \ + libnetutils \ + libnetdutils \ + libqtaguid \ + libsysutils \ + libutils \ + libssl \ + +include $(BUILD_NATIVE_TEST) + diff --git a/aosp/system/security/keystore/Android.bp b/aosp/system/security/keystore/Android.bp new file mode 100644 index 000000000..701a63b6b --- /dev/null +++ b/aosp/system/security/keystore/Android.bp @@ -0,0 +1,290 @@ +cc_defaults { + name: "keystore_defaults", + + cflags: [ + "-Wall", + "-Werror", + "-Wextra", + "-Wunused", + ], + + sanitize: { + misc_undefined: ["integer"], + }, + + clang: true, +} + +cc_binary { + name: "keystore_orig", + defaults: ["keystore_defaults"], + + srcs: [ + ":IKeyAttestationApplicationIdProvider.aidl", + "KeyStore.cpp", + "auth_token_table.cpp", + "blob.cpp", + "confirmation_manager.cpp", + "entropy.cpp", + "grant_store.cpp", + "key_config.proto", + "key_proto_handler.cpp", + "key_store_service.cpp", + "keyblob_utils.cpp", + "keymaster_enforcement.cpp", + "keystore_attestation_id.cpp", + "keystore_main.cpp", + "keystore_utils.cpp", + "legacy_keymaster_device_wrapper.cpp", + "operation.cpp", + "operation_config.proto", + "operation_proto_handler.cpp", + "permissions.cpp", + "user_state.cpp", + ], + shared_libs: [ + "android.hardware.confirmationui@1.0", + "android.hardware.keymaster@3.0", + "android.hardware.keymaster@4.0", + "android.system.wifi.keystore@1.0", + "libbase", + "libbinder", + "libcrypto", + "libhardware", + "libhidlbase", + "libhidltransport", + "libhwbinder", + "libkeymaster4support", + "libkeymaster_messages", + "libkeymaster_portable", + "libkeystore_aidl", + "libkeystore_binder", + "libkeystore_parcelables", + "liblog", + "libprotobuf-cpp-lite", + "libselinux", + "libservices", + "libsoftkeymasterdevice", + "libutils", + "libwifikeystorehal", + ], + init_rc: ["keystore.rc"], + aidl: { + include_dirs: ["frameworks/base/core/java/"], + }, + + product_variables: { + pdk: { + enabled: false, + }, + }, + + required: ["keystore_cli_v2"], +} + +cc_binary { + name: "keystore_cli", + defaults: ["keystore_defaults"], + tags: ["debug"], + + srcs: ["keystore_cli.cpp"], + shared_libs: [ + "android.hardware.keymaster@4.0", + "libbinder", + "libcrypto", + "libcutils", + "libhidlbase", + "libhwbinder", + "libkeystore_aidl", // for IKeyStoreService.asInterface() + "libkeystore_binder", + "libkeystore_parcelables", + "liblog", + "libutils", + ], +} + +cc_binary { + name: "keystore_cli_v2", + defaults: ["keystore_defaults"], + tags: ["debug"], + + cflags: [ + "-DKEYMASTER_NAME_TAGS", + "-Wno-unused-parameter", + ], + srcs: ["keystore_cli_v2.cpp"], + shared_libs: [ + "android.hardware.confirmationui@1.0", + "libbinder", + "android.hardware.keymaster@4.0", + "libchrome", + "libutils", + "libhidlbase", + "libhwbinder", + "libkeymaster4support", + "libkeystore_aidl", + "libkeystore_binder", + "libkeystore_parcelables", + ], + + local_include_dirs: ["include"], +} + +cc_library_shared { + name: "libkeystore_parcelables", + defaults: ["keystore_defaults"], + export_include_dirs: ["include"], + srcs: [ + "KeyAttestationApplicationId.cpp", + "KeyAttestationPackageInfo.cpp", + "KeymasterArguments.cpp", + "KeystoreArguments.cpp", + "OperationResult.cpp", + "Signature.cpp", + "keystore_aidl_hidl_marshalling_utils.cpp", + ], + shared_libs: [ + "android.hardware.keymaster@4.0", + "libbinder", + "libhardware", + "libhidlbase", + "libhwbinder", + "libkeymaster4support", + "liblog", + "libprotobuf-cpp-lite", + "libutils", + ], + export_shared_lib_headers: [ + "android.hardware.keymaster@4.0", + "libbinder", + "libhidlbase", + "libhwbinder", + "libkeymaster4support", + ], +} +// Library for keystore clients +cc_library_shared { + name: "libkeystore_binder", + defaults: ["keystore_defaults"], + + srcs: [ + "keyblob_utils.cpp", + "keystore_client.proto", + "keystore_client_impl.cpp", + "keystore_get.cpp", + ], + shared_libs: [ + "android.hardware.keymaster@4.0", + "libbinder", + "libhidlbase", + "libhwbinder", + "libkeymaster4support", + "libkeystore_aidl", + "libkeystore_parcelables", + "liblog", + "libprotobuf-cpp-lite", + "libutils", + ], + + proto: { + type: "lite", + export_proto_headers: true, + }, + aidl: { + export_aidl_headers: true, + include_dirs: ["frameworks/base/core/java/"], + }, + export_include_dirs: ["include"], + export_shared_lib_headers: [ + "android.hardware.keymaster@4.0", + "libbinder", + "libhidlbase", + "libhwbinder", + "libkeystore_aidl", + "libkeystore_parcelables", + ], +} + +// Library for keystore clients using the WiFi HIDL interface +cc_library_shared { + name: "libkeystore-wifi-hidl", + defaults: ["keystore_defaults"], + + srcs: ["keystore_get_wifi_hidl.cpp"], + shared_libs: [ + "android.system.wifi.keystore@1.0", + "libbase", + "libhidlbase", + "libhidltransport", + "liblog", + "libutils", + ], + + export_include_dirs: ["include"], + + vendor: true, +} + +// Library for unit tests +cc_library_static { + name: "libkeystore_test", + defaults: ["keystore_defaults"], + + srcs: [ + "auth_token_table.cpp", + ], + cflags: [ "-O0", ], + static_libs: ["libgtest_main"], + shared_libs: [ + "android.hardware.keymaster@4.0", + "libhidlbase", + "libhwbinder", + "libkeymaster4support", + "libutils", + ], + export_shared_lib_headers: [ + "android.hardware.keymaster@4.0", + "libhidlbase", + "libhwbinder", + "libkeymaster4support", + ], + + export_include_dirs: ["include"], +} + +filegroup { + name: "keystore_aidl", + srcs: [ + "binder/android/security/IConfirmationPromptCallback.aidl", + "binder/android/security/IKeystoreService.aidl", + ], +} + +cc_library_shared { + name: "libkeystore_aidl", + srcs: [":keystore_aidl"], + aidl: { + export_aidl_headers: true, + include_dirs: [ + "system/security/keystore/binder", + ], + }, + shared_libs: [ + "libbinder", + "libcutils", + "libhardware", + "libhidlbase", + "libhidltransport", + "libhwbinder", + "libkeystore_parcelables", + "liblog", + "libselinux", + "libutils", + ], + export_shared_lib_headers: [ + "libbinder", + "libkeystore_parcelables", + ], +} + +subdirs = ["tests"] diff --git a/aosp/system/sepolicy/prebuilts/api/26.0/private/service_contexts b/aosp/system/sepolicy/prebuilts/api/26.0/private/service_contexts new file mode 100644 index 000000000..f2b0b38ea --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/26.0/private/service_contexts @@ -0,0 +1,176 @@ +accessibility u:object_r:accessibility_service:s0 +account u:object_r:account_service:s0 +activity u:object_r:activity_service:s0 +alarm u:object_r:alarm_service:s0 +android.os.UpdateEngineService u:object_r:update_engine_service:s0 +android.security.keystore u:object_r:keystore_service:s0 +android.service.gatekeeper.IGateKeeperService u:object_r:gatekeeper_service:s0 +appops u:object_r:appops_service:s0 +appwidget u:object_r:appwidget_service:s0 +assetatlas u:object_r:assetatlas_service:s0 +audio u:object_r:audio_service:s0 +autofill u:object_r:autofill_service:s0 +backup u:object_r:backup_service:s0 +batteryproperties u:object_r:batteryproperties_service:s0 +batterystats u:object_r:batterystats_service:s0 +battery u:object_r:battery_service:s0 +bluetooth_manager u:object_r:bluetooth_manager_service:s0 +bluetooth u:object_r:bluetooth_service:s0 +carrier_config u:object_r:radio_service:s0 +clipboard u:object_r:clipboard_service:s0 +com.android.net.IProxyService u:object_r:IProxyService_service:s0 +commontime_management u:object_r:commontime_management_service:s0 +common_time.clock u:object_r:mediaserver_service:s0 +common_time.config u:object_r:mediaserver_service:s0 +companiondevice u:object_r:companion_device_service:s0 +connectivity u:object_r:connectivity_service:s0 +connmetrics u:object_r:connmetrics_service:s0 +consumer_ir u:object_r:consumer_ir_service:s0 +content u:object_r:content_service:s0 +contexthub u:object_r:contexthub_service:s0 +country_detector u:object_r:country_detector_service:s0 +coverage u:object_r:coverage_service:s0 +cpuinfo u:object_r:cpuinfo_service:s0 +dbinfo u:object_r:dbinfo_service:s0 +device_policy u:object_r:device_policy_service:s0 +device_identifiers u:object_r:device_identifiers_service:s0 +deviceidle u:object_r:deviceidle_service:s0 +devicestoragemonitor u:object_r:devicestoragemonitor_service:s0 +diskstats u:object_r:diskstats_service:s0 +display.qservice u:object_r:surfaceflinger_service:s0 +display u:object_r:display_service:s0 +netd_listener u:object_r:netd_listener_service:s0 +DockObserver u:object_r:DockObserver_service:s0 +dreams u:object_r:dreams_service:s0 +drm.drmManager u:object_r:drmserver_service:s0 +dropbox u:object_r:dropbox_service:s0 +dumpstate u:object_r:dumpstate_service:s0 +econtroller u:object_r:radio_service:s0 +ethernet u:object_r:ethernet_service:s0 +fingerprint u:object_r:fingerprint_service:s0 +font u:object_r:font_service:s0 +android.hardware.fingerprint.IFingerprintDaemon u:object_r:fingerprintd_service:s0 +gfxinfo u:object_r:gfxinfo_service:s0 +graphicsstats u:object_r:graphicsstats_service:s0 +gpu u:object_r:gpu_service:s0 +hardware u:object_r:hardware_service:s0 +hardware_properties u:object_r:hardware_properties_service:s0 +hdmi_control u:object_r:hdmi_control_service:s0 +incident u:object_r:incident_service:s0 +inputflinger u:object_r:inputflinger_service:s0 +input_method u:object_r:input_method_service:s0 +input u:object_r:input_service:s0 +installd u:object_r:installd_service:s0 +iphonesubinfo_msim u:object_r:radio_service:s0 +iphonesubinfo2 u:object_r:radio_service:s0 +iphonesubinfo u:object_r:radio_service:s0 +ims u:object_r:radio_service:s0 +imms u:object_r:imms_service:s0 +ipsec u:object_r:ipsec_service:s0 +isms_msim u:object_r:radio_service:s0 +isms2 u:object_r:radio_service:s0 +isms u:object_r:radio_service:s0 +isub u:object_r:radio_service:s0 +jobscheduler u:object_r:jobscheduler_service:s0 +launcherapps u:object_r:launcherapps_service:s0 +location u:object_r:location_service:s0 +lock_settings u:object_r:lock_settings_service:s0 +media.aaudio u:object_r:audioserver_service:s0 +media.audio_flinger u:object_r:audioserver_service:s0 +media.audio_policy u:object_r:audioserver_service:s0 +media.camera u:object_r:cameraserver_service:s0 +media.camera.proxy u:object_r:cameraproxy_service:s0 +media.log u:object_r:audioserver_service:s0 +media.player u:object_r:mediaserver_service:s0 +media.metrics u:object_r:mediametrics_service:s0 +media.extractor u:object_r:mediaextractor_service:s0 +media.codec u:object_r:mediacodec_service:s0 +media.resource_manager u:object_r:mediaserver_service:s0 +media.radio u:object_r:audioserver_service:s0 +media.sound_trigger_hw u:object_r:audioserver_service:s0 +media.drm u:object_r:mediadrmserver_service:s0 +media.cas u:object_r:mediacasserver_service:s0 +media_projection u:object_r:media_projection_service:s0 +media_resource_monitor u:object_r:media_session_service:s0 +media_router u:object_r:media_router_service:s0 +media_session u:object_r:media_session_service:s0 +meminfo u:object_r:meminfo_service:s0 +midi u:object_r:midi_service:s0 +mount u:object_r:mount_service:s0 +netd u:object_r:netd_service:s0 +netpolicy u:object_r:netpolicy_service:s0 +netstats u:object_r:netstats_service:s0 +network_management u:object_r:network_management_service:s0 +network_score u:object_r:network_score_service:s0 +network_time_update_service u:object_r:network_time_update_service:s0 +nfc u:object_r:nfc_service:s0 +notification u:object_r:notification_service:s0 +oem_lock u:object_r:oem_lock_service:s0 +otadexopt u:object_r:otadexopt_service:s0 +overlay u:object_r:overlay_service:s0 +package u:object_r:package_service:s0 +permission u:object_r:permission_service:s0 +persistent_data_block u:object_r:persistent_data_block_service:s0 +phone_msim u:object_r:radio_service:s0 +phone1 u:object_r:radio_service:s0 +phone2 u:object_r:radio_service:s0 +phone u:object_r:radio_service:s0 +pinner u:object_r:pinner_service:s0 +power u:object_r:power_service:s0 +print u:object_r:print_service:s0 +processinfo u:object_r:processinfo_service:s0 +procstats u:object_r:procstats_service:s0 +radio.phonesubinfo u:object_r:radio_service:s0 +radio.phone u:object_r:radio_service:s0 +radio.sms u:object_r:radio_service:s0 +recovery u:object_r:recovery_service:s0 +restrictions u:object_r:restrictions_service:s0 +rttmanager u:object_r:rttmanager_service:s0 +samplingprofiler u:object_r:samplingprofiler_service:s0 +scheduling_policy u:object_r:scheduling_policy_service:s0 +search u:object_r:search_service:s0 +sec_key_att_app_id_provider u:object_r:sec_key_att_app_id_provider_service:s0 +sensorservice u:object_r:sensorservice_service:s0 +serial u:object_r:serial_service:s0 +servicediscovery u:object_r:servicediscovery_service:s0 +settings u:object_r:settings_service:s0 +shortcut u:object_r:shortcut_service:s0 +simphonebook_msim u:object_r:radio_service:s0 +simphonebook2 u:object_r:radio_service:s0 +simphonebook u:object_r:radio_service:s0 +sip u:object_r:radio_service:s0 +soundtrigger u:object_r:voiceinteraction_service:s0 +statusbar u:object_r:statusbar_service:s0 +storaged u:object_r:storaged_service:s0 +storaged_pri u:object_r:storaged_service:s0 +storagestats u:object_r:storagestats_service:s0 +SurfaceFlinger u:object_r:surfaceflinger_service:s0 +task u:object_r:task_service:s0 +telecom u:object_r:telecom_service:s0 +telephony.registry u:object_r:registry_service:s0 +textclassification u:object_r:textclassification_service:s0 +textservices u:object_r:textservices_service:s0 +trust u:object_r:trust_service:s0 +tv_input u:object_r:tv_input_service:s0 +uimode u:object_r:uimode_service:s0 +updatelock u:object_r:updatelock_service:s0 +usagestats u:object_r:usagestats_service:s0 +usb u:object_r:usb_service:s0 +user u:object_r:user_service:s0 +vibrator u:object_r:vibrator_service:s0 +virtual_touchpad u:object_r:virtual_touchpad_service:s0 +voiceinteraction u:object_r:voiceinteraction_service:s0 +vr_hwc u:object_r:vr_hwc_service:s0 +vrmanager u:object_r:vr_manager_service:s0 +wallpaper u:object_r:wallpaper_service:s0 +webviewupdate u:object_r:webviewupdate_service:s0 +wifip2p u:object_r:wifip2p_service:s0 +wifiscanner u:object_r:wifiscanner_service:s0 +wifi u:object_r:wifi_service:s0 +wificond u:object_r:wificond_service:s0 +wifiaware u:object_r:wifiaware_service:s0 +window u:object_r:window_service:s0 +cph_performance u:object_r:activity_service:s0 +phoneadjust u:object_r:activity_service:s0 +attributes u:object_r:activity_service:s0 +* u:object_r:default_android_service:s0 diff --git a/aosp/system/sepolicy/prebuilts/api/27.0/private/compat/26.0/26.0.ignore.cil b/aosp/system/sepolicy/prebuilts/api/27.0/private/compat/26.0/26.0.ignore.cil new file mode 100644 index 000000000..b0dbea0ba --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/27.0/private/compat/26.0/26.0.ignore.cil @@ -0,0 +1,34 @@ +;; new_objects - a collection of types that have been introduced that have no +;; analogue in older policy. Thus, we do not need to map these types to +;; previous ones. Add here to pass checkapi tests. +(typeattribute new_objects) +(typeattributeset new_objects + ( adbd_exec + broadcastradio_service + e2fs + e2fs_exec + hal_broadcastradio_hwservice + hal_cas_hwservice + hal_neuralnetworks_hwservice + hal_tetheroffload_hwservice + hal_wifi_offload_hwservice + kmsg_debug_device + mediaprovider_tmpfs + netd_stable_secret_prop + package_native_service + sysfs_fs_ext4_features + system_net_netd_hwservice + thermal_service + thermalcallback_hwservice + thermalserviced + thermalserviced_exec + thermalserviced_tmpfs + timezone_service + tombstoned_java_trace_socket)) + +;; private_objects - a collection of types that were labeled differently in +;; older policy, but that should not remain accessible to vendor policy. +;; Thus, these types are also not mapped, but recorded for checkapi tests +(typeattribute priv_objects) +(typeattributeset priv_objects + ( adbd_tmpfs exagear_debug_file )) diff --git a/aosp/system/sepolicy/prebuilts/api/27.0/private/service_contexts b/aosp/system/sepolicy/prebuilts/api/27.0/private/service_contexts new file mode 100644 index 000000000..95e5e69f5 --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/27.0/private/service_contexts @@ -0,0 +1,177 @@ +accessibility u:object_r:accessibility_service:s0 +account u:object_r:account_service:s0 +activity u:object_r:activity_service:s0 +alarm u:object_r:alarm_service:s0 +android.os.UpdateEngineService u:object_r:update_engine_service:s0 +android.security.keystore u:object_r:keystore_service:s0 +android.service.gatekeeper.IGateKeeperService u:object_r:gatekeeper_service:s0 +appops u:object_r:appops_service:s0 +appwidget u:object_r:appwidget_service:s0 +assetatlas u:object_r:assetatlas_service:s0 +audio u:object_r:audio_service:s0 +autofill u:object_r:autofill_service:s0 +backup u:object_r:backup_service:s0 +batteryproperties u:object_r:batteryproperties_service:s0 +batterystats u:object_r:batterystats_service:s0 +battery u:object_r:battery_service:s0 +bluetooth_manager u:object_r:bluetooth_manager_service:s0 +bluetooth u:object_r:bluetooth_service:s0 +broadcastradio u:object_r:broadcastradio_service:s0 +carrier_config u:object_r:radio_service:s0 +clipboard u:object_r:clipboard_service:s0 +com.android.net.IProxyService u:object_r:IProxyService_service:s0 +commontime_management u:object_r:commontime_management_service:s0 +common_time.clock u:object_r:mediaserver_service:s0 +common_time.config u:object_r:mediaserver_service:s0 +companiondevice u:object_r:companion_device_service:s0 +connectivity u:object_r:connectivity_service:s0 +connmetrics u:object_r:connmetrics_service:s0 +consumer_ir u:object_r:consumer_ir_service:s0 +content u:object_r:content_service:s0 +contexthub u:object_r:contexthub_service:s0 +country_detector u:object_r:country_detector_service:s0 +coverage u:object_r:coverage_service:s0 +cpuinfo u:object_r:cpuinfo_service:s0 +dbinfo u:object_r:dbinfo_service:s0 +device_policy u:object_r:device_policy_service:s0 +device_identifiers u:object_r:device_identifiers_service:s0 +deviceidle u:object_r:deviceidle_service:s0 +devicestoragemonitor u:object_r:devicestoragemonitor_service:s0 +diskstats u:object_r:diskstats_service:s0 +display.qservice u:object_r:surfaceflinger_service:s0 +display u:object_r:display_service:s0 +netd_listener u:object_r:netd_listener_service:s0 +DockObserver u:object_r:DockObserver_service:s0 +dreams u:object_r:dreams_service:s0 +drm.drmManager u:object_r:drmserver_service:s0 +dropbox u:object_r:dropbox_service:s0 +dumpstate u:object_r:dumpstate_service:s0 +econtroller u:object_r:radio_service:s0 +ethernet u:object_r:ethernet_service:s0 +fingerprint u:object_r:fingerprint_service:s0 +font u:object_r:font_service:s0 +android.hardware.fingerprint.IFingerprintDaemon u:object_r:fingerprintd_service:s0 +gfxinfo u:object_r:gfxinfo_service:s0 +graphicsstats u:object_r:graphicsstats_service:s0 +gpu u:object_r:gpu_service:s0 +hardware u:object_r:hardware_service:s0 +hardware_properties u:object_r:hardware_properties_service:s0 +hdmi_control u:object_r:hdmi_control_service:s0 +incident u:object_r:incident_service:s0 +inputflinger u:object_r:inputflinger_service:s0 +input_method u:object_r:input_method_service:s0 +input u:object_r:input_service:s0 +installd u:object_r:installd_service:s0 +iphonesubinfo_msim u:object_r:radio_service:s0 +iphonesubinfo2 u:object_r:radio_service:s0 +iphonesubinfo u:object_r:radio_service:s0 +ims u:object_r:radio_service:s0 +imms u:object_r:imms_service:s0 +ipsec u:object_r:ipsec_service:s0 +isms_msim u:object_r:radio_service:s0 +isms2 u:object_r:radio_service:s0 +isms u:object_r:radio_service:s0 +isub u:object_r:radio_service:s0 +jobscheduler u:object_r:jobscheduler_service:s0 +launcherapps u:object_r:launcherapps_service:s0 +location u:object_r:location_service:s0 +lock_settings u:object_r:lock_settings_service:s0 +media.aaudio u:object_r:audioserver_service:s0 +media.audio_flinger u:object_r:audioserver_service:s0 +media.audio_policy u:object_r:audioserver_service:s0 +media.camera u:object_r:cameraserver_service:s0 +media.camera.proxy u:object_r:cameraproxy_service:s0 +media.log u:object_r:audioserver_service:s0 +media.player u:object_r:mediaserver_service:s0 +media.metrics u:object_r:mediametrics_service:s0 +media.extractor u:object_r:mediaextractor_service:s0 +media.codec u:object_r:mediacodec_service:s0 +media.resource_manager u:object_r:mediaserver_service:s0 +media.sound_trigger_hw u:object_r:audioserver_service:s0 +media.drm u:object_r:mediadrmserver_service:s0 +media_projection u:object_r:media_projection_service:s0 +media_resource_monitor u:object_r:media_session_service:s0 +media_router u:object_r:media_router_service:s0 +media_session u:object_r:media_session_service:s0 +meminfo u:object_r:meminfo_service:s0 +midi u:object_r:midi_service:s0 +mount u:object_r:mount_service:s0 +netd u:object_r:netd_service:s0 +netpolicy u:object_r:netpolicy_service:s0 +netstats u:object_r:netstats_service:s0 +network_management u:object_r:network_management_service:s0 +network_score u:object_r:network_score_service:s0 +network_time_update_service u:object_r:network_time_update_service:s0 +nfc u:object_r:nfc_service:s0 +notification u:object_r:notification_service:s0 +oem_lock u:object_r:oem_lock_service:s0 +otadexopt u:object_r:otadexopt_service:s0 +overlay u:object_r:overlay_service:s0 +package u:object_r:package_service:s0 +package_native u:object_r:package_native_service:s0 +permission u:object_r:permission_service:s0 +persistent_data_block u:object_r:persistent_data_block_service:s0 +phone_msim u:object_r:radio_service:s0 +phone1 u:object_r:radio_service:s0 +phone2 u:object_r:radio_service:s0 +phone u:object_r:radio_service:s0 +pinner u:object_r:pinner_service:s0 +power u:object_r:power_service:s0 +print u:object_r:print_service:s0 +processinfo u:object_r:processinfo_service:s0 +procstats u:object_r:procstats_service:s0 +radio.phonesubinfo u:object_r:radio_service:s0 +radio.phone u:object_r:radio_service:s0 +radio.sms u:object_r:radio_service:s0 +recovery u:object_r:recovery_service:s0 +restrictions u:object_r:restrictions_service:s0 +rttmanager u:object_r:rttmanager_service:s0 +samplingprofiler u:object_r:samplingprofiler_service:s0 +scheduling_policy u:object_r:scheduling_policy_service:s0 +search u:object_r:search_service:s0 +sec_key_att_app_id_provider u:object_r:sec_key_att_app_id_provider_service:s0 +sensorservice u:object_r:sensorservice_service:s0 +serial u:object_r:serial_service:s0 +servicediscovery u:object_r:servicediscovery_service:s0 +settings u:object_r:settings_service:s0 +shortcut u:object_r:shortcut_service:s0 +simphonebook_msim u:object_r:radio_service:s0 +simphonebook2 u:object_r:radio_service:s0 +simphonebook u:object_r:radio_service:s0 +sip u:object_r:radio_service:s0 +soundtrigger u:object_r:voiceinteraction_service:s0 +statusbar u:object_r:statusbar_service:s0 +storaged u:object_r:storaged_service:s0 +storagestats u:object_r:storagestats_service:s0 +SurfaceFlinger u:object_r:surfaceflinger_service:s0 +task u:object_r:task_service:s0 +telecom u:object_r:telecom_service:s0 +telephony.registry u:object_r:registry_service:s0 +textclassification u:object_r:textclassification_service:s0 +textservices u:object_r:textservices_service:s0 +timezone u:object_r:timezone_service:s0 +thermalservice u:object_r:thermal_service:s0 +trust u:object_r:trust_service:s0 +tv_input u:object_r:tv_input_service:s0 +uimode u:object_r:uimode_service:s0 +updatelock u:object_r:updatelock_service:s0 +usagestats u:object_r:usagestats_service:s0 +usb u:object_r:usb_service:s0 +user u:object_r:user_service:s0 +vibrator u:object_r:vibrator_service:s0 +virtual_touchpad u:object_r:virtual_touchpad_service:s0 +voiceinteraction u:object_r:voiceinteraction_service:s0 +vr_hwc u:object_r:vr_hwc_service:s0 +vrmanager u:object_r:vr_manager_service:s0 +wallpaper u:object_r:wallpaper_service:s0 +webviewupdate u:object_r:webviewupdate_service:s0 +wifip2p u:object_r:wifip2p_service:s0 +wifiscanner u:object_r:wifiscanner_service:s0 +wifi u:object_r:wifi_service:s0 +wificond u:object_r:wificond_service:s0 +wifiaware u:object_r:wifiaware_service:s0 +window u:object_r:window_service:s0 +cph_performance u:object_r:activity_service:s0 +phoneadjust u:object_r:activity_service:s0 +attributes u:object_r:activity_service:s0 +* u:object_r:default_android_service:s0 diff --git a/aosp/system/sepolicy/prebuilts/api/28.0/private/app_neverallows.te b/aosp/system/sepolicy/prebuilts/api/28.0/private/app_neverallows.te new file mode 100644 index 000000000..3ac36c9c9 --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/28.0/private/app_neverallows.te @@ -0,0 +1,263 @@ +### +### neverallow rules for untrusted app domains +### + +define(`all_untrusted_apps',`{ + ephemeral_app + isolated_app + mediaprovider + untrusted_app + untrusted_app_25 + untrusted_app_27 + untrusted_app_all + untrusted_v2_app +}') +# Receive or send uevent messages. +neverallow all_untrusted_apps domain:netlink_kobject_uevent_socket *; + +# Receive or send generic netlink messages +neverallow all_untrusted_apps domain:netlink_socket *; + +# Too much leaky information in debugfs. It's a security +# best practice to ensure these files aren't readable. +neverallow all_untrusted_apps debugfs_type:file read; + +# Do not allow untrusted apps to register services. +# Only trusted components of Android should be registering +# services. +neverallow all_untrusted_apps service_manager_type:service_manager add; + +# Do not allow untrusted apps to use VendorBinder +neverallow all_untrusted_apps vndbinder_device:chr_file *; +neverallow all_untrusted_apps vndservice_manager_type:service_manager *; + +# Do not allow untrusted apps to connect to the property service +# or set properties. b/10243159 +neverallow { all_untrusted_apps -mediaprovider } property_socket:sock_file write; +neverallow { all_untrusted_apps -mediaprovider } init:unix_stream_socket connectto; +neverallow { all_untrusted_apps -mediaprovider } property_type:property_service set; + +# net.dns properties are not a public API. Temporarily exempt pre-Oreo apps, +# but otherwise disallow untrusted apps from reading this property. +neverallow { all_untrusted_apps -untrusted_app_25 } net_dns_prop:file read; + +# Do not allow untrusted apps to be assigned mlstrustedsubject. +# This would undermine the per-user isolation model being +# enforced via levelFrom=user in seapp_contexts and the mls +# constraints. As there is no direct way to specify a neverallow +# on attribute assignment, this relies on the fact that fork +# permission only makes sense within a domain (hence should +# never be granted to any other domain within mlstrustedsubject) +# and an untrusted app is allowed fork permission to itself. +neverallow all_untrusted_apps mlstrustedsubject:process fork; + +# Do not allow untrusted apps to hard link to any files. +# In particular, if an untrusted app links to other app data +# files, installd will not be able to guarantee the deletion +# of the linked to file. Hard links also contribute to security +# bugs, so we want to ensure untrusted apps never have this +# capability. +neverallow all_untrusted_apps file_type:file link; + +# Do not allow untrusted apps to access network MAC address file +neverallow all_untrusted_apps sysfs_mac_address:file no_rw_file_perms; + +# Do not allow any write access to files in /sys +neverallow all_untrusted_apps sysfs_type:file { no_w_file_perms no_x_file_perms }; + +# Apps may never access the default sysfs label. +neverallow all_untrusted_apps sysfs:file no_rw_file_perms; + +# Restrict socket ioctls. Either 1. disallow privileged ioctls, 2. disallow the +# ioctl permission, or 3. disallow the socket class. +neverallowxperm all_untrusted_apps domain:{ rawip_socket tcp_socket udp_socket } ioctl priv_sock_ioctls; +neverallow all_untrusted_apps *:{ netlink_route_socket netlink_selinux_socket } ioctl; +neverallow all_untrusted_apps *:{ + socket netlink_socket packet_socket key_socket appletalk_socket + netlink_tcpdiag_socket netlink_nflog_socket + netlink_xfrm_socket netlink_audit_socket + netlink_dnrt_socket netlink_kobject_uevent_socket tun_socket + netlink_iscsi_socket netlink_fib_lookup_socket netlink_connector_socket + netlink_netfilter_socket netlink_generic_socket netlink_scsitransport_socket + netlink_rdma_socket netlink_crypto_socket +} *; + +# Do not allow untrusted apps access to /cache +neverallow { all_untrusted_apps -mediaprovider } { cache_file cache_recovery_file }:dir ~{ r_dir_perms }; +neverallow { all_untrusted_apps -mediaprovider } { cache_file cache_recovery_file }:file ~{ read getattr }; + +# Do not allow untrusted apps to create/unlink files outside of its sandbox, +# internal storage or sdcard. +# World accessible data locations allow application to fill the device +# with unaccounted for data. This data will not get removed during +# application un-installation. +neverallow { all_untrusted_apps -mediaprovider } { + fs_type + -sdcard_type + file_type + -app_data_file # The apps sandbox itself + -media_rw_data_file # Internal storage. Known that apps can + # leave artfacts here after uninstall. + -user_profile_data_file # Access to profile files + userdebug_or_eng(` + -method_trace_data_file # only on ro.debuggable=1 + -coredump_file # userdebug/eng only + -exagear_debug_file # userdebug/eng only + ') +}:dir_file_class_set { create unlink }; + +# No untrusted component should be touching /dev/fuse +neverallow all_untrusted_apps fuse_device:chr_file *; + +# Do not allow untrusted apps to directly open tun_device +neverallow all_untrusted_apps tun_device:chr_file open; + +# Only allow appending to /data/anr/traces.txt (b/27853304, b/18340553) +neverallow all_untrusted_apps anr_data_file:file ~{ open append }; +neverallow all_untrusted_apps anr_data_file:dir ~search; + +# Avoid reads from generically labeled /proc files +# Create a more specific label if needed +neverallow all_untrusted_apps { + proc + proc_asound + proc_filesystems + proc_kmsg + proc_loadavg + proc_mounts + proc_pagetypeinfo + proc_stat + proc_swaps + proc_uptime + proc_version + proc_vmallocinfo + proc_vmstat +}:file { no_rw_file_perms no_x_file_perms }; + +# Avoid all access to kernel configuration +neverallow all_untrusted_apps config_gz:file { no_rw_file_perms no_x_file_perms }; + +# Do not allow untrusted apps access to preloads data files +neverallow all_untrusted_apps preloads_data_file:file no_rw_file_perms; + +# Locking of files on /system could lead to denial of service attacks +# against privileged system components +neverallow all_untrusted_apps system_file:file lock; + +# Do not permit untrusted apps to perform actions on HwBinder service_manager +# other than find actions for services listed below +neverallow all_untrusted_apps *:hwservice_manager ~find; + +# Do not permit access from apps which host arbitrary code to HwBinder services, +# except those considered sufficiently safe for access from such apps. +# The two main reasons for this are: +# 1. HwBinder servers do not perform client authentication because HIDL +# currently does not expose caller UID information and, even if it did, many +# HwBinder services either operate at a level below that of apps (e.g., HALs) +# or must not rely on app identity for authorization. Thus, to be safe, the +# default assumption is that every HwBinder service treats all its clients as +# equally authorized to perform operations offered by the service. +# 2. HAL servers (a subset of HwBinder services) contain code with higher +# incidence rate of security issues than system/core components and have +# access to lower layes of the stack (all the way down to hardware) thus +# increasing opportunities for bypassing the Android security model. +# +# Safe services include: +# - same process services: because they by definition run in the process +# of the client and thus have the same access as the client domain in which +# the process runs +# - coredomain_hwservice: are considered safe because they do not pose risks +# associated with reason #2 above. +# - hal_configstore_ISurfaceFlingerConfigs: becuase it has specifically been +# designed for use by any domain. +# - hal_graphics_allocator_hwservice: because these operations are also offered +# by surfaceflinger Binder service, which apps are permitted to access +# - hal_omx_hwservice: because this is a HwBinder version of the mediacodec +# Binder service which apps were permitted to access. +# - hal_codec2_hwservice: because this is a newer version of hal_omx_hwservice. +neverallow all_untrusted_apps { + hwservice_manager_type + -same_process_hwservice + -coredomain_hwservice + -hal_codec2_hwservice + -hal_configstore_ISurfaceFlingerConfigs + -hal_graphics_allocator_hwservice + -hal_omx_hwservice + -hal_cas_hwservice + -hal_neuralnetworks_hwservice + -untrusted_app_visible_hwservice +}:hwservice_manager find; + +# Make sure that the following services are never accessible by untrusted_apps +neverallow all_untrusted_apps { + default_android_hwservice + hal_audio_hwservice + hal_authsecret_hwservice + hal_bluetooth_hwservice + hal_bootctl_hwservice + hal_camera_hwservice + hal_confirmationui_hwservice + hal_contexthub_hwservice + hal_drm_hwservice + hal_dumpstate_hwservice + hal_fingerprint_hwservice + hal_gatekeeper_hwservice + hal_gnss_hwservice + hal_graphics_composer_hwservice + hal_health_hwservice + hal_ir_hwservice + hal_keymaster_hwservice + hal_light_hwservice + hal_memtrack_hwservice + hal_nfc_hwservice + hal_oemlock_hwservice + hal_power_hwservice + hal_secure_element_hwservice + hal_sensors_hwservice + hal_telephony_hwservice + hal_thermal_hwservice + hal_tv_cec_hwservice + hal_tv_input_hwservice + hal_usb_hwservice + hal_vibrator_hwservice + hal_vr_hwservice + hal_weaver_hwservice + hal_wifi_hwservice + hal_wifi_offload_hwservice + hal_wifi_supplicant_hwservice + hidl_base_hwservice + system_net_netd_hwservice + thermalcallback_hwservice +}:hwservice_manager find; +# HwBinder services offered by core components (as opposed to vendor components) +# are considered somewhat safer due to point #2 above. +neverallow all_untrusted_apps { + coredomain_hwservice + -same_process_hwservice + -hidl_allocator_hwservice # Designed for use by any domain + -hidl_manager_hwservice # Designed for use by any domain + -hidl_memory_hwservice # Designed for use by any domain + -hidl_token_hwservice # Designed for use by any domain +}:hwservice_manager find; + +# SELinux is not an API for untrusted apps to use +neverallow all_untrusted_apps selinuxfs:file no_rw_file_perms; + +# Restrict *Binder access from apps to HAL domains. We can only do this on full +# Treble devices where *Binder communications between apps and HALs are tightly +# restricted. +full_treble_only(` + neverallow all_untrusted_apps { + halserverdomain + -coredomain + -hal_configstore_server + -hal_graphics_allocator_server + -hal_cas_server + -hal_neuralnetworks_server + -binder_in_vendor_violators # TODO(b/35870313): Remove once all violations are gone + -untrusted_app_visible_halserver + }:binder { call transfer }; +') + +# Untrusted apps are not allowed to find mediaextractor update service. +neverallow all_untrusted_apps mediaextractor_update_service:service_manager find; diff --git a/aosp/system/sepolicy/prebuilts/api/28.0/private/compat/26.0/26.0.ignore.cil b/aosp/system/sepolicy/prebuilts/api/28.0/private/compat/26.0/26.0.ignore.cil new file mode 100644 index 000000000..5ce0b4013 --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/28.0/private/compat/26.0/26.0.ignore.cil @@ -0,0 +1,158 @@ +;; new_objects - a collection of types that have been introduced that have no +;; analogue in older policy. Thus, we do not need to map these types to +;; previous ones. Add here to pass checkapi tests. +(typeattribute new_objects) +(typeattributeset new_objects + ( adbd_exec + atrace + binder_calls_stats_service + bootloader_boot_reason_prop + blank_screen + blank_screen_exec + blank_screen_tmpfs + bluetooth_a2dp_offload_prop + bpfloader + bpfloader_exec + broadcastradio_service + cgroup_bpf + crossprofileapps_service + ctl_interface_restart_prop + ctl_interface_start_prop + ctl_interface_stop_prop + ctl_sigstop_prop + e2fs + e2fs_exec + exfat + exported_bluetooth_prop + exported_config_prop + exported_dalvik_prop + exported_default_prop + exported_dumpstate_prop + exported_ffs_prop + exported_fingerprint_prop + exported_overlay_prop + exported_pm_prop + exported_radio_prop + exported_secure_prop + exported_system_prop + exported_system_radio_prop + exported_vold_prop + exported_wifi_prop + exported2_config_prop + exported2_default_prop + exported2_radio_prop + exported2_system_prop + exported2_vold_prop + exported3_default_prop + exported3_radio_prop + exported3_system_prop + fingerprint_vendor_data_file + fs_bpf + hal_audiocontrol_hwservice + hal_authsecret_hwservice + hal_broadcastradio_hwservice + hal_cas_hwservice + hal_codec2_hwservice + hal_confirmationui_hwservice + hal_evs_hwservice + hal_lowpan_hwservice + hal_neuralnetworks_hwservice + hal_secure_element_hwservice + hal_tetheroffload_hwservice + hal_wifi_hostapd_hwservice + hal_usb_gadget_hwservice + hal_vehicle_hwservice + hal_wifi_offload_hwservice + incident_helper + incident_helper_exec + kmsg_debug_device + last_boot_reason_prop + lowpan_device + lowpan_prop + lowpan_service + mediaextractor_update_service + mediaprovider_tmpfs + metadata_file + mnt_vendor_file + netd_stable_secret_prop + network_watchlist_data_file + network_watchlist_service + package_native_service + perfetto + perfetto_exec + perfetto_tmpfs + perfetto_traces_data_file + perfprofd_service + property_info + secure_element + secure_element_device + secure_element_tmpfs + secure_element_service + slice_service + stats + stats_data_file + stats_exec + stats_service + statsd + statsd_exec + statsd_tmpfs + statsdw + statsdw_socket + statscompanion_service + storaged_data_file + sysfs_fs_ext4_features + system_boot_reason_prop + system_net_netd_hwservice + system_update_service + test_boot_reason_prop + thermal_service + thermalcallback_hwservice + thermalserviced + thermalserviced_exec + thermalserviced_tmpfs + timezone_service + tombstoned_java_trace_socket + tombstone_wifi_data_file + trace_data_file + traceur_app + traceur_app_tmpfs + traced + traced_consumer_socket + traced_enabled_prop + traced_exec + traced_probes + traced_probes_exec + traced_probes_tmpfs + traced_producer_socket + traced_tmpfs + untrusted_app_all_devpts + update_engine_log_data_file + vendor_default_prop + vendor_security_patch_level_prop + usbd + usbd_exec + usbd_tmpfs + vendor_init + vendor_shell + vold_metadata_file + vold_prepare_subdirs + vold_prepare_subdirs_exec + vold_service + wait_for_keymaster + wait_for_keymaster_exec + wait_for_keymaster_tmpfs + wpantund + wpantund_exec + wpantund_service + wpantund_tmpfs + wm_trace_data_file)) + +;; private_objects - a collection of types that were labeled differently in +;; older policy, but that should not remain accessible to vendor policy. +;; Thus, these types are also not mapped, but recorded for checkapi tests +(typeattribute priv_objects) +(typeattributeset priv_objects + ( adbd_tmpfs + exagear_debug_file + untrusted_app_27_tmpfs + )) diff --git a/aosp/system/sepolicy/prebuilts/api/28.0/private/compat/27.0/27.0.ignore.cil b/aosp/system/sepolicy/prebuilts/api/28.0/private/compat/27.0/27.0.ignore.cil new file mode 100644 index 000000000..61a7569ec --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/28.0/private/compat/27.0/27.0.ignore.cil @@ -0,0 +1,132 @@ +;; new_objects - a collection of types that have been introduced that have no +;; analogue in older policy. Thus, we do not need to map these types to +;; previous ones. Add here to pass checkapi tests. +(typeattribute new_objects) +(typeattributeset new_objects + ( atrace + binder_calls_stats_service + blank_screen + blank_screen_exec + blank_screen_tmpfs + bootloader_boot_reason_prop + bluetooth_a2dp_offload_prop + bpfloader + bpfloader_exec + cgroup_bpf + crossprofileapps_service + ctl_interface_restart_prop + ctl_interface_start_prop + ctl_interface_stop_prop + ctl_sigstop_prop + exfat + exported2_config_prop + exported2_default_prop + exported2_radio_prop + exported2_system_prop + exported2_vold_prop + exported3_default_prop + exported3_radio_prop + exported3_system_prop + exported_bluetooth_prop + exported_config_prop + exported_dalvik_prop + exported_default_prop + exported_dumpstate_prop + exported_ffs_prop + exported_fingerprint_prop + exported_overlay_prop + exported_pm_prop + exported_radio_prop + exported_secure_prop + exported_system_prop + exported_system_radio_prop + exported_vold_prop + exported_wifi_prop + fingerprint_vendor_data_file + fs_bpf + hal_audiocontrol_hwservice + hal_authsecret_hwservice + hal_codec2_hwservice + hal_confirmationui_hwservice + hal_evs_hwservice + hal_lowpan_hwservice + hal_secure_element_hwservice + hal_usb_gadget_hwservice + hal_vehicle_hwservice + hal_wifi_hostapd_hwservice + incident_helper + incident_helper_exec + last_boot_reason_prop + lowpan_device + lowpan_prop + lowpan_service + mediaextractor_update_service + metadata_file + mnt_vendor_file + network_watchlist_data_file + network_watchlist_service + perfetto + perfetto_exec + perfetto_tmpfs + perfetto_traces_data_file + perfprofd_service + property_info + secure_element + secure_element_device + secure_element_service + secure_element_tmpfs + slice_service + stats + stats_data_file + stats_exec + stats_service + statscompanion_service + statsd + statsd_exec + statsd_tmpfs + statsdw + statsdw_socket + storaged_data_file + system_boot_reason_prop + system_update_service + test_boot_reason_prop + tombstone_wifi_data_file + trace_data_file + traced + traced_consumer_socket + traced_enabled_prop + traced_exec + traced_probes + traced_probes_exec + traced_probes_tmpfs + traced_producer_socket + traced_tmpfs + traceur_app + traceur_app_tmpfs + untrusted_app_all_devpts + update_engine_log_data_file + usbd + usbd_exec + usbd_tmpfs + vendor_default_prop + vendor_init + vendor_security_patch_level_prop + vendor_shell + vold_metadata_file + vold_prepare_subdirs + vold_prepare_subdirs_exec + vold_service + wait_for_keymaster + wait_for_keymaster_exec + wait_for_keymaster_tmpfs + wm_trace_data_file + wpantund + wpantund_exec + wpantund_service + wpantund_tmpfs)) + +;; private_objects - a collection of types that were labeled differently in +;; older policy, but that should not remain accessible to vendor policy. +;; Thus, these types are also not mapped, but recorded for checkapi tests +(typeattribute priv_objects) +(typeattributeset priv_objects (exagear_debug_file untrusted_app_27_tmpfs)) diff --git a/aosp/system/sepolicy/prebuilts/api/28.0/private/file_contexts b/aosp/system/sepolicy/prebuilts/api/28.0/private/file_contexts new file mode 100644 index 000000000..5f020cf02 --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/28.0/private/file_contexts @@ -0,0 +1,560 @@ +########################################### +# Root +/ u:object_r:rootfs:s0 + +# Data files +/adb_keys u:object_r:adb_keys_file:s0 +/build\.prop u:object_r:rootfs:s0 +/default\.prop u:object_r:rootfs:s0 +/fstab\..* u:object_r:rootfs:s0 +/init\..* u:object_r:rootfs:s0 +/res(/.*)? u:object_r:rootfs:s0 +/selinux_version u:object_r:rootfs:s0 +/ueventd\..* u:object_r:rootfs:s0 +/verity_key u:object_r:rootfs:s0 + +# Executables +/charger u:object_r:rootfs:s0 +/init u:object_r:init_exec:s0 +/sbin(/.*)? u:object_r:rootfs:s0 + +# For kernel modules +/lib(/.*)? u:object_r:rootfs:s0 + +# Empty directories +/lost\+found u:object_r:rootfs:s0 +/acct u:object_r:cgroup:s0 +/config u:object_r:rootfs:s0 +/mnt u:object_r:tmpfs:s0 +/postinstall u:object_r:postinstall_mnt_dir:s0 +/proc u:object_r:rootfs:s0 +/sys u:object_r:sysfs:s0 + +# proc fs & sys fs +/proc/net/route u:object_r:proc_net_route:s0 +/proc/version u:object_r:proc_version:s0 +/sys/block u:object_r:sysfs_block:s0 +/sys/bus/pci/drivers/virtio-pci u:object_r:sysfs_bpd_virtio_pci:s0 +/sys/bus/virtio u:object_r:sysfs_b_virtio:s0 +/sys/class/net/wlan0 u:object_r:sysfs_cn_wlan0:s0 +/sys/class/power_supply/battery/voltage_now u:object_r:sysfs_power:s0 +/sys/module/virtio_pci u:object_r:sysfs_m_virtio_pci:s0 + +# Symlinks +/bin u:object_r:rootfs:s0 +/bugreports u:object_r:rootfs:s0 +/d u:object_r:rootfs:s0 +/etc u:object_r:rootfs:s0 +/sdcard u:object_r:rootfs:s0 + +# SELinux policy files +/vendor_file_contexts u:object_r:file_contexts_file:s0 +/nonplat_file_contexts u:object_r:file_contexts_file:s0 +/plat_file_contexts u:object_r:file_contexts_file:s0 +/mapping_sepolicy\.cil u:object_r:sepolicy_file:s0 +/nonplat_sepolicy\.cil u:object_r:sepolicy_file:s0 +/plat_sepolicy\.cil u:object_r:sepolicy_file:s0 +/plat_property_contexts u:object_r:property_contexts_file:s0 +/nonplat_property_contexts u:object_r:property_contexts_file:s0 +/vendor_property_contexts u:object_r:property_contexts_file:s0 +/seapp_contexts u:object_r:seapp_contexts_file:s0 +/nonplat_seapp_contexts u:object_r:seapp_contexts_file:s0 +/vendor_seapp_contexts u:object_r:seapp_contexts_file:s0 +/plat_seapp_contexts u:object_r:seapp_contexts_file:s0 +/sepolicy u:object_r:sepolicy_file:s0 +/plat_service_contexts u:object_r:service_contexts_file:s0 +/plat_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/nonplat_service_contexts u:object_r:nonplat_service_contexts_file:s0 +# Use nonplat_service_contexts_file to allow servicemanager to read it +# on non full-treble devices. +/vendor_service_contexts u:object_r:nonplat_service_contexts_file:s0 +/nonplat_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/vendor_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/vndservice_contexts u:object_r:vndservice_contexts_file:s0 + +########################## +# Devices +# +/dev(/.*)? u:object_r:device:s0 +/dev/akm8973.* u:object_r:sensors_device:s0 +/dev/accelerometer u:object_r:sensors_device:s0 +/dev/adf[0-9]* u:object_r:graphics_device:s0 +/dev/adf-interface[0-9]*\.[0-9]* u:object_r:graphics_device:s0 +/dev/adf-overlay-engine[0-9]*\.[0-9]* u:object_r:graphics_device:s0 +/dev/alarm u:object_r:alarm_device:s0 +/dev/ashmem u:object_r:ashmem_device:s0 +/dev/audio.* u:object_r:audio_device:s0 +/dev/binder u:object_r:binder_device:s0 +/dev/block(/.*)? u:object_r:block_device:s0 +/dev/block/dm-[0-9]+ u:object_r:dm_device:s0 +/dev/block/loop[0-9]* u:object_r:loop_device:s0 +/dev/block/vold/.+ u:object_r:vold_device:s0 +/dev/block/ram[0-9]* u:object_r:ram_device:s0 +/dev/block/zram[0-9]* u:object_r:ram_device:s0 +/dev/bus/usb(.*)? u:object_r:usb_device:s0 +/dev/cam u:object_r:camera_device:s0 +/dev/console u:object_r:console_device:s0 +/dev/cpuctl(/.*)? u:object_r:cpuctl_device:s0 +/dev/memcg(/.*)? u:object_r:cgroup:s0 +/dev/device-mapper u:object_r:dm_device:s0 +/dev/eac u:object_r:audio_device:s0 +/dev/event-log-tags u:object_r:runtime_event_log_tags_file:s0 +/dev/fscklogs(/.*)? u:object_r:fscklogs:s0 +/dev/full u:object_r:full_device:s0 +/dev/fuse u:object_r:fuse_device:s0 +/dev/graphics(/.*)? u:object_r:graphics_device:s0 +/dev/hw_random u:object_r:hw_random_device:s0 +/dev/hwbinder u:object_r:hwbinder_device:s0 +/dev/i2c-[0-9]+ u:object_r:i2c_device:s0 +/dev/input(/.*)? u:object_r:input_device:s0 +/dev/iio:device[0-9]+ u:object_r:iio_device:s0 +/dev/ion u:object_r:ion_device:s0 +/dev/keychord u:object_r:keychord_device:s0 +/dev/kmem u:object_r:kmem_device:s0 +/dev/loop-control u:object_r:loop_control_device:s0 +/dev/mem u:object_r:kmem_device:s0 +/dev/modem.* u:object_r:radio_device:s0 +/dev/mtd(/.*)? u:object_r:mtd_device:s0 +/dev/mtp_usb u:object_r:mtp_device:s0 +/dev/pmsg0 u:object_r:pmsg_device:s0 +/dev/pn544 u:object_r:nfc_device:s0 +/dev/port u:object_r:port_device:s0 +/dev/ppp u:object_r:ppp_device:s0 +/dev/ptmx u:object_r:ptmx_device:s0 +/dev/pvrsrvkm u:object_r:gpu_device:s0 +/dev/kmsg u:object_r:kmsg_device:s0 +/dev/kmsg_debug u:object_r:kmsg_debug_device:s0 +/dev/null u:object_r:null_device:s0 +/dev/nvhdcp1 u:object_r:video_device:s0 +/dev/random u:object_r:random_device:s0 +/dev/rpmsg-omx[0-9] u:object_r:rpmsg_device:s0 +/dev/rproc_user u:object_r:rpmsg_device:s0 +/dev/rtc[0-9] u:object_r:rtc_device:s0 +/dev/snd(/.*)? u:object_r:audio_device:s0 +/dev/snd/audio_timer_device u:object_r:audio_timer_device:s0 +/dev/snd/audio_seq_device u:object_r:audio_seq_device:s0 +/dev/socket(/.*)? u:object_r:socket_device:s0 +/dev/socket/adbd u:object_r:adbd_socket:s0 +/dev/socket/dnsproxyd u:object_r:dnsproxyd_socket:s0 +/dev/socket/dumpstate u:object_r:dumpstate_socket:s0 +/dev/socket/fwmarkd u:object_r:fwmarkd_socket:s0 +/dev/socket/lmkd u:object_r:lmkd_socket:s0 +/dev/socket/logd u:object_r:logd_socket:s0 +/dev/socket/logdr u:object_r:logdr_socket:s0 +/dev/socket/logdw u:object_r:logdw_socket:s0 +/dev/socket/statsdw u:object_r:statsdw_socket:s0 +/dev/socket/mdns u:object_r:mdns_socket:s0 +/dev/socket/mdnsd u:object_r:mdnsd_socket:s0 +/dev/socket/mtpd u:object_r:mtpd_socket:s0 +/dev/socket/netd u:object_r:netd_socket:s0 +/dev/socket/pdx/system/buffer_hub u:object_r:pdx_bufferhub_dir:s0 +/dev/socket/pdx/system/buffer_hub/client u:object_r:pdx_bufferhub_client_endpoint_socket:s0 +/dev/socket/pdx/system/performance u:object_r:pdx_performance_dir:s0 +/dev/socket/pdx/system/performance/client u:object_r:pdx_performance_client_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display u:object_r:pdx_display_dir:s0 +/dev/socket/pdx/system/vr/display/client u:object_r:pdx_display_client_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/manager u:object_r:pdx_display_manager_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/screenshot u:object_r:pdx_display_screenshot_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/vsync u:object_r:pdx_display_vsync_endpoint_socket:s0 +/dev/socket/property_service u:object_r:property_socket:s0 +/dev/socket/racoon u:object_r:racoon_socket:s0 +/dev/socket/rild u:object_r:rild_socket:s0 +/dev/socket/rild-debug u:object_r:rild_debug_socket:s0 +/dev/socket/tombstoned_crash u:object_r:tombstoned_crash_socket:s0 +/dev/socket/tombstoned_java_trace u:object_r:tombstoned_java_trace_socket:s0 +/dev/socket/tombstoned_intercept u:object_r:tombstoned_intercept_socket:s0 +/dev/socket/traced_producer u:object_r:traced_producer_socket:s0 +/dev/socket/traced_consumer u:object_r:traced_consumer_socket:s0 +/dev/socket/uncrypt u:object_r:uncrypt_socket:s0 +/dev/socket/wpa_eth[0-9] u:object_r:wpa_socket:s0 +/dev/socket/wpa_wlan[0-9] u:object_r:wpa_socket:s0 +/dev/socket/zygote u:object_r:zygote_socket:s0 +/dev/socket/zygote_secondary u:object_r:zygote_socket:s0 +/dev/spdif_out.* u:object_r:audio_device:s0 +/dev/tegra.* u:object_r:video_device:s0 +/dev/tty u:object_r:owntty_device:s0 +/dev/tty[0-9]* u:object_r:tty_device:s0 +/dev/ttyS[0-9]* u:object_r:serial_device:s0 +/dev/tun u:object_r:tun_device:s0 +/dev/uhid u:object_r:uhid_device:s0 +/dev/uinput u:object_r:uhid_device:s0 +/dev/uio[0-9]* u:object_r:uio_device:s0 +/dev/urandom u:object_r:random_device:s0 +/dev/usb_accessory u:object_r:usbaccessory_device:s0 +/dev/v4l-touch[0-9]* u:object_r:input_device:s0 +/dev/vcs[0-9a-z]* u:object_r:vcs_device:s0 +/dev/video[0-9]* u:object_r:video_device:s0 +/dev/vndbinder u:object_r:vndbinder_device:s0 +/dev/watchdog u:object_r:watchdog_device:s0 +/dev/xt_qtaguid u:object_r:qtaguid_device:s0 +/dev/zero u:object_r:zero_device:s0 +/dev/__properties__ u:object_r:properties_device:s0 +/dev/__properties__/property_info u:object_r:property_info:s0 +############################# +# System files +# +/system(/.*)? u:object_r:system_file:s0 +/system/bin/atrace u:object_r:atrace_exec:s0 +/system/bin/blank_screen u:object_r:blank_screen_exec:s0 +/system/bin/e2fsdroid u:object_r:e2fs_exec:s0 +/system/bin/mke2fs u:object_r:e2fs_exec:s0 +/system/bin/e2fsck -- u:object_r:fsck_exec:s0 +/system/bin/fsck\.f2fs -- u:object_r:fsck_exec:s0 +/system/bin/sload_f2fs -- u:object_r:e2fs_exec:s0 +/system/bin/make_f2fs -- u:object_r:e2fs_exec:s0 +/system/bin/fsck_msdos -- u:object_r:fsck_exec:s0 +/system/bin/tune2fs -- u:object_r:fsck_exec:s0 +/system/bin/toolbox -- u:object_r:toolbox_exec:s0 +/system/bin/toybox -- u:object_r:toolbox_exec:s0 +/system/bin/logcat -- u:object_r:logcat_exec:s0 +/system/bin/logcatd -- u:object_r:logcat_exec:s0 +/system/bin/sh -- u:object_r:shell_exec:s0 +/system/bin/run-as -- u:object_r:runas_exec:s0 +/system/bin/bootanimation u:object_r:bootanim_exec:s0 +/system/bin/bootstat u:object_r:bootstat_exec:s0 +/system/bin/app_process32 u:object_r:zygote_exec:s0 +/system/bin/app_process64 u:object_r:zygote_exec:s0 +/system/bin/servicemanager u:object_r:servicemanager_exec:s0 +/system/bin/hwservicemanager u:object_r:hwservicemanager_exec:s0 +/system/bin/surfaceflinger u:object_r:surfaceflinger_exec:s0 +/system/bin/bufferhubd u:object_r:bufferhubd_exec:s0 +/system/bin/performanced u:object_r:performanced_exec:s0 +/system/bin/drmserver u:object_r:drmserver_exec:s0 +/system/bin/dumpstate u:object_r:dumpstate_exec:s0 +/system/bin/incident u:object_r:incident_exec:s0 +/system/bin/incidentd u:object_r:incidentd_exec:s0 +/system/bin/incident_helper u:object_r:incident_helper_exec:s0 +/system/bin/netutils-wrapper-1\.0 u:object_r:netutils_wrapper_exec:s0 +/system/bin/vold u:object_r:vold_exec:s0 +/system/bin/netd u:object_r:netd_exec:s0 +/system/bin/wificond u:object_r:wificond_exec:s0 +/system/bin/audioserver u:object_r:audioserver_exec:s0 +/system/bin/mediadrmserver u:object_r:mediadrmserver_exec:s0 +/system/bin/mediaserver u:object_r:mediaserver_exec:s0 +/system/bin/mediametrics u:object_r:mediametrics_exec:s0 +/system/bin/cameraserver u:object_r:cameraserver_exec:s0 +/system/bin/mediaextractor u:object_r:mediaextractor_exec:s0 +/system/bin/mdnsd u:object_r:mdnsd_exec:s0 +/system/bin/installd u:object_r:installd_exec:s0 +/system/bin/otapreopt_chroot u:object_r:otapreopt_chroot_exec:s0 +/system/bin/otapreopt_slot u:object_r:otapreopt_slot_exec:s0 +/system/bin/keystore u:object_r:keystore_exec:s0 +/system/bin/fingerprintd u:object_r:fingerprintd_exec:s0 +/system/bin/gatekeeperd u:object_r:gatekeeperd_exec:s0 +/system/bin/crash_dump32 u:object_r:crash_dump_exec:s0 +/system/bin/crash_dump64 u:object_r:crash_dump_exec:s0 +/system/bin/tombstoned u:object_r:tombstoned_exec:s0 +/system/bin/recovery-persist u:object_r:recovery_persist_exec:s0 +/system/bin/recovery-refresh u:object_r:recovery_refresh_exec:s0 +/system/bin/sdcard u:object_r:sdcardd_exec:s0 +/system/bin/dhcpcd u:object_r:dhcp_exec:s0 +/system/bin/dhcpcd-6.8.2 u:object_r:dhcp_exec:s0 +/system/bin/mtpd u:object_r:mtp_exec:s0 +/system/bin/pppd u:object_r:ppp_exec:s0 +/system/bin/racoon u:object_r:racoon_exec:s0 +/system/bin/cph_su u:object_r:su_exec:s0 +/system/bin/su u:object_r:su_exec:s0 +/system/xbin/su u:object_r:su_exec:s0 +/system/bin/perfprofd u:object_r:perfprofd_exec:s0 +/system/bin/dnsmasq u:object_r:dnsmasq_exec:s0 +/system/bin/healthd u:object_r:healthd_exec:s0 +/system/bin/clatd u:object_r:clatd_exec:s0 +/system/bin/lmkd u:object_r:lmkd_exec:s0 +/system/bin/usbd u:object_r:usbd_exec:s0 +/system/bin/inputflinger u:object_r:inputflinger_exec:s0 +/system/bin/logd u:object_r:logd_exec:s0 +/system/bin/perfetto u:object_r:perfetto_exec:s0 +/system/bin/traced u:object_r:traced_exec:s0 +/system/bin/traced_probes u:object_r:traced_probes_exec:s0 +/system/bin/uncrypt u:object_r:uncrypt_exec:s0 +/system/bin/update_verifier u:object_r:update_verifier_exec:s0 +/system/bin/logwrapper u:object_r:system_file:s0 +/system/bin/vdc u:object_r:vdc_exec:s0 +/system/bin/cppreopts.sh u:object_r:cppreopts_exec:s0 +/system/bin/preopt2cachename u:object_r:preopt2cachename_exec:s0 +/system/bin/install-recovery.sh u:object_r:install_recovery_exec:s0 +/system/bin/dex2oat(d)? u:object_r:dex2oat_exec:s0 +/system/bin/dexoptanalyzer(d)? u:object_r:dexoptanalyzer_exec:s0 +# patchoat executable has (essentially) the same requirements as dex2oat. +/system/bin/patchoat(d)? u:object_r:dex2oat_exec:s0 +/system/bin/profman(d)? u:object_r:profman_exec:s0 +/system/bin/sgdisk u:object_r:sgdisk_exec:s0 +/system/bin/blkid u:object_r:blkid_exec:s0 +/system/bin/tzdatacheck u:object_r:tzdatacheck_exec:s0 +/system/bin/idmap u:object_r:idmap_exec:s0 +/system/bin/update_engine u:object_r:update_engine_exec:s0 +/system/bin/bspatch u:object_r:update_engine_exec:s0 +/system/bin/storaged u:object_r:storaged_exec:s0 +/system/bin/thermalserviced u:object_r:thermalserviced_exec:s0 +/system/bin/wpantund u:object_r:wpantund_exec:s0 +/system/bin/virtual_touchpad u:object_r:virtual_touchpad_exec:s0 +/system/bin/hw/android\.hidl\.allocator@1\.0-service u:object_r:hal_allocator_default_exec:s0 +/system/etc/selinux/mapping/[0-9]+\.[0-9]+\.cil u:object_r:sepolicy_file:s0 +/system/etc/selinux/plat_mac_permissions\.xml u:object_r:mac_perms_file:s0 +/system/etc/selinux/plat_property_contexts u:object_r:property_contexts_file:s0 +/system/etc/selinux/plat_service_contexts u:object_r:service_contexts_file:s0 +/system/etc/selinux/plat_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/system/etc/selinux/plat_file_contexts u:object_r:file_contexts_file:s0 +/system/etc/selinux/plat_seapp_contexts u:object_r:seapp_contexts_file:s0 +/system/etc/selinux/plat_sepolicy.cil u:object_r:sepolicy_file:s0 +/system/etc/selinux/plat_and_mapping_sepolicy\.cil\.sha256 u:object_r:sepolicy_file:s0 +/system/bin/vr_hwc u:object_r:vr_hwc_exec:s0 +/system/bin/adbd u:object_r:adbd_exec:s0 +/system/bin/vold_prepare_subdirs u:object_r:vold_prepare_subdirs_exec:s0 +/system/bin/stats u:object_r:stats_exec:s0 +/system/bin/statsd u:object_r:statsd_exec:s0 +/system/bin/bpfloader u:object_r:bpfloader_exec:s0 +/system/bin/wait_for_keymaster u:object_r:wait_for_keymaster_exec:s0 +############################# +# Vendor files +# +/(vendor|system/vendor)(/.*)? u:object_r:vendor_file:s0 +/(vendor|system/vendor)/bin/sh u:object_r:vendor_shell_exec:s0 +/(vendor|system/vendor)/bin/toybox_vendor u:object_r:vendor_toolbox_exec:s0 +/(vendor|system/vendor)/bin/toolbox u:object_r:vendor_toolbox_exec:s0 +/(vendor|system/vendor)/etc(/.*)? u:object_r:vendor_configs_file:s0 + +/(vendor|system/vendor)/lib(64)?/egl(/.*)? u:object_r:same_process_hal_file:s0 + +/(vendor|system/vendor)/lib(64)?/vndk-sp(/.*)? u:object_r:vndk_sp_file:s0 + +/(vendor|system/vendor)/manifest.xml u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/compatibility_matrix.xml u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/etc/vintf(/.*)? u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/app(/.*)? u:object_r:vendor_app_file:s0 +/(vendor|system/vendor)/priv-app(/.*)? u:object_r:vendor_app_file:s0 +/(vendor|system/vendor)/overlay(/.*)? u:object_r:vendor_overlay_file:s0 +/(vendor|system/vendor)/framework(/.*)? u:object_r:vendor_framework_file:s0 + +# HAL location +/(vendor|system/vendor)/lib(64)?/hw u:object_r:vendor_hal_file:s0 + +############################# +# OEM and ODM files +# +/(odm|vendor/odm)(/.*)? u:object_r:vendor_file:s0 +/(odm|vendor/odm)/lib(64)?/egl(/.*)? u:object_r:same_process_hal_file:s0 +/(odm|vendor/odm)/lib(64)?/hw u:object_r:vendor_hal_file:s0 +/(odm|vendor/odm)/lib(64)?/vndk-sp(/.*)? u:object_r:vndk_sp_file:s0 +/(odm|vendor/odm)/bin/sh u:object_r:vendor_shell_exec:s0 +/(odm|vendor/odm)/etc(/.*)? u:object_r:vendor_configs_file:s0 +/(odm|vendor/odm)/app(/.*)? u:object_r:vendor_app_file:s0 +/(odm|vendor/odm)/priv-app(/.*)? u:object_r:vendor_app_file:s0 +/(odm|vendor/odm)/overlay(/.*)? u:object_r:vendor_overlay_file:s0 +/(odm|vendor/odm)/framework(/.*)? u:object_r:vendor_framework_file:s0 + +/oem(/.*)? u:object_r:oemfs:s0 + +# The precompiled monolithic sepolicy will be under /odm only when +# BOARD_USES_ODMIMAGE is true: a separate odm.img is built. +/odm/etc/selinux/precompiled_sepolicy u:object_r:sepolicy_file:s0 +/odm/etc/selinux/precompiled_sepolicy\.plat_and_mapping\.sha256 u:object_r:sepolicy_file:s0 + +/(odm|vendor/odm)/etc/selinux/odm_sepolicy.cil u:object_r:sepolicy_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_file_contexts u:object_r:file_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_seapp_contexts u:object_r:seapp_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_property_contexts u:object_r:property_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_mac_permissions.xml u:object_r:mac_perms_file:s0 + +############################# +# Product files +# +/(product|system/product)(/.*)? u:object_r:system_file:s0 + +############################# +# Data files +# +# NOTE: When modifying existing label rules, changes may also need to +# propagate to the "Expanded data files" section. +# +/data(/.*)? u:object_r:system_data_file:s0 +# for /data/data/xxx +/data/data u:object_r:app_data_file:s0 +/data/data(/.*)? u:object_r:app_data_file:s0 +/data/.layout_version u:object_r:install_data_file:s0 +/data/unencrypted(/.*)? u:object_r:unencrypted_data_file:s0 +/data/backup(/.*)? u:object_r:backup_data_file:s0 +/data/secure/backup(/.*)? u:object_r:backup_data_file:s0 +/data/system/ndebugsocket u:object_r:system_ndebug_socket:s0 +/data/drm(/.*)? u:object_r:drm_data_file:s0 +/data/resource-cache(/.*)? u:object_r:resourcecache_data_file:s0 +/data/dalvik-cache(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/ota(/.*)? u:object_r:ota_data_file:s0 +/data/ota_package(/.*)? u:object_r:ota_package_file:s0 +/data/adb(/.*)? u:object_r:adb_data_file:s0 +/data/anr(/.*)? u:object_r:anr_data_file:s0 +/data/app(/.*)? u:object_r:apk_data_file:s0 +/data/app/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/app/vmdl[^/]+\.tmp(/.*)? u:object_r:apk_tmp_file:s0 +/data/app/vmdl[^/]+\.tmp/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/app-private(/.*)? u:object_r:apk_private_data_file:s0 +/data/app-private/vmdl.*\.tmp(/.*)? u:object_r:apk_private_tmp_file:s0 +/data/tombstones(/.*)? u:object_r:tombstone_data_file:s0 +/data/vendor/tombstones/wifi(/.*)? u:object_r:tombstone_wifi_data_file:s0 +/data/local(/.*)? u:object_r:app_data_file:s0 +/data/local/tmp(/.*)? u:object_r:shell_data_file:s0 +/data/local/tmp/ltp(/.*)? u:object_r:nativetest_data_file:s0 +/data/local/traces(/.*)? u:object_r:trace_data_file:s0 +/data/media(/.*)? u:object_r:media_rw_data_file:s0 +/data/mediadrm(/.*)? u:object_r:media_data_file:s0 +/data/nativetest(/.*)? u:object_r:nativetest_data_file:s0 +/data/nativetest64(/.*)? u:object_r:nativetest_data_file:s0 +/data/property(/.*)? u:object_r:property_data_file:s0 +/data/preloads(/.*)? u:object_r:preloads_data_file:s0 +/data/preloads/media(/.*)? u:object_r:preloads_media_file:s0 +/data/preloads/demo(/.*)? u:object_r:preloads_media_file:s0 + +# Misc data +/data/misc/adb(/.*)? u:object_r:adb_keys_file:s0 +/data/misc/apns(/.*)? u:object_r:radio_data_file:s0 +/data/misc/audio(/.*)? u:object_r:audio_data_file:s0 +/data/misc/audioserver(/.*)? u:object_r:audioserver_data_file:s0 +/data/misc/audiohal(/.*)? u:object_r:audiohal_data_file:s0 +/data/misc/bootstat(/.*)? u:object_r:bootstat_data_file:s0 +/data/misc/boottrace(/.*)? u:object_r:boottrace_data_file:s0 +/data/misc/bluetooth(/.*)? u:object_r:bluetooth_data_file:s0 +/data/misc/bluetooth/logs(/.*)? u:object_r:bluetooth_logs_data_file:s0 +/data/misc/bluedroid(/.*)? u:object_r:bluetooth_data_file:s0 +/data/misc/bluedroid/\.a2dp_ctrl u:object_r:bluetooth_socket:s0 +/data/misc/bluedroid/\.a2dp_data u:object_r:bluetooth_socket:s0 +/data/misc/camera(/.*)? u:object_r:camera_data_file:s0 +/data/misc/carrierid(/.*)? u:object_r:radio_data_file:s0 +/data/misc/dhcp(/.*)? u:object_r:dhcp_data_file:s0 +/data/misc/dhcp-6.8.2(/.*)? u:object_r:dhcp_data_file:s0 +/data/misc/gatekeeper(/.*)? u:object_r:gatekeeper_data_file:s0 +/data/misc/incidents(/.*)? u:object_r:incident_data_file:s0 +/data/misc/keychain(/.*)? u:object_r:keychain_data_file:s0 +/data/misc/keystore(/.*)? u:object_r:keystore_data_file:s0 +/data/misc/logd(/.*)? u:object_r:misc_logd_file:s0 +/data/misc/media(/.*)? u:object_r:media_data_file:s0 +/data/misc/net(/.*)? u:object_r:net_data_file:s0 +/data/misc/network_watchlist(/.*)? u:object_r:network_watchlist_data_file:s0 +/data/misc/perfetto-traces(/.*)? u:object_r:perfetto_traces_data_file:s0 +/data/misc/recovery(/.*)? u:object_r:recovery_data_file:s0 +/data/misc/shared_relro(/.*)? u:object_r:shared_relro_file:s0 +/data/misc/sms(/.*)? u:object_r:radio_data_file:s0 +/data/misc/stats-data(/.*)? u:object_r:stats_data_file:s0 +/data/misc/stats-service(/.*)? u:object_r:stats_data_file:s0 +/data/misc/systemkeys(/.*)? u:object_r:systemkeys_data_file:s0 +/data/misc/textclassifier(/.*)? u:object_r:textclassifier_data_file:s0 +/data/misc/user(/.*)? u:object_r:misc_user_data_file:s0 +/data/misc/vpn(/.*)? u:object_r:vpn_data_file:s0 +/data/misc/wifi(/.*)? u:object_r:wifi_data_file:s0 +/data/misc/wifi/sockets(/.*)? u:object_r:wpa_socket:s0 +/data/misc/wifi/sockets/wpa_ctrl.* u:object_r:system_wpa_socket:s0 +/data/misc/zoneinfo(/.*)? u:object_r:zoneinfo_data_file:s0 +/data/misc/vold(/.*)? u:object_r:vold_data_file:s0 +/data/misc/perfprofd(/.*)? u:object_r:perfprofd_data_file:s0 +/data/misc/update_engine(/.*)? u:object_r:update_engine_data_file:s0 +/data/misc/update_engine_log(/.*)? u:object_r:update_engine_log_data_file:s0 +/data/system/heapdump(/.*)? u:object_r:heapdump_data_file:s0 +/data/misc/trace(/.*)? u:object_r:method_trace_data_file:s0 +/data/misc/wmtrace(/.*)? u:object_r:wm_trace_data_file:s0 +# TODO(calin) label profile reference differently so that only +# profman run as a special user can write to them +/data/misc/profiles/cur(/.*)? u:object_r:user_profile_data_file:s0 +/data/misc/profiles/ref(/.*)? u:object_r:user_profile_data_file:s0 +/data/misc/profman(/.*)? u:object_r:profman_dump_data_file:s0 +/data/vendor(/.*)? u:object_r:vendor_data_file:s0 +/data/vendor_ce(/.*)? u:object_r:vendor_data_file:s0 +/data/vendor_de(/.*)? u:object_r:vendor_data_file:s0 + +# storaged proto files +/data/misc_de/[0-9]+/storaged(/.*)? u:object_r:storaged_data_file:s0 +/data/misc_ce/[0-9]+/storaged(/.*)? u:object_r:storaged_data_file:s0 + +# Fingerprint data +/data/system/users/[0-9]+/fpdata(/.*)? u:object_r:fingerprintd_data_file:s0 + +# Fingerprint vendor data file +/data/vendor_de/[0-9]+/fpdata(/.*)? u:object_r:fingerprint_vendor_data_file:s0 + +# Bootchart data +/data/bootchart(/.*)? u:object_r:bootchart_data_file:s0 + +############################# +# Expanded data files +# +/mnt/expand(/.*)? u:object_r:mnt_expand_file:s0 +/mnt/expand/[^/]+(/.*)? u:object_r:system_data_file:s0 +/mnt/expand/[^/]+/app(/.*)? u:object_r:apk_data_file:s0 +/mnt/expand/[^/]+/app/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/mnt/expand/[^/]+/app/vmdl[^/]+\.tmp(/.*)? u:object_r:apk_tmp_file:s0 +/mnt/expand/[^/]+/app/vmdl[^/]+\.tmp/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/mnt/expand/[^/]+/local/tmp(/.*)? u:object_r:shell_data_file:s0 +/mnt/expand/[^/]+/media(/.*)? u:object_r:media_rw_data_file:s0 +/mnt/expand/[^/]+/misc/vold(/.*)? u:object_r:vold_data_file:s0 + +# coredump directory for userdebug/eng devices +/cores(/.*)? u:object_r:coredump_file:s0 + +# Wallpaper files +/data/system/users/[0-9]+/wallpaper_lock_orig u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper_lock u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper_orig u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper u:object_r:wallpaper_file:s0 + +# Ringtone files +/data/system_de/[0-9]+/ringtones(/.*)? u:object_r:ringtone_file:s0 + +# ShortcutManager icons, e.g. +# /data/system_ce/0/shortcut_service/bitmaps/com.example.app/1457472879282.png +/data/system_ce/[0-9]+/shortcut_service/bitmaps(/.*)? u:object_r:shortcut_manager_icons:s0 + +# User icon files +/data/system/users/[0-9]+/photo.png u:object_r:icon_file:s0 + +# vold per-user data +/data/misc_de/[0-9]+/vold(/.*)? u:object_r:vold_data_file:s0 +/data/misc_ce/[0-9]+/vold(/.*)? u:object_r:vold_data_file:s0 + +############################# +# efs files +# +/efs(/.*)? u:object_r:efs_file:s0 + +############################# +# Cache files +# +/cache(/.*)? u:object_r:cache_file:s0 +/cache/recovery(/.*)? u:object_r:cache_recovery_file:s0 +# General backup/restore interchange with apps +/cache/backup_stage(/.*)? u:object_r:cache_backup_file:s0 +# LocalTransport (backup) uses this subtree +/cache/backup(/.*)? u:object_r:cache_private_backup_file:s0 + +/data/cache(/.*)? u:object_r:cache_file:s0 +/data/cache/recovery(/.*)? u:object_r:cache_recovery_file:s0 +# General backup/restore interchange with apps +/data/cache/backup_stage(/.*)? u:object_r:cache_backup_file:s0 +# LocalTransport (backup) uses this subtree +/data/cache/backup(/.*)? u:object_r:cache_private_backup_file:s0 + +############################# +# Metadata files +# +/metadata(/.*)? u:object_r:metadata_file:s0 +/metadata/vold(/.*)? u:object_r:vold_metadata_file:s0 + +############################# +# asec containers +/mnt/asec(/.*)? u:object_r:asec_apk_file:s0 +/mnt/asec/[^/]+/[^/]+\.zip u:object_r:asec_public_file:s0 +/mnt/asec/[^/]+/lib(/.*)? u:object_r:asec_public_file:s0 +/data/app-asec(/.*)? u:object_r:asec_image_file:s0 + +############################# +# external storage +/mnt/media_rw(/.*)? u:object_r:mnt_media_rw_file:s0 +/mnt/user(/.*)? u:object_r:mnt_user_file:s0 +/mnt/runtime(/.*)? u:object_r:storage_file:s0 +/storage(/.*)? u:object_r:storage_file:s0 + +############################# +# mount point for read-write vendor partitions +/mnt/vendor(/.*)? u:object_r:mnt_vendor_file:s0 + +############################# +# mbox +/anbox-init.sh u:object_r:rootfs:s0 diff --git a/aosp/system/sepolicy/prebuilts/api/28.0/private/service_contexts b/aosp/system/sepolicy/prebuilts/api/28.0/private/service_contexts new file mode 100644 index 000000000..fd2c4305a --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/28.0/private/service_contexts @@ -0,0 +1,191 @@ +accessibility u:object_r:accessibility_service:s0 +account u:object_r:account_service:s0 +activity u:object_r:activity_service:s0 +alarm u:object_r:alarm_service:s0 +android.os.UpdateEngineService u:object_r:update_engine_service:s0 +android.security.keystore u:object_r:keystore_service:s0 +android.service.gatekeeper.IGateKeeperService u:object_r:gatekeeper_service:s0 +appops u:object_r:appops_service:s0 +appwidget u:object_r:appwidget_service:s0 +assetatlas u:object_r:assetatlas_service:s0 +audio u:object_r:audio_service:s0 +autofill u:object_r:autofill_service:s0 +backup u:object_r:backup_service:s0 +batteryproperties u:object_r:batteryproperties_service:s0 +batterystats u:object_r:batterystats_service:s0 +battery u:object_r:battery_service:s0 +binder_calls_stats u:object_r:binder_calls_stats_service:s0 +bluetooth_manager u:object_r:bluetooth_manager_service:s0 +bluetooth u:object_r:bluetooth_service:s0 +broadcastradio u:object_r:broadcastradio_service:s0 +carrier_config u:object_r:radio_service:s0 +clipboard u:object_r:clipboard_service:s0 +com.android.net.IProxyService u:object_r:IProxyService_service:s0 +commontime_management u:object_r:commontime_management_service:s0 +common_time.clock u:object_r:mediaserver_service:s0 +common_time.config u:object_r:mediaserver_service:s0 +companiondevice u:object_r:companion_device_service:s0 +connectivity u:object_r:connectivity_service:s0 +connmetrics u:object_r:connmetrics_service:s0 +consumer_ir u:object_r:consumer_ir_service:s0 +content u:object_r:content_service:s0 +contexthub u:object_r:contexthub_service:s0 +country_detector u:object_r:country_detector_service:s0 +coverage u:object_r:coverage_service:s0 +cpuinfo u:object_r:cpuinfo_service:s0 +crossprofileapps u:object_r:crossprofileapps_service:s0 +dbinfo u:object_r:dbinfo_service:s0 +device_policy u:object_r:device_policy_service:s0 +device_identifiers u:object_r:device_identifiers_service:s0 +deviceidle u:object_r:deviceidle_service:s0 +devicestoragemonitor u:object_r:devicestoragemonitor_service:s0 +diskstats u:object_r:diskstats_service:s0 +display u:object_r:display_service:s0 +netd_listener u:object_r:netd_listener_service:s0 +network_watchlist u:object_r:network_watchlist_service:s0 +DockObserver u:object_r:DockObserver_service:s0 +dreams u:object_r:dreams_service:s0 +drm.drmManager u:object_r:drmserver_service:s0 +dropbox u:object_r:dropbox_service:s0 +dumpstate u:object_r:dumpstate_service:s0 +econtroller u:object_r:radio_service:s0 +euicc_card_controller u:object_r:radio_service:s0 +lowpan u:object_r:lowpan_service:s0 +ethernet u:object_r:ethernet_service:s0 +fingerprint u:object_r:fingerprint_service:s0 +font u:object_r:font_service:s0 +android.hardware.fingerprint.IFingerprintDaemon u:object_r:fingerprintd_service:s0 +gfxinfo u:object_r:gfxinfo_service:s0 +graphicsstats u:object_r:graphicsstats_service:s0 +gpu u:object_r:gpu_service:s0 +hardware u:object_r:hardware_service:s0 +hardware_properties u:object_r:hardware_properties_service:s0 +hdmi_control u:object_r:hdmi_control_service:s0 +incident u:object_r:incident_service:s0 +inputflinger u:object_r:inputflinger_service:s0 +input_method u:object_r:input_method_service:s0 +input u:object_r:input_service:s0 +installd u:object_r:installd_service:s0 +iphonesubinfo_msim u:object_r:radio_service:s0 +iphonesubinfo2 u:object_r:radio_service:s0 +iphonesubinfo u:object_r:radio_service:s0 +ims u:object_r:radio_service:s0 +imms u:object_r:imms_service:s0 +ipsec u:object_r:ipsec_service:s0 +isms_msim u:object_r:radio_service:s0 +isms2 u:object_r:radio_service:s0 +isms u:object_r:radio_service:s0 +isub u:object_r:radio_service:s0 +jobscheduler u:object_r:jobscheduler_service:s0 +launcherapps u:object_r:launcherapps_service:s0 +location u:object_r:location_service:s0 +lock_settings u:object_r:lock_settings_service:s0 +media.aaudio u:object_r:audioserver_service:s0 +media.audio_flinger u:object_r:audioserver_service:s0 +media.audio_policy u:object_r:audioserver_service:s0 +media.camera u:object_r:cameraserver_service:s0 +media.camera.proxy u:object_r:cameraproxy_service:s0 +media.log u:object_r:audioserver_service:s0 +media.player u:object_r:mediaserver_service:s0 +media.metrics u:object_r:mediametrics_service:s0 +media.extractor u:object_r:mediaextractor_service:s0 +media.extractor.update u:object_r:mediaextractor_update_service:s0 +media.codec u:object_r:mediacodec_service:s0 +media.resource_manager u:object_r:mediaserver_service:s0 +media.sound_trigger_hw u:object_r:audioserver_service:s0 +media.drm u:object_r:mediadrmserver_service:s0 +media_projection u:object_r:media_projection_service:s0 +media_resource_monitor u:object_r:media_session_service:s0 +media_router u:object_r:media_router_service:s0 +media_session u:object_r:media_session_service:s0 +meminfo u:object_r:meminfo_service:s0 +midi u:object_r:midi_service:s0 +mount u:object_r:mount_service:s0 +netd u:object_r:netd_service:s0 +netpolicy u:object_r:netpolicy_service:s0 +netstats u:object_r:netstats_service:s0 +network_management u:object_r:network_management_service:s0 +network_score u:object_r:network_score_service:s0 +network_time_update_service u:object_r:network_time_update_service:s0 +nfc u:object_r:nfc_service:s0 +notification u:object_r:notification_service:s0 +oem_lock u:object_r:oem_lock_service:s0 +otadexopt u:object_r:otadexopt_service:s0 +overlay u:object_r:overlay_service:s0 +package u:object_r:package_service:s0 +package_native u:object_r:package_native_service:s0 +perfprofd u:object_r:perfprofd_service:s0 +permission u:object_r:permission_service:s0 +persistent_data_block u:object_r:persistent_data_block_service:s0 +phone_msim u:object_r:radio_service:s0 +phone1 u:object_r:radio_service:s0 +phone2 u:object_r:radio_service:s0 +phone u:object_r:radio_service:s0 +pinner u:object_r:pinner_service:s0 +power u:object_r:power_service:s0 +print u:object_r:print_service:s0 +processinfo u:object_r:processinfo_service:s0 +procstats u:object_r:procstats_service:s0 +radio.phonesubinfo u:object_r:radio_service:s0 +radio.phone u:object_r:radio_service:s0 +radio.sms u:object_r:radio_service:s0 +recovery u:object_r:recovery_service:s0 +restrictions u:object_r:restrictions_service:s0 +rttmanager u:object_r:rttmanager_service:s0 +samplingprofiler u:object_r:samplingprofiler_service:s0 +scheduling_policy u:object_r:scheduling_policy_service:s0 +search u:object_r:search_service:s0 +secure_element u:object_r:secure_element_service:s0 +sec_key_att_app_id_provider u:object_r:sec_key_att_app_id_provider_service:s0 +sensorservice u:object_r:sensorservice_service:s0 +serial u:object_r:serial_service:s0 +servicediscovery u:object_r:servicediscovery_service:s0 +settings u:object_r:settings_service:s0 +shortcut u:object_r:shortcut_service:s0 +simphonebook_msim u:object_r:radio_service:s0 +simphonebook2 u:object_r:radio_service:s0 +simphonebook u:object_r:radio_service:s0 +sip u:object_r:radio_service:s0 +slice u:object_r:slice_service:s0 +stats u:object_r:stats_service:s0 +statscompanion u:object_r:statscompanion_service:s0 +soundtrigger u:object_r:voiceinteraction_service:s0 +statusbar u:object_r:statusbar_service:s0 +storaged u:object_r:storaged_service:s0 +storaged_pri u:object_r:storaged_service:s0 +storagestats u:object_r:storagestats_service:s0 +SurfaceFlinger u:object_r:surfaceflinger_service:s0 +system_update u:object_r:system_update_service:s0 +task u:object_r:task_service:s0 +telecom u:object_r:telecom_service:s0 +telephony.registry u:object_r:registry_service:s0 +textclassification u:object_r:textclassification_service:s0 +textservices u:object_r:textservices_service:s0 +timezone u:object_r:timezone_service:s0 +thermalservice u:object_r:thermal_service:s0 +trust u:object_r:trust_service:s0 +tv_input u:object_r:tv_input_service:s0 +uimode u:object_r:uimode_service:s0 +updatelock u:object_r:updatelock_service:s0 +usagestats u:object_r:usagestats_service:s0 +usb u:object_r:usb_service:s0 +user u:object_r:user_service:s0 +vibrator u:object_r:vibrator_service:s0 +virtual_touchpad u:object_r:virtual_touchpad_service:s0 +voiceinteraction u:object_r:voiceinteraction_service:s0 +vold u:object_r:vold_service:s0 +vr_hwc u:object_r:vr_hwc_service:s0 +vrmanager u:object_r:vr_manager_service:s0 +wallpaper u:object_r:wallpaper_service:s0 +webviewupdate u:object_r:webviewupdate_service:s0 +wifip2p u:object_r:wifip2p_service:s0 +wifiscanner u:object_r:wifiscanner_service:s0 +wifi u:object_r:wifi_service:s0 +wificond u:object_r:wificond_service:s0 +wifiaware u:object_r:wifiaware_service:s0 +wifirtt u:object_r:rttmanager_service:s0 +window u:object_r:window_service:s0 +cph_performance u:object_r:activity_service:s0 +phoneadjust u:object_r:activity_service:s0 +attributes u:object_r:activity_service:s0 +* u:object_r:default_android_service:s0 diff --git a/aosp/system/sepolicy/prebuilts/api/28.0/public/domain.te b/aosp/system/sepolicy/prebuilts/api/28.0/public/domain.te new file mode 100644 index 000000000..8a461343b --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/28.0/public/domain.te @@ -0,0 +1,1403 @@ +# Rules for all domains. + +# Allow reaping by init. +allow domain init:process sigchld; + +# Intra-domain accesses. +allow domain self:process { + fork + sigchld + sigkill + sigstop + signull + signal + getsched + setsched + getsession + getpgid + setpgid + getcap + setcap + getattr + setrlimit +}; +allow domain self:fd use; +allow domain proc:dir r_dir_perms; +allow domain proc_net:dir search; +r_dir_file(domain, self) +allow domain self:{ fifo_file file } rw_file_perms; +allow domain self:unix_dgram_socket { create_socket_perms sendto }; +allow domain self:unix_stream_socket { create_stream_socket_perms connectto }; + +# Inherit or receive open files from others. +allow domain init:fd use; + +userdebug_or_eng(` + allow domain su:fd use; + allow domain su:unix_stream_socket { connectto getattr getopt read write shutdown }; + allow domain su:unix_dgram_socket sendto; + + allow { domain -init } su:binder { call transfer }; + + # Running something like "pm dump com.android.bluetooth" requires + # fifo writes + allow domain su:fifo_file { write getattr }; + + # allow "gdbserver --attach" to work for su. + allow domain su:process sigchld; + + # Allow writing coredumps to /cores/* + allow domain coredump_file:file create_file_perms; + allow domain coredump_file:dir ra_dir_perms; +') + +# Root fs. +allow domain rootfs:dir search; +allow domain rootfs:lnk_file { read getattr }; + +# Device accesses. +allow domain device:dir search; +allow domain dev_type:lnk_file r_file_perms; +allow domain devpts:dir search; +allow domain socket_device:dir r_dir_perms; +allow domain owntty_device:chr_file rw_file_perms; +allow domain null_device:chr_file rw_file_perms; +allow domain zero_device:chr_file rw_file_perms; +allow domain ashmem_device:chr_file rw_file_perms; +# /dev/binder can be accessed by non-vendor domains and by apps +allow { + coredomain + appdomain + binder_in_vendor_violators # TODO(b/35870313): Remove once all violations are gone + -hwservicemanager +} binder_device:chr_file rw_file_perms; +# Devices which are not full TREBLE have fewer restrictions on access to /dev/binder +not_full_treble(`allow { domain -hwservicemanager -vndservicemanager } binder_device:chr_file rw_file_perms;') +allow { domain -servicemanager -vndservicemanager -isolated_app } hwbinder_device:chr_file rw_file_perms; +allow domain ptmx_device:chr_file rw_file_perms; +allow domain alarm_device:chr_file r_file_perms; +allow domain random_device:chr_file rw_file_perms; +allow domain proc_random:dir r_dir_perms; +allow domain proc_random:file r_file_perms; +allow domain properties_device:dir { search getattr }; +allow domain properties_serial:file r_file_perms; +allow domain property_info:file r_file_perms; + +# For now, everyone can access core property files +# Device specific properties are not granted by default +not_compatible_property(` + get_prop(domain, core_property_type) + get_prop(domain, exported_dalvik_prop) + get_prop(domain, exported_ffs_prop) + get_prop(domain, exported_system_radio_prop) + get_prop(domain, exported2_config_prop) + get_prop(domain, exported2_radio_prop) + get_prop(domain, exported2_system_prop) + get_prop(domain, exported2_vold_prop) + get_prop(domain, exported3_default_prop) + get_prop(domain, exported3_radio_prop) + get_prop(domain, exported3_system_prop) + get_prop(domain, vendor_default_prop) +') +compatible_property_only(` + get_prop({coredomain appdomain shell}, core_property_type) + get_prop({coredomain appdomain shell}, exported_dalvik_prop) + get_prop({coredomain appdomain shell}, exported_ffs_prop) + get_prop({coredomain appdomain shell}, exported_system_radio_prop) + get_prop({coredomain appdomain shell}, exported2_config_prop) + get_prop({coredomain appdomain shell}, exported2_radio_prop) + get_prop({coredomain appdomain shell}, exported2_system_prop) + get_prop({coredomain appdomain shell}, exported2_vold_prop) + get_prop({coredomain appdomain shell}, exported3_default_prop) + get_prop({coredomain appdomain shell}, exported3_radio_prop) + get_prop({coredomain appdomain shell}, exported3_system_prop) + userdebug_or_eng(` + get_prop(su, core_property_type) + get_prop(su, exported_dalvik_prop) + get_prop(su, exported_ffs_prop) + get_prop(su, exported_system_radio_prop) + get_prop(su, exported2_config_prop) + get_prop(su, exported2_radio_prop) + get_prop(su, exported2_system_prop) + get_prop(su, exported2_vold_prop) + get_prop(su, exported3_default_prop) + get_prop(su, exported3_radio_prop) + get_prop(su, exported3_system_prop) + ') + get_prop({domain -coredomain -appdomain}, vendor_default_prop) +') + +# Public readable properties +get_prop(domain, debug_prop) +get_prop(domain, exported_config_prop) +get_prop(domain, exported_default_prop) +get_prop(domain, exported_dumpstate_prop) +get_prop(domain, exported_fingerprint_prop) +get_prop(domain, exported_radio_prop) +get_prop(domain, exported_secure_prop) +get_prop(domain, exported_system_prop) +get_prop(domain, exported_vold_prop) +get_prop(domain, exported2_default_prop) +get_prop(domain, logd_prop) + +# Let everyone read log properties, so that liblog can avoid sending unloggable +# messages to logd. +get_prop(domain, log_property_type) +dontaudit domain property_type:file audit_access; +allow domain property_contexts_file:file r_file_perms; + +allow domain init:key search; +allow domain vold:key search; + +# logd access +write_logd(domain) + +# System file accesses. +allow domain system_file:dir { search getattr }; +allow domain system_file:file { execute read open getattr map }; +allow domain system_file:lnk_file { getattr read }; + +# Make sure system/vendor split doesn not affect non-treble +# devices +not_full_treble(` + allow domain vendor_file_type:dir { search getattr }; + allow domain vendor_file_type:file { execute read open getattr map }; + allow domain vendor_file_type:lnk_file { getattr read }; +') + +# All domains are allowed to open and read directories +# that contain HAL implementations (e.g. passthrough +# HALs require clients to have these permissions) +allow domain vendor_hal_file:dir r_dir_perms; + +# Everyone can read and execute all same process HALs +allow domain same_process_hal_file:dir r_dir_perms; +allow domain same_process_hal_file:file { execute read open getattr map }; + +# Any process can load vndk-sp libraries, which are system libraries +# used by same process HALs +allow domain vndk_sp_file:dir r_dir_perms; +allow domain vndk_sp_file:file { execute read open getattr map }; + +# All domains get access to /vendor/etc +allow domain vendor_configs_file:dir r_dir_perms; +allow domain vendor_configs_file:file { read open getattr }; + +full_treble_only(` + # Allow all domains to be able to follow /system/vendor and/or + # /vendor/odm symlinks. + allow domain vendor_file_type:lnk_file { getattr open read }; + + # This is required to be able to search & read /vendor/lib64 + # in order to lookup vendor libraries. The execute permission + # for coredomains is granted *only* for same process HALs + allow domain vendor_file:dir { getattr search }; + + # Allow reading and executing out of /vendor to all vendor domains + allow { domain -coredomain } vendor_file_type:dir r_dir_perms; + allow { domain -coredomain } vendor_file_type:file { read open getattr execute map }; + allow { domain -coredomain } vendor_file_type:lnk_file { getattr read }; +') + +# read and stat any sysfs symlinks +allow domain sysfs:lnk_file { getattr read }; + +# libc references /data/misc/zoneinfo for timezone related information +# This directory is considered to be a VNDK-stable +allow domain zoneinfo_data_file:file r_file_perms; +allow domain zoneinfo_data_file:dir r_dir_perms; + +# Lots of processes access current CPU information +r_dir_file(domain, sysfs_devices_system_cpu) + +r_dir_file(domain, sysfs_usb); + +# files under /data. +not_full_treble(` + allow domain system_data_file:dir getattr; +') +allow { coredomain appdomain } system_data_file:dir getattr; +# /data has the label system_data_file. Vendor components need the search +# permission on system_data_file for path traversal to /data/vendor. +allow domain system_data_file:dir search; +# TODO restrict this to non-coredomain +allow domain vendor_data_file:dir { getattr search }; + +# required by the dynamic linker +allow domain proc:lnk_file { getattr read }; + +# /proc/cpuinfo +allow domain proc_cpuinfo:file r_file_perms; + +# jemalloc needs to read /proc/sys/vm/overcommit_memory +allow domain proc_overcommit_memory:file r_file_perms; + +# profiling needs to read /proc/sys/kernel/perf_event_max_sample_rate +allow domain proc_perf:file r_file_perms; + +# toybox loads libselinux which stats /sys/fs/selinux/ +allow domain selinuxfs:dir search; +allow domain selinuxfs:file getattr; +allow domain sysfs:dir search; +allow domain selinuxfs:filesystem getattr; + +# For /acct/uid/*/tasks. +allow domain cgroup:dir { search write }; +allow domain cgroup:file w_file_perms; + +# Almost all processes log tracing information to +# /sys/kernel/debug/tracing/trace_marker +# The reason behind this is documented in b/6513400 +allow domain debugfs:dir search; +allow domain debugfs_tracing:dir search; +allow domain debugfs_tracing_debug:dir search; +allow domain debugfs_trace_marker:file w_file_perms; + +# Filesystem access. +allow domain fs_type:filesystem getattr; +allow domain fs_type:dir getattr; + +# Restrict all domains to a whitelist for common socket types. Additional +# ioctl commands may be added to individual domains, but this sets safe +# defaults for all processes. Note that granting this whitelist to domain does +# not grant the ioctl permission on these socket types. That must be granted +# separately. +allowxperm domain domain:{ rawip_socket tcp_socket udp_socket } + ioctl { unpriv_sock_ioctls unpriv_tty_ioctls }; +# default whitelist for unix sockets. +allowxperm domain domain:{ unix_dgram_socket unix_stream_socket } + ioctl unpriv_unix_sock_ioctls; + +# Restrict PTYs to only whitelisted ioctls. +# Note that granting this whitelist to domain does +# not grant the wider ioctl permission. That must be granted +# separately. +allowxperm domain devpts:chr_file ioctl unpriv_tty_ioctls; + +# Workaround for policy compiler being too aggressive and removing hwservice_manager_type +# when it's not explicitly used in allow rules +allow { domain -domain } hwservice_manager_type:hwservice_manager { add find }; +# Workaround for policy compiler being too aggressive and removing vndservice_manager_type +# when it's not explicitly used in allow rules +allow { domain -domain } vndservice_manager_type:service_manager { add find }; + +# Under ASAN, processes will try to read /data, as the sanitized libraries are there. +with_asan(`allow domain system_data_file:dir getattr;') + +### +### neverallow rules +### + +# All socket ioctls must be restricted to a whitelist. +neverallowxperm domain domain:socket_class_set ioctl { 0 }; + +# b/68014825 and https://android-review.googlesource.com/516535 +# rfc6093 says that processes should not use the TCP urgent mechanism +neverallowxperm domain domain:socket_class_set ioctl { SIOCATMARK }; + +# TIOCSTI is only ever used for exploits. Block it. +# b/33073072, b/7530569 +# http://www.openwall.com/lists/oss-security/2016/09/26/14 +neverallowxperm * devpts:chr_file ioctl TIOCSTI; + +# Do not allow any domain other than init to create unlabeled files. +neverallow { domain -init -recovery } unlabeled:dir_file_class_set create; + +# Limit device node creation to these whitelisted domains. +neverallow { + domain + -kernel + -init + -ueventd + -vold +} self:global_capability_class_set mknod; + +# Limit raw I/O to these whitelisted domains. Do not apply to debug builds. +neverallow { + domain + userdebug_or_eng(`-domain') + -kernel + -init + -recovery + -ueventd + -healthd + -uncrypt + -tee +} self:global_capability_class_set sys_rawio; + +# No process can map low memory (< CONFIG_LSM_MMAP_MIN_ADDR). +neverallow * self:memprotect mmap_zero; + +# No domain needs mac_override as it is unused by SELinux. +neverallow * self:global_capability2_class_set mac_override; + +# Disallow attempts to set contexts not defined in current policy +# This helps guarantee that unknown or dangerous contents will not ever +# be set. +neverallow * self:global_capability2_class_set mac_admin; + +# Once the policy has been loaded there shall be none to modify the policy. +# It is sealed. +neverallow * kernel:security load_policy; + +# Only init prior to switching context should be able to set enforcing mode. +# init starts in kernel domain and switches to init domain via setcon in +# the init.rc, so the setenforce occurs while still in kernel. After +# switching domains, there is never any need to setenforce again by init. +neverallow * kernel:security setenforce; +neverallow { domain -kernel } kernel:security setcheckreqprot; + +# No booleans in AOSP policy, so no need to ever set them. +neverallow * kernel:security setbool; + +# Adjusting the AVC cache threshold. +# Not presently allowed to anything in policy, but possibly something +# that could be set from init.rc. +neverallow { domain -init } kernel:security setsecparam; + +# Only init, ueventd, shell and system_server should be able to access HW RNG +neverallow { + domain + -init + -shell # For CTS and is restricted to getattr in shell.te + -system_server + -ueventd +} hw_random_device:chr_file *; +# b/78174219 b/64114943 +neverallow { + domain + -init + -shell # stat of /dev, getattr only + -vendor_init + -ueventd +} keychord_device:chr_file *; + +# Ensure that all entrypoint executables are in exec_type or postinstall_file. +neverallow * { file_type -exec_type -postinstall_file }:file entrypoint; + +# Ensure that nothing in userspace can access /dev/mem or /dev/kmem +neverallow { + domain + -shell # For CTS and is restricted to getattr in shell.te + -ueventd # Further restricted in ueventd.te +} kmem_device:chr_file *; +neverallow * kmem_device:chr_file ~{ create relabelto unlink setattr getattr }; + +#Ensure that nothing in userspace can access /dev/port +neverallow { + domain + -shell # Shell user should not have any abilities outside of getattr + -ueventd +} port_device:chr_file *; +neverallow * port_device:chr_file ~{ create relabelto unlink setattr getattr }; +# Only init should be able to configure kernel usermodehelpers or +# security-sensitive proc settings. +neverallow { domain -init } usermodehelper:file { append write }; +neverallow { domain -init -ueventd } sysfs_usermodehelper:file { append write }; +neverallow { domain -init -vendor_init } proc_security:file { append open read write }; + +# No domain should be allowed to ptrace init. +neverallow * init:process ptrace; + +# Init can't do anything with binder calls. If this neverallow rule is being +# triggered, it's probably due to a service with no SELinux domain. +neverallow * init:binder *; +neverallow * vendor_init:binder *; + +# Don't allow raw read/write/open access to block_device +# Rather force a relabel to a more specific type +neverallow { domain -kernel -init -recovery } block_device:blk_file { open read write }; + +# Do not allow renaming of block files or character files +# Ability to do so can lead to possible use in an exploit chain +# e.g. https://googleprojectzero.blogspot.com/2016/12/chrome-os-exploit-one-byte-overflow-and.html +neverallow * *:{ blk_file chr_file } rename; + +# Don't allow raw read/write/open access to generic devices. +# Rather force a relabel to a more specific type. +neverallow domain device:chr_file { open read write }; + +# Limit what domains can mount filesystems or change their mount flags. +# sdcard_type / vfat is exempt as a larger set of domains need +# this capability, including device-specific domains. +neverallow { domain -kernel -init -recovery -vold -zygote -update_engine -otapreopt_chroot } { fs_type -sdcard_type }:filesystem { mount remount relabelfrom relabelto }; + +# +# Assert that, to the extent possible, we're not loading executable content from +# outside the rootfs or /system partition except for a few whitelisted domains. +# +neverallow { + domain + -appdomain + with_asan(`-asan_extract') + -dumpstate + -shell + userdebug_or_eng(`-su') + -webview_zygote + -zygote + userdebug_or_eng(`-mediaextractor') +} { + file_type + -system_file + -vendor_file_type + -exec_type + -postinstall_file +}:file execute; + +neverallow { + domain + -appdomain # for oemfs + -bootanim # for oemfs + -recovery # for /tmp/update_binary in tmpfs +} { fs_type -rootfs }:file execute; + +# Files from cache should never be executed +neverallow domain { cache_file cache_backup_file cache_private_backup_file cache_recovery_file }:file execute; + +# Protect most domains from executing arbitrary content from /data. +neverallow { + domain + -appdomain +} { + data_file_type + -dalvikcache_data_file + -system_data_file # shared libs in apks + -apk_data_file +}:file no_x_file_perms; + +# The test files and executables MUST not be accessible to any domain +neverallow { domain userdebug_or_eng(`-kernel') } nativetest_data_file:file_class_set no_w_file_perms; +neverallow domain nativetest_data_file:dir no_w_dir_perms; +neverallow { domain userdebug_or_eng(`-shell') } nativetest_data_file:file no_x_file_perms; + +# Only the init property service should write to /data/property and /dev/__properties__ +neverallow { domain -init } property_data_file:dir no_w_dir_perms; +neverallow { domain -init } property_data_file:file { no_w_file_perms no_x_file_perms }; +neverallow { domain -init } property_type:file { no_w_file_perms no_x_file_perms }; +neverallow { domain -init } properties_device:file { no_w_file_perms no_x_file_perms }; +neverallow { domain -init } properties_serial:file { no_w_file_perms no_x_file_perms }; + +# Nobody should be doing writes to /system & /vendor +# These partitions are intended to be read-only and must never be +# modified. Doing so would violate important Android security guarantees +# and invalidate dm-verity signatures. +neverallow { + domain + with_asan(`-asan_extract') +} { + system_file + vendor_file_type + exec_type +}:dir_file_class_set { create write setattr relabelfrom append unlink link rename }; + +neverallow { domain -kernel with_asan(`-asan_extract') } { system_file vendor_file_type exec_type }:dir_file_class_set relabelto; + +# Don't allow mounting on top of /system files or directories +neverallow * exec_type:dir_file_class_set mounton; +neverallow { domain -init } { system_file vendor_file_type }:dir_file_class_set mounton; + +# Nothing should be writing to files in the rootfs. +neverallow * rootfs:file { create write setattr relabelto append unlink link rename }; + +# Restrict context mounts to specific types marked with +# the contextmount_type attribute. +neverallow * {fs_type -contextmount_type}:filesystem relabelto; + +# Ensure that context mount types are not writable, to ensure that +# the write to /system restriction above is not bypassed via context= +# mount to another type. +neverallow * contextmount_type:dir_file_class_set + { create write setattr relabelfrom relabelto append unlink link rename }; + +# Do not allow service_manager add for default service labels. +# Instead domains should use a more specific type such as +# system_app_service rather than the generic type. +# New service_types are defined in {,hw,vnd}service.te and new mappings +# from service name to service_type are defined in {,hw,vnd}service_contexts. +neverallow * default_android_service:service_manager add; +neverallow * default_android_vndservice:service_manager { add find }; +neverallow * default_android_hwservice:hwservice_manager { add find }; + +# Looking up the base class/interface of all HwBinder services is a bad idea. +# hwservicemanager currently offer such lookups only to make it so that security +# decisions are expressed in SELinux policy. However, it's unclear whether this +# lookup has security implications. If it doesn't, hwservicemanager should be +# modified to not offer this lookup. +# This rule can be removed if hwservicemanager is modified to not permit these +# lookups. +neverallow * hidl_base_hwservice:hwservice_manager find; + +# Require that domains explicitly label unknown properties, and do not allow +# anyone but init to modify unknown properties. +neverallow { domain -init -vendor_init } default_prop:property_service set; +neverallow { domain -init -vendor_init } mmc_prop:property_service set; + +compatible_property_only(` + neverallow { domain -init } default_prop:property_service set; + neverallow { domain -init } mmc_prop:property_service set; + neverallow { domain -init -vendor_init } exported_default_prop:property_service set; + neverallow { domain -init } exported_secure_prop:property_service set; + neverallow { domain -init } exported2_default_prop:property_service set; + neverallow { domain -init -vendor_init } exported3_default_prop:property_service set; + neverallow { domain -init -vendor_init } vendor_default_prop:property_service set; +') + +# Only core domains are allowed to access package_manager properties +neverallow { domain -init -system_server } pm_prop:property_service set; +neverallow { domain -coredomain } pm_prop:file no_rw_file_perms; + +compatible_property_only(` + neverallow { domain -init -system_server -vendor_init } exported_pm_prop:property_service set; + neverallow { domain -coredomain -vendor_init } exported_pm_prop:file no_rw_file_perms; +') + +# Do not allow reading device's serial number from system properties except form +# a few whitelisted domains. +neverallow { + domain + -adbd + -dumpstate + -hal_drm_server + -hal_cas_server + -init + -mediadrmserver + -recovery + -shell + -system_server + -vendor_init +} serialno_prop:file r_file_perms; + +# Do not allow reading the last boot timestamp from system properties +neverallow { domain -init -system_server -dumpstate } firstboot_prop:file r_file_perms; + +neverallow { + domain + -init + -recovery + -system_server + -shell # Shell is further restricted in shell.te + -ueventd # Further restricted in ueventd.te +} frp_block_device:blk_file no_rw_file_perms; + +# The metadata block device is set aside for device encryption and +# verified boot metadata. It may be reset at will and should not +# be used by other domains. +neverallow { + domain + -init + -recovery + -vold + -e2fs + -fsck +} metadata_block_device:blk_file { append link rename write open read ioctl lock }; + +# No domain other than recovery and update_engine can write to system partition(s). +neverallow { domain -recovery -update_engine } system_block_device:blk_file { write append }; + +# No domains other than install_recovery or recovery can write to recovery. +neverallow { domain -install_recovery -recovery } recovery_block_device:blk_file { write append }; + +# No domains other than a select few can access the misc_block_device. This +# block device is reserved for OTA use. +# Do not assert this rule on userdebug/eng builds, due to some devices using +# this partition for testing purposes. +neverallow { + domain + userdebug_or_eng(`-domain') # exclude debuggable builds + -hal_bootctl_server + -init + -uncrypt + -update_engine + -vendor_init + -vold + -recovery + -ueventd +} misc_block_device:blk_file { append link relabelfrom rename write open read ioctl lock }; + +# Only (hw|vnd|)servicemanager should be able to register with binder as the context manager +neverallow { domain -servicemanager -hwservicemanager -vndservicemanager } *:binder set_context_mgr; +# The service managers are only allowed to access their own device node +neverallow servicemanager hwbinder_device:chr_file no_rw_file_perms; +neverallow servicemanager vndbinder_device:chr_file no_rw_file_perms; +neverallow hwservicemanager binder_device:chr_file no_rw_file_perms; +neverallow hwservicemanager vndbinder_device:chr_file no_rw_file_perms; +neverallow vndservicemanager binder_device:chr_file no_rw_file_perms; +neverallow vndservicemanager hwbinder_device:chr_file no_rw_file_perms; + +# On full TREBLE devices, only core components and apps can use Binder and servicemanager. Non-core +# domain apps need this because Android framework offers many of its services to apps as Binder +# services. +full_treble_only(` + neverallow { + domain + -coredomain + -appdomain + -binder_in_vendor_violators # TODO(b/35870313): Remove once all violations are gone + } binder_device:chr_file rw_file_perms; +') +full_treble_only(` + neverallow { + domain + -coredomain + -appdomain # restrictions for vendor apps are declared lower down + -binder_in_vendor_violators # TODO(b/35870313): Remove once all violations are gone + } service_manager_type:service_manager find; +') +full_treble_only(` + # Vendor apps are permited to use only stable public services. If they were to use arbitrary + # services which can change any time framework/core is updated, breakage is likely. + neverallow { + appdomain + -coredomain + } { + service_manager_type + -app_api_service + -ephemeral_app_api_service + -audioserver_service # TODO(b/36783122) remove exemptions below once app_api_service is fixed + -cameraserver_service + -drmserver_service + -keystore_service + -mediadrmserver_service + -mediaextractor_service + -mediametrics_service + -mediaserver_service + -nfc_service + -radio_service + -virtual_touchpad_service + -vr_hwc_service + -vr_manager_service + }:service_manager find; +') +full_treble_only(` + neverallow { + domain + -coredomain + -appdomain + -binder_in_vendor_violators # TODO(b/35870313): Remove once all violations are gone + } servicemanager:binder { call transfer }; +') + +# On full TREBLE devices, only vendor components, shell, and su can use VendorBinder. +full_treble_only(` + neverallow { + coredomain + -shell + userdebug_or_eng(`-su') + -ueventd # uevent is granted create for this device, but we still neverallow I/O below + } vndbinder_device:chr_file rw_file_perms; +') +full_treble_only(` + neverallow ueventd vndbinder_device:chr_file { read write append ioctl }; +') +full_treble_only(` + neverallow { + coredomain + -shell + userdebug_or_eng(`-su') + } vndservice_manager_type:service_manager *; +') +full_treble_only(` + neverallow { + coredomain + -shell + userdebug_or_eng(`-su') + } vndservicemanager:binder *; +') + +# On full TREBLE devices, socket communications between core components and vendor components are +# not permitted. + # Most general rules first, more specific rules below. + + # Core domains are not permitted to initiate communications to vendor domain sockets. + # We are not restricting the use of already established sockets because it is fine for a process + # to obtain an already established socket via some public/official/stable API and then exchange + # data with its peer over that socket. The wire format in this scenario is dicatated by the API + # and thus does not break the core-vendor separation. +full_treble_only(` + neverallow_establish_socket_comms({ + coredomain + -init + -adbd + }, { + domain + -coredomain + -socket_between_core_and_vendor_violators + }); +') + # Vendor domains are not permitted to initiate communications to core domain sockets +full_treble_only(` + neverallow_establish_socket_comms({ + domain + -coredomain + -appdomain + -socket_between_core_and_vendor_violators + }, { + coredomain + -logd # Logging by writing to logd Unix domain socket is public API + -netd # netdomain needs this + -mdnsd # netdomain needs this + userdebug_or_eng(`-su') # communications with su are permitted only on userdebug or eng builds + -init + -incidentd # TODO(b/35870313): Remove incidentd from this list once vendor domains no longer declare Binder services + -tombstoned # TODO(b/36604251): Remove tombstoned from this list once mediacodec (OMX HAL) no longer declares Binder services + }); +') + + # Vendor domains (except netdomain) are not permitted to initiate communications to netd sockets +full_treble_only(` + neverallow_establish_socket_comms({ + domain + -coredomain + -netdomain + -socket_between_core_and_vendor_violators + }, netd); +') + + # Vendor domains are not permitted to initiate create/open sockets owned by core domains +full_treble_only(` + neverallow { + domain + -coredomain + -appdomain # appdomain restrictions below + -data_between_core_and_vendor_violators # b/70393317 + -socket_between_core_and_vendor_violators + -vendor_init + } { + coredomain_socket + core_data_file_type + unlabeled # used only by core domains + }:sock_file ~{ append getattr ioctl read write }; +') +full_treble_only(` + neverallow { + appdomain + -coredomain + } { + coredomain_socket + unlabeled # used only by core domains + core_data_file_type + -app_data_file + -pdx_endpoint_socket_type # used by VR layer + -pdx_channel_socket_type # used by VR layer + }:sock_file ~{ append getattr ioctl read write }; +') + + # Core domains are not permitted to create/open sockets owned by vendor domains +full_treble_only(` + neverallow { + coredomain + -init + -ueventd + -socket_between_core_and_vendor_violators + } { + file_type + dev_type + -coredomain_socket + -core_data_file_type + -unlabeled + }:sock_file ~{ append getattr ioctl read write }; +') + +# On TREBLE devices, vendor and system components are only allowed to share +# files by passing open FDs over hwbinder. Ban all directory access and all file +# accesses other than what can be applied to an open FD such as +# ioctl/stat/read/write/append. This is enforced by segregating /data. +# Vendor domains may directly access file in /data/vendor by path, but may only +# access files outside of /data/vendor via an open FD passed over hwbinder. +# Likewise, core domains may only directly access files outside /data/vendor by +# path and files in /data/vendor by open FD. +full_treble_only(` + # only coredomains may only access core_data_file_type, particularly not + # /data/vendor + neverallow { + coredomain + -appdomain # TODO(b/34980020) remove exemption for appdomain + -data_between_core_and_vendor_violators + -init + -vold_prepare_subdirs + } { + data_file_type + -core_data_file_type + }:file_class_set ~{ append getattr ioctl read write }; +') +full_treble_only(` + neverallow { + coredomain + -appdomain # TODO(b/34980020) remove exemption for appdomain + -data_between_core_and_vendor_violators + -init + -vold_prepare_subdirs + } { + data_file_type + -core_data_file_type + # TODO(b/72998741) Remove exemption. Further restricted in a subsequent + # neverallow. Currently only getattr and search are allowed. + -vendor_data_file + }:dir *; + +') +full_treble_only(` + # vendor domains may only access files in /data/vendor, never core_data_file_types + neverallow { + domain + -appdomain # TODO(b/34980020) remove exemption for appdomain + -coredomain + -data_between_core_and_vendor_violators # TODO(b/34980020) Remove once all violators have been cleaned up + -vendor_init + } { + core_data_file_type + # libc includes functions like mktime and localtime which attempt to access + # files in /data/misc/zoneinfo/tzdata file. These functions are considered + # vndk-stable and thus must be allowed for all processes. + -zoneinfo_data_file + userdebug_or_eng(`-exagear_debug_file') + }:file_class_set ~{ append getattr ioctl read write }; + neverallow { + vendor_init + -data_between_core_and_vendor_violators + } { + core_data_file_type + -unencrypted_data_file + -zoneinfo_data_file + userdebug_or_eng(`-exagear_debug_file') + }:file_class_set ~{ append getattr ioctl read write }; + # vendor init needs to be able to read unencrypted_data_file to create directories with FBE. + # The vendor init binary lives on the system partition so there is not a concern with stability. + neverallow vendor_init unencrypted_data_file:file ~r_file_perms; +') +full_treble_only(` + # vendor domains may only access dirs in /data/vendor, never core_data_file_types + neverallow { + domain + -appdomain # TODO(b/34980020) remove exemption for appdomain + -coredomain + -data_between_core_and_vendor_violators + -vendor_init + } { + core_data_file_type + -system_data_file # default label for files on /data. Covered below... + -vendor_data_file + -zoneinfo_data_file + userdebug_or_eng(`-exagear_debug_file') + }:dir *; + neverallow { + vendor_init + -data_between_core_and_vendor_violators + } { + core_data_file_type + -unencrypted_data_file + -system_data_file + -vendor_data_file + -zoneinfo_data_file + userdebug_or_eng(`-exagear_debug_file') + }:dir *; + # vendor init needs to be able to read unencrypted_data_file to create directories with FBE. + # The vendor init binary lives on the system partition so there is not a concern with stability. + neverallow vendor_init unencrypted_data_file:dir ~search; +') +full_treble_only(` + # vendor domains may only access dirs in /data/vendor, never core_data_file_types + neverallow { + domain + -appdomain # TODO(b/34980020) remove exemption for appdomain + -coredomain + -data_between_core_and_vendor_violators # TODO(b/34980020) Remove once all violators have been cleaned up + } { + system_data_file # default label for files on /data. Covered below + }:dir ~{ getattr search }; +') + +full_treble_only(` + # coredomains may not access dirs in /data/vendor. + neverallow { + coredomain + -data_between_core_and_vendor_violators # TODO(b/34980020) Remove once all violators have been cleaned up + -init + -vold # vold creates per-user storage for both system and vendor + -vold_prepare_subdirs + } { + vendor_data_file # default label for files on /data. Covered below + }:dir ~{ getattr search }; +') + +full_treble_only(` + # coredomains may not access dirs in /data/vendor. + neverallow { + coredomain + -data_between_core_and_vendor_violators # TODO(b/34980020) Remove once all violators have been cleaned up + -init + } { + vendor_data_file # default label for files on /data/vendor{,_ce,_de}. + }:file_class_set ~{ append getattr ioctl read write }; +') + +# On TREBLE devices, a limited set of files in /vendor are accessible to +# only a few whitelisted coredomains to keep system/vendor separation. +full_treble_only(` + # Limit access to /vendor/app + neverallow { + coredomain + -appdomain + -dex2oat + -idmap + -init + -installd + userdebug_or_eng(`-perfprofd') + -postinstall_dexopt + -system_server + } vendor_app_file:dir { open read getattr search }; +') + +full_treble_only(` + neverallow { + coredomain + -appdomain + -dex2oat + -idmap + -init + -installd + userdebug_or_eng(`-perfprofd') + -postinstall_dexopt + -system_server + } vendor_app_file:file r_file_perms; +') + +full_treble_only(` + # Limit access to /vendor/overlay + neverallow { + coredomain + -appdomain + -idmap + -init + -installd + -system_server + -webview_zygote + -zygote + } vendor_overlay_file:dir { getattr open read search }; +') + +full_treble_only(` + neverallow { + coredomain + -appdomain + -idmap + -init + -installd + -system_server + -webview_zygote + -zygote + } vendor_overlay_file:file r_file_perms; +') + +full_treble_only(` + # Non-vendor domains are not allowed to file execute shell + # from vendor + neverallow { + coredomain + -init + -shell + } vendor_shell_exec:file { execute execute_no_trans }; +') + +full_treble_only(` + # Do not allow vendor components to execute files from system + # except for the ones whitelist here. + neverallow { + domain + -coredomain + -appdomain + -vendor_executes_system_violators + -vendor_init + } { + exec_type + -vendor_file_type + -crash_dump_exec + -netutils_wrapper_exec + }:file { entrypoint execute execute_no_trans }; +') + +full_treble_only(` + # Do not allow system components to execute files from vendor + # except for the ones whitelisted here. + neverallow { + coredomain + -init + -shell + -system_executes_vendor_violators + } { + vendor_file_type + -same_process_hal_file + -vndk_sp_file + -vendor_app_file + }:file execute; +') + +full_treble_only(` + neverallow { + coredomain + -shell + -system_executes_vendor_violators + } vendor_file_type:file execute_no_trans; +') + +# Only authorized processes should be writing to files in /data/dalvik-cache +neverallow { + domain + -init # TODO: limit init to relabelfrom for files + -zygote + -installd + -postinstall_dexopt + -cppreopts + -dex2oat + -otapreopt_slot +} dalvikcache_data_file:file no_w_file_perms; + +neverallow { + domain + -init + -installd + -postinstall_dexopt + -cppreopts + -dex2oat + -zygote + -otapreopt_slot +} dalvikcache_data_file:dir no_w_dir_perms; + +# Only system_server should be able to send commands via the zygote socket +neverallow { domain -zygote -system_server } zygote:unix_stream_socket connectto; +neverallow { domain -system_server } zygote_socket:sock_file write; + +neverallow { domain -system_server -webview_zygote } webview_zygote:unix_stream_socket connectto; +neverallow { domain -system_server } webview_zygote:sock_file write; + +neverallow { + domain + -tombstoned + -crash_dump + -dumpstate + -incidentd + -system_server + + # Processes that can't exec crash_dump + -mediacodec + -mediaextractor +} tombstoned_crash_socket:unix_stream_socket connectto; + +# Never allow anyone except dumpstate, incidentd, or the system server to connect or write to +# the tombstoned intercept socket. +neverallow { domain -dumpstate -incidentd -system_server } tombstoned_intercept_socket:sock_file write; +neverallow { domain -dumpstate -incidentd -system_server } tombstoned_intercept_socket:unix_stream_socket connectto; + +# Android does not support System V IPCs. +# +# The reason for this is due to the fact that, by design, they lead to global +# kernel resource leakage. +# +# For example, there is no way to automatically release a SysV semaphore +# allocated in the kernel when: +# +# - a buggy or malicious process exits +# - a non-buggy and non-malicious process crashes or is explicitly killed. +# +# Killing processes automatically to make room for new ones is an +# important part of Android's application lifecycle implementation. This means +# that, even assuming only non-buggy and non-malicious code, it is very likely +# that over time, the kernel global tables used to implement SysV IPCs will fill +# up. +neverallow * *:{ shm sem msg msgq } *; + +# Do not mount on top of symlinks, fifos, or sockets. +# Feature parity with Chromium LSM. +neverallow * { file_type fs_type dev_type }:{ lnk_file fifo_file sock_file } mounton; + +# Nobody should be able to execute su on user builds. +# On userdebug/eng builds, only dumpstate, shell, and +# su itself execute su. +neverallow { domain userdebug_or_eng(`-dumpstate -shell -su') } su_exec:file no_x_file_perms; + +# Do not allow the introduction of new execmod rules. Text relocations +# and modification of executable pages are unsafe. +# The only exceptions are for NDK text relocations associated with +# https://code.google.com/p/android/issues/detail?id=23203 +# which, long term, need to go away. +neverallow * { + file_type + -apk_data_file + -app_data_file + -asec_public_file +}:file execmod; + +# Do not allow making the stack or heap executable. +# We would also like to minimize execmem but it seems to be +# required by some device-specific service domains. +neverallow * self:process { execstack execheap }; + +# prohibit non-zygote spawned processes from using shared libraries +# with text relocations. b/20013628 . +neverallow { domain -untrusted_app_all } file_type:file execmod; + +neverallow { domain -init } proc:{ file dir } mounton; + +# Ensure that all types assigned to processes are included +# in the domain attribute, so that all allow and neverallow rules +# written on domain are applied to all processes. +# This is achieved by ensuring that it is impossible to transition +# from a domain to a non-domain type and vice versa. +# TODO - rework this: neverallow domain ~domain:process { transition dyntransition }; +neverallow ~domain domain:process { transition dyntransition }; + +# +# Only system_app and system_server should be creating or writing +# their files. The proper way to share files is to setup +# type transitions to a more specific type or assigning a type +# to its parent directory via a file_contexts entry. +# Example type transition: +# mydomain.te:file_type_auto_trans(mydomain, system_data_file, new_file_type) +# +neverallow { + domain + -system_server + -system_app + -init + -installd # for relabelfrom and unlink, check for this in explicit neverallow + -vold_prepare_subdirs # For unlink + with_asan(`-asan_extract') +} system_data_file:file no_w_file_perms; +# do not grant anything greater than r_file_perms and relabelfrom unlink +# to installd +neverallow installd system_data_file:file ~{ r_file_perms relabelfrom unlink }; + +# respect system_app sandboxes +neverallow { + domain + -appdomain # finer-grained rules for appdomain are listed below + -system_server #populate com.android.providers.settings/databases/settings.db. + -installd # creation of app sandbox + -traced_probes # resolve inodes for i/o tracing. + # only needs open and read, the rest is neverallow in + # traced_probes.te. +} system_app_data_file:dir_file_class_set { create unlink open }; +neverallow { + isolated_app + untrusted_app_all # finer-grained rules for appdomain are listed below + ephemeral_app + priv_app +} system_app_data_file:dir_file_class_set { create unlink open }; + + +# Services should respect app sandboxes +neverallow { + domain + -appdomain + -installd # creation of sandbox +} app_data_file:dir_file_class_set { create unlink }; + +# +# Only these domains should transition to shell domain. This domain is +# permissible for the "shell user". If you need a process to exec a shell +# script with differing privilege, define a domain and set up a transition. +# +neverallow { + domain + -adbd + -init + -runas + -zygote +} shell:process { transition dyntransition }; + +# Only domains spawned from zygote and runas may have the appdomain attribute. +neverallow { domain -runas -webview_zygote -zygote } { + appdomain -shell userdebug_or_eng(`-su') +}:process { transition dyntransition }; + +# Minimize read access to shell- or app-writable symlinks. +# This is to prevent malicious symlink attacks. +neverallow { + domain + -appdomain + -installd + -uncrypt # TODO: see if we can remove +} app_data_file:lnk_file read; + +neverallow { + domain + -shell + userdebug_or_eng(`-uncrypt') + -installd +} shell_data_file:lnk_file read; + +# In addition to the symlink reading restrictions above, restrict +# write access to shell owned directories. The /data/local/tmp +# directory is untrustworthy, and non-whitelisted domains should +# not be trusting any content in those directories. +neverallow { + domain + -adbd + -dumpstate + -installd + -init + -shell + -vold +} shell_data_file:dir no_w_dir_perms; + +neverallow { + domain + -adbd + -appdomain + -dumpstate + -init + -installd + -system_server # why? + userdebug_or_eng(`-uncrypt') +} shell_data_file:dir { open search }; + +# Same as above for /data/local/tmp files. We allow shell files +# to be passed around by file descriptor, but not directly opened. +neverallow { + domain + -adbd + -appdomain + -dumpstate + -installd + userdebug_or_eng(`-uncrypt') +} shell_data_file:file open; + +# servicemanager and vndservicemanager are the only processes which handle the +# service_manager list request +neverallow * ~{ + servicemanager + vndservicemanager + }:service_manager list; + +# hwservicemanager is the only process which handles hw list requests +neverallow * ~{ + hwservicemanager + }:hwservice_manager list; + +# only service_manager_types can be added to service_manager +# TODO - rework this: neverallow * ~service_manager_type:service_manager { add find }; + +# Prevent assigning non property types to properties +# TODO - rework this: neverallow * ~property_type:property_service set; + +# Domain types should never be assigned to any files other +# than the /proc/pid files associated with a process. The +# executable file used to enter a domain should be labeled +# with its own _exec type, not with the domain type. +# Conventionally, this looks something like: +# $ cat mydaemon.te +# type mydaemon, domain; +# type mydaemon_exec, exec_type, file_type; +# init_daemon_domain(mydaemon) +# $ grep mydaemon file_contexts +# /system/bin/mydaemon -- u:object_r:mydaemon_exec:s0 +neverallow * domain:file { execute execute_no_trans entrypoint }; + +# Do not allow access to the generic debugfs label. This is too broad. +# Instead, if access to part of debugfs is desired, it should have a +# more specific label. +# TODO: fix system_server and dumpstate +neverallow { domain -init -vendor_init -system_server -dumpstate } debugfs:file no_rw_file_perms; + +# Profiles contain untrusted data and profman parses that. We should only run +# in from installd forked processes. +neverallow { + domain + -installd + -profman +} profman_exec:file no_x_file_perms; + +# Enforce restrictions on kernel module origin. +# Do not allow kernel module loading except from system, +# vendor, and boot partitions. +neverallow * ~{ system_file vendor_file rootfs }:system module_load; + +# Only allow filesystem caps to be set at build time. Runtime changes +# to filesystem capabilities are not permitted. +neverallow * self:global_capability_class_set setfcap; + +# Enforce AT_SECURE for executing crash_dump. +neverallow domain crash_dump:process noatsecure; + +# Do not permit non-core domains to register HwBinder services which are +# guaranteed to be provided by core domains only. +neverallow ~coredomain coredomain_hwservice:hwservice_manager add; + +# Do not permit the registeration of HwBinder services which are guaranteed to +# be passthrough only (i.e., run in the process of their clients instead of a +# separate server process). +neverallow * same_process_hwservice:hwservice_manager add; + +# On TREBLE devices, most coredomains should not access vendor_files. +# TODO(b/71553434): Remove exceptions here. +full_treble_only(` + neverallow { + coredomain + -appdomain + -bootanim + -crash_dump + -init + -kernel + -perfprofd + -ueventd + } vendor_file:file { no_w_file_perms no_x_file_perms open }; +') + +# Minimize dac_override and dac_read_search. +# Instead of granting them it is usually better to add the domain to +# a Unix group or change the permissions of a file. +neverallow { + domain + -dnsmasq + -dumpstate + -init + -installd + -install_recovery + -lmkd + -netd + -perfprofd + -postinstall_dexopt + -recovery + -sdcardd + -tee + -ueventd + -uncrypt + -vendor_init + -vold + -vold_prepare_subdirs + -zygote +} self:capability dac_override; +neverallow { domain -traced_probes } self:capability dac_read_search; + +# If an already existing file is opened with O_CREAT, the kernel might generate +# a false report of a create denial. Silence these denials and make sure that +# inappropriate permissions are not granted. + +# These filesystems don't allow files or directories to be created, so the permission +# to do so should never be granted. +neverallow domain { + proc_type + sysfs_type +}:dir { add_name create link remove_name rename reparent rmdir write }; + +# cgroupfs directories can be created, but not files within them. +neverallow domain cgroup:file create; + +dontaudit domain proc_type:dir write; +dontaudit domain sysfs_type:dir write; +dontaudit domain cgroup:file create; + +# These are only needed in permissive mode - in enforcing mode the +# directory write check fails and so these are never attempted. +userdebug_or_eng(` + dontaudit domain proc_type:dir add_name; + dontaudit domain sysfs_type:dir add_name; + dontaudit domain proc_type:file create; + dontaudit domain sysfs_type:file create; +') + +# Platform must not have access to /mnt/vendor. +neverallow { + coredomain + -init +} mnt_vendor_file:dir *; diff --git a/aosp/system/sepolicy/prebuilts/api/28.0/public/file.te b/aosp/system/sepolicy/prebuilts/api/28.0/public/file.te new file mode 100644 index 000000000..13a34b409 --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/28.0/public/file.te @@ -0,0 +1,419 @@ +# Filesystem types +type labeledfs, fs_type; +type pipefs, fs_type; +type sockfs, fs_type; +type rootfs, fs_type; +type proc, fs_type, proc_type; +# Security-sensitive proc nodes that should not be writable to most. +type proc_security, fs_type, proc_type; +type proc_drop_caches, fs_type, proc_type; +type proc_overcommit_memory, fs_type, proc_type; +type proc_min_free_order_shift, fs_type, proc_type; +# proc, sysfs, or other nodes that permit configuration of kernel usermodehelpers. +type usermodehelper, fs_type, proc_type; +type sysfs_usermodehelper, fs_type, sysfs_type; +type qtaguid_proc, fs_type, mlstrustedobject, proc_type; +type proc_qtaguid_stat, fs_type, mlstrustedobject, proc_type; +type proc_bluetooth_writable, fs_type, proc_type; +type proc_abi, fs_type, proc_type; +type proc_asound, fs_type, proc_type; +type proc_buddyinfo, fs_type, proc_type; +type proc_cmdline, fs_type, proc_type; +type proc_cpuinfo, fs_type, proc_type; +type proc_dirty, fs_type, proc_type; +type proc_diskstats, fs_type, proc_type; +type proc_extra_free_kbytes, fs_type, proc_type; +type proc_filesystems, fs_type, proc_type; +type proc_hostname, fs_type, proc_type; +type proc_hung_task, fs_type, proc_type; +type proc_interrupts, fs_type, proc_type; +type proc_iomem, fs_type, proc_type; +type proc_kmsg, fs_type, proc_type; +type proc_loadavg, fs_type, proc_type; +type proc_max_map_count, fs_type, proc_type; +type proc_meminfo, fs_type, proc_type; +type proc_misc, fs_type, proc_type; +type proc_modules, fs_type, proc_type; +type proc_mounts, fs_type, proc_type; +type proc_net, fs_type, proc_type; +type proc_net_route, fs_type, proc_type; +type proc_page_cluster, fs_type, proc_type; +type proc_pagetypeinfo, fs_type, proc_type; +type proc_panic, fs_type, proc_type; +type proc_perf, fs_type, proc_type; +type proc_pid_max, fs_type, proc_type; +type proc_pipe_conf, fs_type, proc_type; +type proc_random, fs_type, proc_type; +type proc_sched, fs_type, proc_type; +type proc_stat, fs_type, proc_type; +type proc_swaps, fs_type, proc_type; +type proc_sysrq, fs_type, proc_type; +type proc_timer, fs_type, proc_type; +type proc_tty_drivers, fs_type, proc_type; +type proc_uid_cputime_showstat, fs_type, proc_type; +type proc_uid_cputime_removeuid, fs_type, proc_type; +type proc_uid_io_stats, fs_type, proc_type; +type proc_uid_procstat_set, fs_type, proc_type; +type proc_uid_time_in_state, fs_type, proc_type; +type proc_uid_concurrent_active_time, fs_type, proc_type; +type proc_uid_concurrent_policy_time, fs_type, proc_type; +type proc_uid_cpupower, fs_type, proc_type; +type proc_uptime, fs_type, proc_type; +type proc_version, fs_type, proc_type; +type proc_vmallocinfo, fs_type, proc_type; +type proc_vmstat, fs_type, proc_type; +type proc_zoneinfo, fs_type, proc_type; +type selinuxfs, fs_type, mlstrustedobject; +type cgroup, fs_type, mlstrustedobject; +type cgroup_bpf, fs_type; +type sysfs, fs_type, sysfs_type, mlstrustedobject; +type sysfs_android_usb, fs_type, sysfs_type; +type sysfs_uio, sysfs_type, fs_type; +type sysfs_batteryinfo, fs_type, sysfs_type; +type sysfs_bluetooth_writable, fs_type, sysfs_type, mlstrustedobject; +type sysfs_block, fs_type, sysfs_type; +type sysfs_bpd_virtio_pci, fs_type, sysfs_type; +type sysfs_b_virtio, fs_type, sysfs_type; +type sysfs_cn_wlan0, fs_type, sysfs_type; +type sysfs_dm, fs_type, sysfs_type; +type sysfs_dt_firmware_android, fs_type, sysfs_type; +type sysfs_ipv4, fs_type, sysfs_type; +type sysfs_kernel_notes, fs_type, sysfs_type, mlstrustedobject; +type sysfs_leds, fs_type, sysfs_type; +type sysfs_hwrandom, fs_type, sysfs_type; +type sysfs_nfc_power_writable, fs_type, sysfs_type, mlstrustedobject; +type sysfs_wake_lock, fs_type, sysfs_type; +type sysfs_m_virtio_pci, fs_type, sysfs_type; +type sysfs_mac_address, fs_type, sysfs_type; +type sysfs_net, fs_type, sysfs_type; +type sysfs_power, fs_type, sysfs_type; +type sysfs_rtc, fs_type, sysfs_type; +type sysfs_switch, fs_type, sysfs_type; +type sysfs_usb, fs_type, sysfs_type; +type sysfs_wakeup_reasons, fs_type, sysfs_type; +type sysfs_fs_ext4_features, sysfs_type, fs_type; +type fs_bpf, fs_type; +type configfs, fs_type; +# /sys/devices/system/cpu +type sysfs_devices_system_cpu, fs_type, sysfs_type; +# /sys/module/lowmemorykiller +type sysfs_lowmemorykiller, fs_type, sysfs_type; +# /sys/module/wlan/parameters/fwpath +type sysfs_wlan_fwpath, fs_type, sysfs_type; +type sysfs_vibrator, fs_type, sysfs_type; + +type sysfs_thermal, sysfs_type, fs_type; + +type sysfs_zram, fs_type, sysfs_type; +type sysfs_zram_uevent, fs_type, sysfs_type; +type inotify, fs_type, mlstrustedobject; +type devpts, fs_type, mlstrustedobject; +type tmpfs, fs_type; +type shm, fs_type; +type mqueue, fs_type; +type fuse, sdcard_type, fs_type, mlstrustedobject; +type sdcardfs, sdcard_type, fs_type, mlstrustedobject; +type vfat, sdcard_type, fs_type, mlstrustedobject; +type exfat, sdcard_type, fs_type, mlstrustedobject; +type debugfs, fs_type, debugfs_type; +type debugfs_mmc, fs_type, debugfs_type; +type debugfs_trace_marker, fs_type, debugfs_type, mlstrustedobject; +type debugfs_tracing, fs_type, debugfs_type, mlstrustedobject; +type debugfs_tracing_debug, fs_type, debugfs_type, mlstrustedobject; +type debugfs_tracing_instances, fs_type, debugfs_type; +type debugfs_wakeup_sources, fs_type, debugfs_type; +type debugfs_wifi_tracing, fs_type, debugfs_type; + +type pstorefs, fs_type; +type functionfs, fs_type, mlstrustedobject; +type oemfs, fs_type, contextmount_type; +type usbfs, fs_type; +type binfmt_miscfs, fs_type; +type app_fusefs, fs_type, contextmount_type; + +# File types +type unlabeled, file_type; + +# Default type for anything under /system. +type system_file, file_type; + +# Default type for directories search for +# HAL implementations +type vendor_hal_file, vendor_file_type, file_type; +# Default type for under /vendor or /system/vendor +type vendor_file, vendor_file_type, file_type; +# Default type for everything in /vendor/app +type vendor_app_file, vendor_file_type, file_type; +# Default type for everything under /vendor/etc/ +type vendor_configs_file, vendor_file_type, file_type; +# Default type for all *same process* HALs. +# e.g. libEGL_xxx.so, android.hardware.graphics.mapper@2.0-impl.so +type same_process_hal_file, vendor_file_type, file_type; +# Default type for vndk-sp libs. /vendor/lib/vndk-sp +type vndk_sp_file, vendor_file_type, file_type; +# Default type for everything in /vendor/framework +type vendor_framework_file, vendor_file_type, file_type; +# Default type for everything in /vendor/overlay +type vendor_overlay_file, vendor_file_type, file_type; + +# /metadata partition itself +type metadata_file, file_type; +# Vold files within /metadata +type vold_metadata_file, file_type; + +# Speedup access for trusted applications to the runtime event tags +type runtime_event_log_tags_file, file_type; +# Type for /system/bin/logcat. +type logcat_exec, exec_type, file_type; +# /cores for coredumps on userdebug / eng builds +type coredump_file, file_type; +# Default type for anything under /data. +type system_data_file, file_type, data_file_type, core_data_file_type; +# Default type for anything under /data/vendor{_ce,_de}. +type vendor_data_file, file_type, data_file_type; +# Unencrypted data +type unencrypted_data_file, file_type, data_file_type, core_data_file_type; +# /data/.layout_version or other installd-created files that +# are created in a system_data_file directory. +type install_data_file, file_type, data_file_type, core_data_file_type; +# /data/drm - DRM plugin data +type drm_data_file, file_type, data_file_type, core_data_file_type; +# /data/adb - adb debugging files +type adb_data_file, file_type, data_file_type, core_data_file_type; +# /data/anr - ANR traces +type anr_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/tombstones - core dumps +type tombstone_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/vendor/tombstones/wifi - vendor wifi dumps +type tombstone_wifi_data_file, file_type, data_file_type; +# /data/app - user-installed apps +type apk_data_file, file_type, data_file_type, core_data_file_type; +type apk_tmp_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/app-private - forward-locked apps +type apk_private_data_file, file_type, data_file_type, core_data_file_type; +type apk_private_tmp_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/dalvik-cache +type dalvikcache_data_file, file_type, data_file_type, core_data_file_type; +# /data/ota +type ota_data_file, file_type, data_file_type, core_data_file_type; +# /data/ota_package +type ota_package_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/misc/profiles +type user_profile_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/misc/profman +type profman_dump_data_file, file_type, data_file_type, core_data_file_type; +# /data/resource-cache +type resourcecache_data_file, file_type, data_file_type, core_data_file_type; +# /data/local - writable by shell +type shell_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/property +type property_data_file, file_type, data_file_type, core_data_file_type; +# /data/bootchart +type bootchart_data_file, file_type, data_file_type, core_data_file_type; +# /data/system/heapdump +type heapdump_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/nativetest +type nativetest_data_file, file_type, data_file_type, core_data_file_type; +# /data/system_de/0/ringtones +type ringtone_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/preloads +type preloads_data_file, file_type, data_file_type, core_data_file_type; +# /data/preloads/media +type preloads_media_file, file_type, data_file_type, core_data_file_type; +# /data/misc/dhcp and /data/misc/dhcp-6.8.2 +type dhcp_data_file, file_type, data_file_type, core_data_file_type; + +# Mount locations managed by vold +type mnt_media_rw_file, file_type; +type mnt_user_file, file_type; +type mnt_expand_file, file_type; +type storage_file, file_type; + +# Label for storage dirs which are just mount stubs +type mnt_media_rw_stub_file, file_type; +type storage_stub_file, file_type; + +# Mount location for read-write vendor partitions. +type mnt_vendor_file, file_type; + +# /postinstall: Mount point used by update_engine to run postinstall. +type postinstall_mnt_dir, file_type; +# Files inside the /postinstall mountpoint are all labeled as postinstall_file. +type postinstall_file, file_type; + +# /data/misc subdirectories +type adb_keys_file, file_type, data_file_type, core_data_file_type; +type audio_data_file, file_type, data_file_type, core_data_file_type; +type audioserver_data_file, file_type, data_file_type, core_data_file_type; +type bluetooth_data_file, file_type, data_file_type, core_data_file_type; +type bluetooth_logs_data_file, file_type, data_file_type, core_data_file_type; +type bootstat_data_file, file_type, data_file_type, core_data_file_type; +type boottrace_data_file, file_type, data_file_type, core_data_file_type; +type camera_data_file, file_type, data_file_type, core_data_file_type; +type gatekeeper_data_file, file_type, data_file_type, core_data_file_type; +type incident_data_file, file_type, data_file_type, core_data_file_type; +type keychain_data_file, file_type, data_file_type, core_data_file_type; +type keystore_data_file, file_type, data_file_type, core_data_file_type; +type media_data_file, file_type, data_file_type, core_data_file_type; +type media_rw_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type misc_user_data_file, file_type, data_file_type, core_data_file_type; +type net_data_file, file_type, data_file_type, core_data_file_type; +type network_watchlist_data_file, file_type, data_file_type, core_data_file_type; +type nfc_data_file, file_type, data_file_type, core_data_file_type; +type radio_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type recovery_data_file, file_type, data_file_type, core_data_file_type; +type shared_relro_file, file_type, data_file_type, core_data_file_type; +type systemkeys_data_file, file_type, data_file_type, core_data_file_type; +type textclassifier_data_file, file_type, data_file_type, core_data_file_type; +type trace_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type vpn_data_file, file_type, data_file_type, core_data_file_type; +type wifi_data_file, file_type, data_file_type, core_data_file_type; +type zoneinfo_data_file, file_type, data_file_type, core_data_file_type; +type vold_data_file, file_type, data_file_type, core_data_file_type; +type perfprofd_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type tee_data_file, file_type, data_file_type; +type update_engine_data_file, file_type, data_file_type, core_data_file_type; +type update_engine_log_data_file, file_type, data_file_type, core_data_file_type; +# /data/misc/trace for method traces on userdebug / eng builds +type method_trace_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; + +# /data/data subdirectories - app sandboxes +type app_data_file, file_type, data_file_type, core_data_file_type; +# /data/data subdirectory for system UID apps. +type system_app_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Compatibility with type name used in Android 4.3 and 4.4. +# Default type for anything under /cache +type cache_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Type for /cache/backup_stage/* (fd interchange with apps) +type cache_backup_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# type for anything under /cache/backup (local transport storage) +type cache_private_backup_file, file_type, data_file_type, core_data_file_type; +# Type for anything under /cache/recovery +type cache_recovery_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Default type for anything under /efs +type efs_file, file_type; +# Type for wallpaper file. +type wallpaper_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Type for shortcut manager icon file. +type shortcut_manager_icons, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Type for user icon file. +type icon_file, file_type, data_file_type, core_data_file_type; +# /mnt/asec +type asec_apk_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Elements of asec files (/mnt/asec) that are world readable +type asec_public_file, file_type, data_file_type, core_data_file_type; +# /data/app-asec +type asec_image_file, file_type, data_file_type, core_data_file_type; +# /data/backup and /data/secure/backup +type backup_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# All devices have bluetooth efs files. But they +# vary per device, so this type is used in per +# device policy +type bluetooth_efs_file, file_type; +# Type for fingerprint template file +type fingerprintd_data_file, file_type, data_file_type, core_data_file_type; +# Type for _new_ fingerprint template file +type fingerprint_vendor_data_file, file_type, data_file_type; +# Type for appfuse file. +type app_fuse_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; + +# Socket types +type adbd_socket, file_type, coredomain_socket; +type bluetooth_socket, file_type, data_file_type, core_data_file_type, coredomain_socket; +type dnsproxyd_socket, file_type, coredomain_socket, mlstrustedobject; +type dumpstate_socket, file_type, coredomain_socket; +type fwmarkd_socket, file_type, coredomain_socket, mlstrustedobject; +type lmkd_socket, file_type, coredomain_socket; +type logd_socket, file_type, coredomain_socket, mlstrustedobject; +type logdr_socket, file_type, coredomain_socket, mlstrustedobject; +type logdw_socket, file_type, coredomain_socket, mlstrustedobject; +type mdns_socket, file_type, coredomain_socket; +type mdnsd_socket, file_type, coredomain_socket, mlstrustedobject; +type misc_logd_file, coredomain_socket, file_type, data_file_type, core_data_file_type; +type mtpd_socket, file_type, coredomain_socket; +type netd_socket, file_type, coredomain_socket; +type property_socket, file_type, coredomain_socket, mlstrustedobject; +type racoon_socket, file_type, coredomain_socket; +type rild_socket, file_type; +type rild_debug_socket, file_type; +type system_wpa_socket, file_type, data_file_type, core_data_file_type, coredomain_socket; +type system_ndebug_socket, file_type, data_file_type, core_data_file_type, coredomain_socket, mlstrustedobject; +type tombstoned_crash_socket, file_type, coredomain_socket, mlstrustedobject; +type tombstoned_java_trace_socket, file_type, mlstrustedobject; +type tombstoned_intercept_socket, file_type, coredomain_socket; +type traced_producer_socket, file_type, coredomain_socket, mlstrustedobject; +type traced_consumer_socket, file_type, coredomain_socket; +type uncrypt_socket, file_type, coredomain_socket; +type wpa_socket, file_type, data_file_type, core_data_file_type; +type zygote_socket, file_type, coredomain_socket; +# UART (for GPS) control proc file +type gps_control, file_type; + +# PDX endpoint types +type pdx_display_dir, pdx_endpoint_dir_type, file_type; +type pdx_performance_dir, pdx_endpoint_dir_type, file_type; +type pdx_bufferhub_dir, pdx_endpoint_dir_type, file_type; + +pdx_service_socket_types(display_client, pdx_display_dir) +pdx_service_socket_types(display_manager, pdx_display_dir) +pdx_service_socket_types(display_screenshot, pdx_display_dir) +pdx_service_socket_types(display_vsync, pdx_display_dir) +pdx_service_socket_types(performance_client, pdx_performance_dir) +pdx_service_socket_types(bufferhub_client, pdx_bufferhub_dir) + +# file_contexts files +type file_contexts_file, file_type; + +# mac_permissions file +type mac_perms_file, file_type; + +# property_contexts file +type property_contexts_file, file_type; + +# seapp_contexts file +type seapp_contexts_file, file_type; + +# sepolicy files binary and others +type sepolicy_file, file_type; + +# service_contexts file +type service_contexts_file, file_type; + +# nonplat service_contexts file (only accessible on non full-treble devices) +type nonplat_service_contexts_file, file_type; + +# hwservice_contexts file +type hwservice_contexts_file, file_type; + +# vndservice_contexts file +type vndservice_contexts_file, file_type; + +# Allow files to be created in their appropriate filesystems. +allow fs_type self:filesystem associate; +allow cgroup tmpfs:filesystem associate; +allow cgroup_bpf tmpfs:filesystem associate; +allow sysfs_type sysfs:filesystem associate; +allow debugfs_type { debugfs debugfs_tracing debugfs_tracing_debug }:filesystem associate; +allow file_type labeledfs:filesystem associate; +allow file_type tmpfs:filesystem associate; +allow file_type rootfs:filesystem associate; +allow dev_type tmpfs:filesystem associate; +allow app_fuse_file app_fusefs:filesystem associate; +allow postinstall_file self:filesystem associate; + +# asanwrapper (run a sanitized app_process, to be used with wrap properties) +with_asan(`type asanwrapper_exec, exec_type, file_type;') + +# Deprecated in SDK version 28 +type audiohal_data_file, file_type, data_file_type, core_data_file_type; + +# It's a bug to assign the file_type attribute and fs_type attribute +# to any type. Do not allow it. +# +# For example, the following is a bug: +# type apk_data_file, file_type, data_file_type, fs_type; +# Should be: +# type apk_data_file, file_type, data_file_type; +neverallow fs_type file_type:filesystem associate; + +type exagear_debug_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; diff --git a/aosp/system/sepolicy/prebuilts/api/28.0/public/te_macros b/aosp/system/sepolicy/prebuilts/api/28.0/public/te_macros new file mode 100644 index 000000000..241c9ea8a --- /dev/null +++ b/aosp/system/sepolicy/prebuilts/api/28.0/public/te_macros @@ -0,0 +1,597 @@ +##################################### +# domain_trans(olddomain, type, newdomain) +# Allow a transition from olddomain to newdomain +# upon executing a file labeled with type. +# This only allows the transition; it does not +# cause it to occur automatically - use domain_auto_trans +# if that is what you want. +# +define(`domain_trans', ` +# Old domain may exec the file and transition to the new domain. +allow $1 $2:file { getattr open read execute map }; +allow $1 $3:process transition; +# New domain is entered by executing the file. +allow $3 $2:file { entrypoint open read execute getattr map }; +# New domain can send SIGCHLD to its caller. +ifelse($1, `init', `', `allow $3 $1:process sigchld;') +# Enable AT_SECURE, i.e. libc secure mode. +dontaudit $1 $3:process noatsecure; +# XXX dontaudit candidate but requires further study. +allow $1 $3:process { siginh rlimitinh }; +') + +##################################### +# domain_auto_trans(olddomain, type, newdomain) +# Automatically transition from olddomain to newdomain +# upon executing a file labeled with type. +# +define(`domain_auto_trans', ` +# Allow the necessary permissions. +domain_trans($1,$2,$3) +# Make the transition occur by default. +type_transition $1 $2:process $3; +') + +##################################### +# file_type_trans(domain, dir_type, file_type) +# Allow domain to create a file labeled file_type in a +# directory labeled dir_type. +# This only allows the transition; it does not +# cause it to occur automatically - use file_type_auto_trans +# if that is what you want. +# +define(`file_type_trans', ` +# Allow the domain to add entries to the directory. +allow $1 $2:dir ra_dir_perms; +# Allow the domain to create the file. +allow $1 $3:notdevfile_class_set create_file_perms; +allow $1 $3:dir create_dir_perms; +') + +##################################### +# file_type_auto_trans(domain, dir_type, file_type) +# Automatically label new files with file_type when +# they are created by domain in directories labeled dir_type. +# +define(`file_type_auto_trans', ` +# Allow the necessary permissions. +file_type_trans($1, $2, $3) +# Make the transition occur by default. +type_transition $1 $2:dir $3; +type_transition $1 $2:notdevfile_class_set $3; +') + +##################################### +# r_dir_file(domain, type) +# Allow the specified domain to read directories, files +# and symbolic links of the specified type. +define(`r_dir_file', ` +allow $1 $2:dir r_dir_perms; +allow $1 $2:{ file lnk_file } r_file_perms; +') + +##################################### +# tmpfs_domain(domain) +# Define and allow access to a unique type for +# this domain when creating tmpfs / shmem / ashmem files. +define(`tmpfs_domain', ` +type $1_tmpfs, file_type; +type_transition $1 tmpfs:file $1_tmpfs; +allow $1 $1_tmpfs:file { read write getattr map open ioctl }; +allow $1 tmpfs:dir { getattr search }; +') + +# pdx macros for IPC. pdx is a high-level name which contains transport-specific +# rules from underlying transport (e.g. UDS-based implementation). + +##################################### +# pdx_service_attributes(service) +# Defines type attribute used to identify various service-related types. +define(`pdx_service_attributes', ` +attribute pdx_$1_endpoint_dir_type; +attribute pdx_$1_endpoint_socket_type; +attribute pdx_$1_channel_socket_type; +attribute pdx_$1_server_type; +') + +##################################### +# pdx_service_socket_types(service, endpoint_dir_t) +# Define types for endpoint and channel sockets. +define(`pdx_service_socket_types', ` +typeattribute $2 pdx_$1_endpoint_dir_type; +type pdx_$1_endpoint_socket, pdx_$1_endpoint_socket_type, pdx_endpoint_socket_type, file_type, coredomain_socket, mlstrustedobject, mlstrustedsubject; +type pdx_$1_channel_socket, pdx_$1_channel_socket_type, pdx_channel_socket_type, coredomain_socket; +userdebug_or_eng(` +dontaudit su pdx_$1_endpoint_socket:unix_stream_socket *; +dontaudit su pdx_$1_channel_socket:unix_stream_socket *; +') +') + +##################################### +# pdx_server(server_domain, service) +define(`pdx_server', ` +# Mark the server domain as a PDX server. +typeattribute $1 pdx_$2_server_type; +# Allow the init process to create the initial endpoint socket. +allow init pdx_$2_endpoint_socket_type:unix_stream_socket { create bind }; +# Allow the server domain to use the endpoint socket and accept connections on it. +# Not using macro like "rw_socket_perms_no_ioctl" because it provides more rights +# than we need (e.g. we don"t need "bind" or "connect"). +allow $1 pdx_$2_endpoint_socket_type:unix_stream_socket { read getattr write setattr lock append getopt setopt shutdown listen accept }; +# Allow the server domain to apply security context label to the channel socket pair (allow process to use setsockcreatecon_raw()). +allow $1 self:process setsockcreate; +# Allow the server domain to create a client channel socket. +allow $1 pdx_$2_channel_socket_type:unix_stream_socket create_stream_socket_perms; +# Prevent other processes from claiming to be a server for the same service. +neverallow {domain -$1} pdx_$2_endpoint_socket_type:unix_stream_socket { listen accept }; +') + +##################################### +# pdx_connect(client, service) +define(`pdx_connect', ` +# Allow client to open the service endpoint file. +allow $1 pdx_$2_endpoint_dir_type:dir r_dir_perms; +allow $1 pdx_$2_endpoint_socket_type:sock_file rw_file_perms; +# Allow the client to connect to endpoint socket. +allow $1 pdx_$2_endpoint_socket_type:unix_stream_socket { connectto read write shutdown }; +') + +##################################### +# pdx_use(client, service) +define(`pdx_use', ` +# Allow the client to use the PDX channel socket. +# Not using macro like "rw_socket_perms_no_ioctl" because it provides more rights +# than we need (e.g. we don"t need "bind" or "connect"). +allow $1 pdx_$2_channel_socket_type:unix_stream_socket { read getattr write setattr lock append getopt setopt shutdown }; +# Client needs to use an channel event fd from the server. +allow $1 pdx_$2_server_type:fd use; +# Servers may receive sync fences, gralloc buffers, etc, from clients. +# This could be tightened on a per-server basis, but keeping track of service +# clients is error prone. +allow pdx_$2_server_type $1:fd use; +') + +##################################### +# pdx_client(client, service) +define(`pdx_client', ` +pdx_connect($1, $2) +pdx_use($1, $2) +') + +##################################### +# init_daemon_domain(domain) +# Set up a transition from init to the daemon domain +# upon executing its binary. +define(`init_daemon_domain', ` +domain_auto_trans(init, $1_exec, $1) +tmpfs_domain($1) +') + +##################################### +# app_domain(domain) +# Allow a base set of permissions required for all apps. +define(`app_domain', ` +typeattribute $1 appdomain; +# Label ashmem objects with our own unique type. +tmpfs_domain($1) +# Map with PROT_EXEC. +allow $1 $1_tmpfs:file execute; +neverallow { $1 -shell } { domain -$1 }:file no_rw_file_perms; +neverallow { appdomain -shell -$1 } $1:file no_rw_file_perms; +') + +##################################### +# untrusted_app_domain(domain) +# Allow a base set of permissions required for all untrusted apps. +define(`untrusted_app_domain', ` +typeattribute $1 untrusted_app_all; +') + +##################################### +# net_domain(domain) +# Allow a base set of permissions required for network access. +define(`net_domain', ` +typeattribute $1 netdomain; +') + +##################################### +# bluetooth_domain(domain) +# Allow a base set of permissions required for bluetooth access. +define(`bluetooth_domain', ` +typeattribute $1 bluetoothdomain; +') + +##################################### +# hal_attribute(hal_name) +# Add an attribute for hal implementations along with necessary +# restrictions. +define(`hal_attribute', ` +attribute hal_$1; +expandattribute hal_$1 true; +attribute hal_$1_client; +expandattribute hal_$1_client true; +attribute hal_$1_server; +expandattribute hal_$1_server false; + +neverallow { hal_$1_server -halserverdomain } domain:process fork; +') + +##################################### +# hal_server_domain(domain, hal_type) +# Allow a base set of permissions required for a domain to offer a +# HAL implementation of the specified type over HwBinder. +# +# For example, default implementation of Foo HAL: +# type hal_foo_default, domain; +# hal_server_domain(hal_foo_default, hal_foo) +# +define(`hal_server_domain', ` +typeattribute $1 halserverdomain; +typeattribute $1 $2_server; +typeattribute $1 $2; +') + +##################################### +# hal_client_domain(domain, hal_type) +# Allow a base set of permissions required for a domain to be a +# client of a HAL of the specified type. +# +# For example, make some_domain a client of Foo HAL: +# hal_client_domain(some_domain, hal_foo) +# +define(`hal_client_domain', ` +typeattribute $1 halclientdomain; +typeattribute $1 $2_client; + +# TODO(b/34170079): Make the inclusion of the rules below conditional also on +# non-Treble devices. For now, on non-Treble device, always grant clients of a +# HAL sufficient access to run the HAL in passthrough mode (i.e., in-process). +not_full_treble(` +typeattribute $1 $2; +# Find passthrough HAL implementations +allow $2 system_file:dir r_dir_perms; +allow $2 vendor_file:dir r_dir_perms; +allow $2 vendor_file:file { read open getattr execute map }; +') +') + +##################################### +# passthrough_hal_client_domain(domain, hal_type) +# Allow a base set of permissions required for a domain to be a +# client of a passthrough HAL of the specified type. +# +# For example, make some_domain a client of passthrough Foo HAL: +# passthrough_hal_client_domain(some_domain, hal_foo) +# +define(`passthrough_hal_client_domain', ` +typeattribute $1 halclientdomain; +typeattribute $1 $2_client; +typeattribute $1 $2; +# Find passthrough HAL implementations +allow $2 system_file:dir r_dir_perms; +allow $2 vendor_file:dir r_dir_perms; +allow $2 vendor_file:file { read open getattr execute map }; +') + +##################################### +# unix_socket_connect(clientdomain, socket, serverdomain) +# Allow a local socket connection from clientdomain via +# socket to serverdomain. +# +# Note: If you see denial records that distill to the +# following allow rules: +# allow clientdomain property_socket:sock_file write; +# allow clientdomain init:unix_stream_socket connectto; +# allow clientdomain something_prop:property_service set; +# +# This sequence is indicative of attempting to set a property. +# use set_prop(sourcedomain, targetproperty) +# +define(`unix_socket_connect', ` +allow $1 $2_socket:sock_file write; +allow $1 $3:unix_stream_socket connectto; +') + +##################################### +# set_prop(sourcedomain, targetproperty) +# Allows source domain to set the +# targetproperty. +# +define(`set_prop', ` +unix_socket_connect($1, property, init) +allow $1 $2:property_service set; +get_prop($1, $2) +') + +##################################### +# get_prop(sourcedomain, targetproperty) +# Allows source domain to read the +# targetproperty. +# +define(`get_prop', ` +allow $1 $2:file r_file_perms; +') + +##################################### +# unix_socket_send(clientdomain, socket, serverdomain) +# Allow a local socket send from clientdomain via +# socket to serverdomain. +define(`unix_socket_send', ` +allow $1 $2_socket:sock_file write; +allow $1 $3:unix_dgram_socket sendto; +') + +##################################### +# binder_use(domain) +# Allow domain to use Binder IPC. +define(`binder_use', ` +# Call the servicemanager and transfer references to it. +allow $1 servicemanager:binder { call transfer }; +# servicemanager performs getpidcon on clients. +allow servicemanager $1:dir search; +allow servicemanager $1:file { read open }; +allow servicemanager $1:process getattr; +# rw access to /dev/binder and /dev/ashmem is presently granted to +# all domains in domain.te. +') + +##################################### +# hwbinder_use(domain) +# Allow domain to use HwBinder IPC. +define(`hwbinder_use', ` +# Call the hwservicemanager and transfer references to it. +allow $1 hwservicemanager:binder { call transfer }; +# Allow hwservicemanager to send out callbacks +allow hwservicemanager $1:binder { call transfer }; +# hwservicemanager performs getpidcon on clients. +allow hwservicemanager $1:dir search; +allow hwservicemanager $1:file { read open }; +allow hwservicemanager $1:process getattr; +# rw access to /dev/hwbinder and /dev/ashmem is presently granted to +# all domains in domain.te. +') + +##################################### +# vndbinder_use(domain) +# Allow domain to use Binder IPC. +define(`vndbinder_use', ` +# Talk to the vndbinder device node +allow $1 vndbinder_device:chr_file rw_file_perms; +# Call the vndservicemanager and transfer references to it. +allow $1 vndservicemanager:binder { call transfer }; +# vndservicemanager performs getpidcon on clients. +allow vndservicemanager $1:dir search; +allow vndservicemanager $1:file { read open }; +allow vndservicemanager $1:process getattr; +') + +##################################### +# binder_call(clientdomain, serverdomain) +# Allow clientdomain to perform binder IPC to serverdomain. +define(`binder_call', ` +# Call the server domain and optionally transfer references to it. +allow $1 $2:binder { call transfer }; +# Allow the serverdomain to transfer references to the client on the reply. +allow $2 $1:binder transfer; +# Receive and use open files from the server. +allow $1 $2:fd use; +') + +##################################### +# binder_service(domain) +# Mark a domain as being a Binder service domain. +# Used to allow binder IPC to the various system services. +define(`binder_service', ` +typeattribute $1 binderservicedomain; +') + +##################################### +# wakelock_use(domain) +# Allow domain to manage wake locks +define(`wakelock_use', ` +# Access /sys/power/wake_lock and /sys/power/wake_unlock +allow $1 sysfs_wake_lock:file rw_file_perms; +# Accessing these files requires CAP_BLOCK_SUSPEND +allow $1 self:global_capability2_class_set block_suspend; +') + +##################################### +# selinux_check_access(domain) +# Allow domain to check SELinux permissions via selinuxfs. +define(`selinux_check_access', ` +r_dir_file($1, selinuxfs) +allow $1 selinuxfs:file w_file_perms; +allow $1 kernel:security compute_av; +allow $1 self:netlink_selinux_socket { read write create getattr setattr lock relabelfrom relabelto append bind connect listen accept getopt setopt shutdown recvfrom sendto name_bind }; +') + +##################################### +# selinux_check_context(domain) +# Allow domain to check SELinux contexts via selinuxfs. +define(`selinux_check_context', ` +r_dir_file($1, selinuxfs) +allow $1 selinuxfs:file w_file_perms; +allow $1 kernel:security check_context; +') + +##################################### +# create_pty(domain) +# Allow domain to create and use a pty, isolated from any other domain ptys. +define(`create_pty', ` +# Each domain gets a unique devpts type. +type $1_devpts, fs_type; +# Label the pty with the unique type when created. +type_transition $1 devpts:chr_file $1_devpts; +# Allow use of the pty after creation. +allow $1 $1_devpts:chr_file { open getattr read write ioctl }; +allowxperm $1 $1_devpts:chr_file ioctl unpriv_tty_ioctls; +# TIOCSTI is only ever used for exploits. Block it. +# b/33073072, b/7530569 +# http://www.openwall.com/lists/oss-security/2016/09/26/14 +neverallowxperm * $1_devpts:chr_file ioctl TIOCSTI; +# Note: devpts:dir search and ptmx_device:chr_file rw_file_perms +# allowed to everyone via domain.te. +') + +##################################### +# Non system_app application set +# +define(`non_system_app_set', `{ appdomain -system_app }') + +##################################### +# Recovery only +# SELinux rules which apply only to recovery mode +# +define(`recovery_only', ifelse(target_recovery, `true', $1, )) + +##################################### +# Full TREBLE only +# SELinux rules which apply only to full TREBLE devices +# +define(`full_treble_only', ifelse(target_full_treble, `true', $1, +ifelse(target_full_treble, `cts', +# BEGIN_TREBLE_ONLY -- this marker is used by CTS -- do not modify +$1 +# END_TREBLE_ONLY -- this marker is used by CTS -- do not modify +, ))) + +##################################### +# Not full TREBLE +# SELinux rules which apply only to devices which are not full TREBLE devices +# +define(`not_full_treble', ifelse(target_full_treble, `true', , $1)) + +##################################### +# Compatible property only +# SELinux rules which apply only to devices with compatible property +# +define(`compatible_property_only', ifelse(target_compatible_property, `true', $1, +ifelse(target_compatible_property, `cts', +# BEGIN_COMPATIBLE_PROPERTY_ONLY -- this marker is used by CTS -- do not modify +$1 +# END_COMPATIBLE_PROPERTY_ONLY -- this marker is used by CTS -- do not modify +, ))) + +##################################### +# Not compatible property +# SELinux rules which apply only to devices without compatible property +# +define(`not_compatible_property', ifelse(target_compatible_property, `true', , $1)) + +##################################### +# Userdebug or eng builds +# SELinux rules which apply only to userdebug or eng builds +# +define(`userdebug_or_eng', ifelse(target_build_variant, `eng', $1, ifelse(target_build_variant, `userdebug', $1))) + +##################################### +# asan builds +# SELinux rules which apply only to asan builds +# +define(`with_asan', ifelse(target_with_asan, `true', userdebug_or_eng(`$1'), )) + +#################################### +# Fallback crash handling for processes that can't exec crash_dump (e.g. because of seccomp). +# +define(`crash_dump_fallback', ` +userdebug_or_eng(` + allow $1 su:fifo_file append; +') +allow $1 anr_data_file:file append; +allow $1 dumpstate:fd use; +allow $1 incidentd:fd use; +# TODO: Figure out why write is needed. +allow $1 dumpstate:fifo_file { append write }; +allow $1 incidentd:fifo_file { append write }; +allow $1 system_server:fifo_file { append write }; +allow $1 tombstoned:unix_stream_socket connectto; +allow $1 tombstoned:fd use; +allow $1 tombstoned_crash_socket:sock_file write; +allow $1 tombstone_data_file:file append; +') + +##################################### +# WITH_DEXPREOPT builds +# SELinux rules which apply only when pre-opting. +# +define(`with_dexpreopt', ifelse(target_with_dexpreopt, `true', $1)) + +##################################### +# write_logd(domain) +# Ability to write to android log +# daemon via sockets +define(`write_logd', ` +unix_socket_send($1, logdw, logd) +allow $1 pmsg_device:chr_file w_file_perms; +') + +##################################### +# read_logd(domain) +# Ability to run logcat and read from android +# log daemon via sockets +define(`read_logd', ` +allow $1 logcat_exec:file rx_file_perms; +unix_socket_connect($1, logdr, logd) +') + +##################################### +# read_runtime_log_tags(domain) +# ability to directly map the runtime event log tags +define(`read_runtime_log_tags', ` +allow $1 runtime_event_log_tags_file:file r_file_perms; +') + +##################################### +# control_logd(domain) +# Ability to control +# android log daemon via sockets +define(`control_logd', ` +# Group AID_LOG checked by filesystem & logd +# to permit control commands +unix_socket_connect($1, logd, logd) +') + +##################################### +# use_keystore(domain) +# Ability to use keystore. +# Keystore is requires the following permissions +# to call getpidcon. +define(`use_keystore', ` + allow keystore $1:dir search; + allow keystore $1:file { read open }; + allow keystore $1:process getattr; + allow $1 keystore_service:service_manager find; + binder_call($1, keystore) + binder_call(keystore, $1) +') + +########################################### +# use_drmservice(domain) +# Ability to use DrmService which requires +# DrmService to call getpidcon. +define(`use_drmservice', ` + allow drmserver $1:dir search; + allow drmserver $1:file { read open }; + allow drmserver $1:process getattr; +') + +########################################### +# add_service(domain, service) +# Ability for domain to add a service to service_manager +# and find it. It also creates a neverallow preventing +# others from adding it. +define(`add_service', ` + allow $1 $2:service_manager { add find }; + neverallow { domain -$1 } $2:service_manager add; +') + +########################################### +# add_hwservice(domain, service) +# Ability for domain to add a service to hwservice_manager +# and find it. It also creates a neverallow preventing +# others from adding it. +define(`add_hwservice', ` + allow $1 $2:hwservice_manager { add find }; + allow $1 hidl_base_hwservice:hwservice_manager add; + neverallow { domain -$1 } $2:hwservice_manager add; +') diff --git a/aosp/system/sepolicy/private/app_neverallows.te b/aosp/system/sepolicy/private/app_neverallows.te new file mode 100644 index 000000000..3ac36c9c9 --- /dev/null +++ b/aosp/system/sepolicy/private/app_neverallows.te @@ -0,0 +1,263 @@ +### +### neverallow rules for untrusted app domains +### + +define(`all_untrusted_apps',`{ + ephemeral_app + isolated_app + mediaprovider + untrusted_app + untrusted_app_25 + untrusted_app_27 + untrusted_app_all + untrusted_v2_app +}') +# Receive or send uevent messages. +neverallow all_untrusted_apps domain:netlink_kobject_uevent_socket *; + +# Receive or send generic netlink messages +neverallow all_untrusted_apps domain:netlink_socket *; + +# Too much leaky information in debugfs. It's a security +# best practice to ensure these files aren't readable. +neverallow all_untrusted_apps debugfs_type:file read; + +# Do not allow untrusted apps to register services. +# Only trusted components of Android should be registering +# services. +neverallow all_untrusted_apps service_manager_type:service_manager add; + +# Do not allow untrusted apps to use VendorBinder +neverallow all_untrusted_apps vndbinder_device:chr_file *; +neverallow all_untrusted_apps vndservice_manager_type:service_manager *; + +# Do not allow untrusted apps to connect to the property service +# or set properties. b/10243159 +neverallow { all_untrusted_apps -mediaprovider } property_socket:sock_file write; +neverallow { all_untrusted_apps -mediaprovider } init:unix_stream_socket connectto; +neverallow { all_untrusted_apps -mediaprovider } property_type:property_service set; + +# net.dns properties are not a public API. Temporarily exempt pre-Oreo apps, +# but otherwise disallow untrusted apps from reading this property. +neverallow { all_untrusted_apps -untrusted_app_25 } net_dns_prop:file read; + +# Do not allow untrusted apps to be assigned mlstrustedsubject. +# This would undermine the per-user isolation model being +# enforced via levelFrom=user in seapp_contexts and the mls +# constraints. As there is no direct way to specify a neverallow +# on attribute assignment, this relies on the fact that fork +# permission only makes sense within a domain (hence should +# never be granted to any other domain within mlstrustedsubject) +# and an untrusted app is allowed fork permission to itself. +neverallow all_untrusted_apps mlstrustedsubject:process fork; + +# Do not allow untrusted apps to hard link to any files. +# In particular, if an untrusted app links to other app data +# files, installd will not be able to guarantee the deletion +# of the linked to file. Hard links also contribute to security +# bugs, so we want to ensure untrusted apps never have this +# capability. +neverallow all_untrusted_apps file_type:file link; + +# Do not allow untrusted apps to access network MAC address file +neverallow all_untrusted_apps sysfs_mac_address:file no_rw_file_perms; + +# Do not allow any write access to files in /sys +neverallow all_untrusted_apps sysfs_type:file { no_w_file_perms no_x_file_perms }; + +# Apps may never access the default sysfs label. +neverallow all_untrusted_apps sysfs:file no_rw_file_perms; + +# Restrict socket ioctls. Either 1. disallow privileged ioctls, 2. disallow the +# ioctl permission, or 3. disallow the socket class. +neverallowxperm all_untrusted_apps domain:{ rawip_socket tcp_socket udp_socket } ioctl priv_sock_ioctls; +neverallow all_untrusted_apps *:{ netlink_route_socket netlink_selinux_socket } ioctl; +neverallow all_untrusted_apps *:{ + socket netlink_socket packet_socket key_socket appletalk_socket + netlink_tcpdiag_socket netlink_nflog_socket + netlink_xfrm_socket netlink_audit_socket + netlink_dnrt_socket netlink_kobject_uevent_socket tun_socket + netlink_iscsi_socket netlink_fib_lookup_socket netlink_connector_socket + netlink_netfilter_socket netlink_generic_socket netlink_scsitransport_socket + netlink_rdma_socket netlink_crypto_socket +} *; + +# Do not allow untrusted apps access to /cache +neverallow { all_untrusted_apps -mediaprovider } { cache_file cache_recovery_file }:dir ~{ r_dir_perms }; +neverallow { all_untrusted_apps -mediaprovider } { cache_file cache_recovery_file }:file ~{ read getattr }; + +# Do not allow untrusted apps to create/unlink files outside of its sandbox, +# internal storage or sdcard. +# World accessible data locations allow application to fill the device +# with unaccounted for data. This data will not get removed during +# application un-installation. +neverallow { all_untrusted_apps -mediaprovider } { + fs_type + -sdcard_type + file_type + -app_data_file # The apps sandbox itself + -media_rw_data_file # Internal storage. Known that apps can + # leave artfacts here after uninstall. + -user_profile_data_file # Access to profile files + userdebug_or_eng(` + -method_trace_data_file # only on ro.debuggable=1 + -coredump_file # userdebug/eng only + -exagear_debug_file # userdebug/eng only + ') +}:dir_file_class_set { create unlink }; + +# No untrusted component should be touching /dev/fuse +neverallow all_untrusted_apps fuse_device:chr_file *; + +# Do not allow untrusted apps to directly open tun_device +neverallow all_untrusted_apps tun_device:chr_file open; + +# Only allow appending to /data/anr/traces.txt (b/27853304, b/18340553) +neverallow all_untrusted_apps anr_data_file:file ~{ open append }; +neverallow all_untrusted_apps anr_data_file:dir ~search; + +# Avoid reads from generically labeled /proc files +# Create a more specific label if needed +neverallow all_untrusted_apps { + proc + proc_asound + proc_filesystems + proc_kmsg + proc_loadavg + proc_mounts + proc_pagetypeinfo + proc_stat + proc_swaps + proc_uptime + proc_version + proc_vmallocinfo + proc_vmstat +}:file { no_rw_file_perms no_x_file_perms }; + +# Avoid all access to kernel configuration +neverallow all_untrusted_apps config_gz:file { no_rw_file_perms no_x_file_perms }; + +# Do not allow untrusted apps access to preloads data files +neverallow all_untrusted_apps preloads_data_file:file no_rw_file_perms; + +# Locking of files on /system could lead to denial of service attacks +# against privileged system components +neverallow all_untrusted_apps system_file:file lock; + +# Do not permit untrusted apps to perform actions on HwBinder service_manager +# other than find actions for services listed below +neverallow all_untrusted_apps *:hwservice_manager ~find; + +# Do not permit access from apps which host arbitrary code to HwBinder services, +# except those considered sufficiently safe for access from such apps. +# The two main reasons for this are: +# 1. HwBinder servers do not perform client authentication because HIDL +# currently does not expose caller UID information and, even if it did, many +# HwBinder services either operate at a level below that of apps (e.g., HALs) +# or must not rely on app identity for authorization. Thus, to be safe, the +# default assumption is that every HwBinder service treats all its clients as +# equally authorized to perform operations offered by the service. +# 2. HAL servers (a subset of HwBinder services) contain code with higher +# incidence rate of security issues than system/core components and have +# access to lower layes of the stack (all the way down to hardware) thus +# increasing opportunities for bypassing the Android security model. +# +# Safe services include: +# - same process services: because they by definition run in the process +# of the client and thus have the same access as the client domain in which +# the process runs +# - coredomain_hwservice: are considered safe because they do not pose risks +# associated with reason #2 above. +# - hal_configstore_ISurfaceFlingerConfigs: becuase it has specifically been +# designed for use by any domain. +# - hal_graphics_allocator_hwservice: because these operations are also offered +# by surfaceflinger Binder service, which apps are permitted to access +# - hal_omx_hwservice: because this is a HwBinder version of the mediacodec +# Binder service which apps were permitted to access. +# - hal_codec2_hwservice: because this is a newer version of hal_omx_hwservice. +neverallow all_untrusted_apps { + hwservice_manager_type + -same_process_hwservice + -coredomain_hwservice + -hal_codec2_hwservice + -hal_configstore_ISurfaceFlingerConfigs + -hal_graphics_allocator_hwservice + -hal_omx_hwservice + -hal_cas_hwservice + -hal_neuralnetworks_hwservice + -untrusted_app_visible_hwservice +}:hwservice_manager find; + +# Make sure that the following services are never accessible by untrusted_apps +neverallow all_untrusted_apps { + default_android_hwservice + hal_audio_hwservice + hal_authsecret_hwservice + hal_bluetooth_hwservice + hal_bootctl_hwservice + hal_camera_hwservice + hal_confirmationui_hwservice + hal_contexthub_hwservice + hal_drm_hwservice + hal_dumpstate_hwservice + hal_fingerprint_hwservice + hal_gatekeeper_hwservice + hal_gnss_hwservice + hal_graphics_composer_hwservice + hal_health_hwservice + hal_ir_hwservice + hal_keymaster_hwservice + hal_light_hwservice + hal_memtrack_hwservice + hal_nfc_hwservice + hal_oemlock_hwservice + hal_power_hwservice + hal_secure_element_hwservice + hal_sensors_hwservice + hal_telephony_hwservice + hal_thermal_hwservice + hal_tv_cec_hwservice + hal_tv_input_hwservice + hal_usb_hwservice + hal_vibrator_hwservice + hal_vr_hwservice + hal_weaver_hwservice + hal_wifi_hwservice + hal_wifi_offload_hwservice + hal_wifi_supplicant_hwservice + hidl_base_hwservice + system_net_netd_hwservice + thermalcallback_hwservice +}:hwservice_manager find; +# HwBinder services offered by core components (as opposed to vendor components) +# are considered somewhat safer due to point #2 above. +neverallow all_untrusted_apps { + coredomain_hwservice + -same_process_hwservice + -hidl_allocator_hwservice # Designed for use by any domain + -hidl_manager_hwservice # Designed for use by any domain + -hidl_memory_hwservice # Designed for use by any domain + -hidl_token_hwservice # Designed for use by any domain +}:hwservice_manager find; + +# SELinux is not an API for untrusted apps to use +neverallow all_untrusted_apps selinuxfs:file no_rw_file_perms; + +# Restrict *Binder access from apps to HAL domains. We can only do this on full +# Treble devices where *Binder communications between apps and HALs are tightly +# restricted. +full_treble_only(` + neverallow all_untrusted_apps { + halserverdomain + -coredomain + -hal_configstore_server + -hal_graphics_allocator_server + -hal_cas_server + -hal_neuralnetworks_server + -binder_in_vendor_violators # TODO(b/35870313): Remove once all violations are gone + -untrusted_app_visible_halserver + }:binder { call transfer }; +') + +# Untrusted apps are not allowed to find mediaextractor update service. +neverallow all_untrusted_apps mediaextractor_update_service:service_manager find; diff --git a/aosp/system/sepolicy/private/compat/26.0/26.0.ignore.cil b/aosp/system/sepolicy/private/compat/26.0/26.0.ignore.cil new file mode 100644 index 000000000..5ce0b4013 --- /dev/null +++ b/aosp/system/sepolicy/private/compat/26.0/26.0.ignore.cil @@ -0,0 +1,158 @@ +;; new_objects - a collection of types that have been introduced that have no +;; analogue in older policy. Thus, we do not need to map these types to +;; previous ones. Add here to pass checkapi tests. +(typeattribute new_objects) +(typeattributeset new_objects + ( adbd_exec + atrace + binder_calls_stats_service + bootloader_boot_reason_prop + blank_screen + blank_screen_exec + blank_screen_tmpfs + bluetooth_a2dp_offload_prop + bpfloader + bpfloader_exec + broadcastradio_service + cgroup_bpf + crossprofileapps_service + ctl_interface_restart_prop + ctl_interface_start_prop + ctl_interface_stop_prop + ctl_sigstop_prop + e2fs + e2fs_exec + exfat + exported_bluetooth_prop + exported_config_prop + exported_dalvik_prop + exported_default_prop + exported_dumpstate_prop + exported_ffs_prop + exported_fingerprint_prop + exported_overlay_prop + exported_pm_prop + exported_radio_prop + exported_secure_prop + exported_system_prop + exported_system_radio_prop + exported_vold_prop + exported_wifi_prop + exported2_config_prop + exported2_default_prop + exported2_radio_prop + exported2_system_prop + exported2_vold_prop + exported3_default_prop + exported3_radio_prop + exported3_system_prop + fingerprint_vendor_data_file + fs_bpf + hal_audiocontrol_hwservice + hal_authsecret_hwservice + hal_broadcastradio_hwservice + hal_cas_hwservice + hal_codec2_hwservice + hal_confirmationui_hwservice + hal_evs_hwservice + hal_lowpan_hwservice + hal_neuralnetworks_hwservice + hal_secure_element_hwservice + hal_tetheroffload_hwservice + hal_wifi_hostapd_hwservice + hal_usb_gadget_hwservice + hal_vehicle_hwservice + hal_wifi_offload_hwservice + incident_helper + incident_helper_exec + kmsg_debug_device + last_boot_reason_prop + lowpan_device + lowpan_prop + lowpan_service + mediaextractor_update_service + mediaprovider_tmpfs + metadata_file + mnt_vendor_file + netd_stable_secret_prop + network_watchlist_data_file + network_watchlist_service + package_native_service + perfetto + perfetto_exec + perfetto_tmpfs + perfetto_traces_data_file + perfprofd_service + property_info + secure_element + secure_element_device + secure_element_tmpfs + secure_element_service + slice_service + stats + stats_data_file + stats_exec + stats_service + statsd + statsd_exec + statsd_tmpfs + statsdw + statsdw_socket + statscompanion_service + storaged_data_file + sysfs_fs_ext4_features + system_boot_reason_prop + system_net_netd_hwservice + system_update_service + test_boot_reason_prop + thermal_service + thermalcallback_hwservice + thermalserviced + thermalserviced_exec + thermalserviced_tmpfs + timezone_service + tombstoned_java_trace_socket + tombstone_wifi_data_file + trace_data_file + traceur_app + traceur_app_tmpfs + traced + traced_consumer_socket + traced_enabled_prop + traced_exec + traced_probes + traced_probes_exec + traced_probes_tmpfs + traced_producer_socket + traced_tmpfs + untrusted_app_all_devpts + update_engine_log_data_file + vendor_default_prop + vendor_security_patch_level_prop + usbd + usbd_exec + usbd_tmpfs + vendor_init + vendor_shell + vold_metadata_file + vold_prepare_subdirs + vold_prepare_subdirs_exec + vold_service + wait_for_keymaster + wait_for_keymaster_exec + wait_for_keymaster_tmpfs + wpantund + wpantund_exec + wpantund_service + wpantund_tmpfs + wm_trace_data_file)) + +;; private_objects - a collection of types that were labeled differently in +;; older policy, but that should not remain accessible to vendor policy. +;; Thus, these types are also not mapped, but recorded for checkapi tests +(typeattribute priv_objects) +(typeattributeset priv_objects + ( adbd_tmpfs + exagear_debug_file + untrusted_app_27_tmpfs + )) diff --git a/aosp/system/sepolicy/private/compat/27.0/27.0.ignore.cil b/aosp/system/sepolicy/private/compat/27.0/27.0.ignore.cil new file mode 100644 index 000000000..61a7569ec --- /dev/null +++ b/aosp/system/sepolicy/private/compat/27.0/27.0.ignore.cil @@ -0,0 +1,132 @@ +;; new_objects - a collection of types that have been introduced that have no +;; analogue in older policy. Thus, we do not need to map these types to +;; previous ones. Add here to pass checkapi tests. +(typeattribute new_objects) +(typeattributeset new_objects + ( atrace + binder_calls_stats_service + blank_screen + blank_screen_exec + blank_screen_tmpfs + bootloader_boot_reason_prop + bluetooth_a2dp_offload_prop + bpfloader + bpfloader_exec + cgroup_bpf + crossprofileapps_service + ctl_interface_restart_prop + ctl_interface_start_prop + ctl_interface_stop_prop + ctl_sigstop_prop + exfat + exported2_config_prop + exported2_default_prop + exported2_radio_prop + exported2_system_prop + exported2_vold_prop + exported3_default_prop + exported3_radio_prop + exported3_system_prop + exported_bluetooth_prop + exported_config_prop + exported_dalvik_prop + exported_default_prop + exported_dumpstate_prop + exported_ffs_prop + exported_fingerprint_prop + exported_overlay_prop + exported_pm_prop + exported_radio_prop + exported_secure_prop + exported_system_prop + exported_system_radio_prop + exported_vold_prop + exported_wifi_prop + fingerprint_vendor_data_file + fs_bpf + hal_audiocontrol_hwservice + hal_authsecret_hwservice + hal_codec2_hwservice + hal_confirmationui_hwservice + hal_evs_hwservice + hal_lowpan_hwservice + hal_secure_element_hwservice + hal_usb_gadget_hwservice + hal_vehicle_hwservice + hal_wifi_hostapd_hwservice + incident_helper + incident_helper_exec + last_boot_reason_prop + lowpan_device + lowpan_prop + lowpan_service + mediaextractor_update_service + metadata_file + mnt_vendor_file + network_watchlist_data_file + network_watchlist_service + perfetto + perfetto_exec + perfetto_tmpfs + perfetto_traces_data_file + perfprofd_service + property_info + secure_element + secure_element_device + secure_element_service + secure_element_tmpfs + slice_service + stats + stats_data_file + stats_exec + stats_service + statscompanion_service + statsd + statsd_exec + statsd_tmpfs + statsdw + statsdw_socket + storaged_data_file + system_boot_reason_prop + system_update_service + test_boot_reason_prop + tombstone_wifi_data_file + trace_data_file + traced + traced_consumer_socket + traced_enabled_prop + traced_exec + traced_probes + traced_probes_exec + traced_probes_tmpfs + traced_producer_socket + traced_tmpfs + traceur_app + traceur_app_tmpfs + untrusted_app_all_devpts + update_engine_log_data_file + usbd + usbd_exec + usbd_tmpfs + vendor_default_prop + vendor_init + vendor_security_patch_level_prop + vendor_shell + vold_metadata_file + vold_prepare_subdirs + vold_prepare_subdirs_exec + vold_service + wait_for_keymaster + wait_for_keymaster_exec + wait_for_keymaster_tmpfs + wm_trace_data_file + wpantund + wpantund_exec + wpantund_service + wpantund_tmpfs)) + +;; private_objects - a collection of types that were labeled differently in +;; older policy, but that should not remain accessible to vendor policy. +;; Thus, these types are also not mapped, but recorded for checkapi tests +(typeattribute priv_objects) +(typeattributeset priv_objects (exagear_debug_file untrusted_app_27_tmpfs)) diff --git a/aosp/system/sepolicy/private/file_contexts b/aosp/system/sepolicy/private/file_contexts new file mode 100644 index 000000000..5f020cf02 --- /dev/null +++ b/aosp/system/sepolicy/private/file_contexts @@ -0,0 +1,560 @@ +########################################### +# Root +/ u:object_r:rootfs:s0 + +# Data files +/adb_keys u:object_r:adb_keys_file:s0 +/build\.prop u:object_r:rootfs:s0 +/default\.prop u:object_r:rootfs:s0 +/fstab\..* u:object_r:rootfs:s0 +/init\..* u:object_r:rootfs:s0 +/res(/.*)? u:object_r:rootfs:s0 +/selinux_version u:object_r:rootfs:s0 +/ueventd\..* u:object_r:rootfs:s0 +/verity_key u:object_r:rootfs:s0 + +# Executables +/charger u:object_r:rootfs:s0 +/init u:object_r:init_exec:s0 +/sbin(/.*)? u:object_r:rootfs:s0 + +# For kernel modules +/lib(/.*)? u:object_r:rootfs:s0 + +# Empty directories +/lost\+found u:object_r:rootfs:s0 +/acct u:object_r:cgroup:s0 +/config u:object_r:rootfs:s0 +/mnt u:object_r:tmpfs:s0 +/postinstall u:object_r:postinstall_mnt_dir:s0 +/proc u:object_r:rootfs:s0 +/sys u:object_r:sysfs:s0 + +# proc fs & sys fs +/proc/net/route u:object_r:proc_net_route:s0 +/proc/version u:object_r:proc_version:s0 +/sys/block u:object_r:sysfs_block:s0 +/sys/bus/pci/drivers/virtio-pci u:object_r:sysfs_bpd_virtio_pci:s0 +/sys/bus/virtio u:object_r:sysfs_b_virtio:s0 +/sys/class/net/wlan0 u:object_r:sysfs_cn_wlan0:s0 +/sys/class/power_supply/battery/voltage_now u:object_r:sysfs_power:s0 +/sys/module/virtio_pci u:object_r:sysfs_m_virtio_pci:s0 + +# Symlinks +/bin u:object_r:rootfs:s0 +/bugreports u:object_r:rootfs:s0 +/d u:object_r:rootfs:s0 +/etc u:object_r:rootfs:s0 +/sdcard u:object_r:rootfs:s0 + +# SELinux policy files +/vendor_file_contexts u:object_r:file_contexts_file:s0 +/nonplat_file_contexts u:object_r:file_contexts_file:s0 +/plat_file_contexts u:object_r:file_contexts_file:s0 +/mapping_sepolicy\.cil u:object_r:sepolicy_file:s0 +/nonplat_sepolicy\.cil u:object_r:sepolicy_file:s0 +/plat_sepolicy\.cil u:object_r:sepolicy_file:s0 +/plat_property_contexts u:object_r:property_contexts_file:s0 +/nonplat_property_contexts u:object_r:property_contexts_file:s0 +/vendor_property_contexts u:object_r:property_contexts_file:s0 +/seapp_contexts u:object_r:seapp_contexts_file:s0 +/nonplat_seapp_contexts u:object_r:seapp_contexts_file:s0 +/vendor_seapp_contexts u:object_r:seapp_contexts_file:s0 +/plat_seapp_contexts u:object_r:seapp_contexts_file:s0 +/sepolicy u:object_r:sepolicy_file:s0 +/plat_service_contexts u:object_r:service_contexts_file:s0 +/plat_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/nonplat_service_contexts u:object_r:nonplat_service_contexts_file:s0 +# Use nonplat_service_contexts_file to allow servicemanager to read it +# on non full-treble devices. +/vendor_service_contexts u:object_r:nonplat_service_contexts_file:s0 +/nonplat_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/vendor_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/vndservice_contexts u:object_r:vndservice_contexts_file:s0 + +########################## +# Devices +# +/dev(/.*)? u:object_r:device:s0 +/dev/akm8973.* u:object_r:sensors_device:s0 +/dev/accelerometer u:object_r:sensors_device:s0 +/dev/adf[0-9]* u:object_r:graphics_device:s0 +/dev/adf-interface[0-9]*\.[0-9]* u:object_r:graphics_device:s0 +/dev/adf-overlay-engine[0-9]*\.[0-9]* u:object_r:graphics_device:s0 +/dev/alarm u:object_r:alarm_device:s0 +/dev/ashmem u:object_r:ashmem_device:s0 +/dev/audio.* u:object_r:audio_device:s0 +/dev/binder u:object_r:binder_device:s0 +/dev/block(/.*)? u:object_r:block_device:s0 +/dev/block/dm-[0-9]+ u:object_r:dm_device:s0 +/dev/block/loop[0-9]* u:object_r:loop_device:s0 +/dev/block/vold/.+ u:object_r:vold_device:s0 +/dev/block/ram[0-9]* u:object_r:ram_device:s0 +/dev/block/zram[0-9]* u:object_r:ram_device:s0 +/dev/bus/usb(.*)? u:object_r:usb_device:s0 +/dev/cam u:object_r:camera_device:s0 +/dev/console u:object_r:console_device:s0 +/dev/cpuctl(/.*)? u:object_r:cpuctl_device:s0 +/dev/memcg(/.*)? u:object_r:cgroup:s0 +/dev/device-mapper u:object_r:dm_device:s0 +/dev/eac u:object_r:audio_device:s0 +/dev/event-log-tags u:object_r:runtime_event_log_tags_file:s0 +/dev/fscklogs(/.*)? u:object_r:fscklogs:s0 +/dev/full u:object_r:full_device:s0 +/dev/fuse u:object_r:fuse_device:s0 +/dev/graphics(/.*)? u:object_r:graphics_device:s0 +/dev/hw_random u:object_r:hw_random_device:s0 +/dev/hwbinder u:object_r:hwbinder_device:s0 +/dev/i2c-[0-9]+ u:object_r:i2c_device:s0 +/dev/input(/.*)? u:object_r:input_device:s0 +/dev/iio:device[0-9]+ u:object_r:iio_device:s0 +/dev/ion u:object_r:ion_device:s0 +/dev/keychord u:object_r:keychord_device:s0 +/dev/kmem u:object_r:kmem_device:s0 +/dev/loop-control u:object_r:loop_control_device:s0 +/dev/mem u:object_r:kmem_device:s0 +/dev/modem.* u:object_r:radio_device:s0 +/dev/mtd(/.*)? u:object_r:mtd_device:s0 +/dev/mtp_usb u:object_r:mtp_device:s0 +/dev/pmsg0 u:object_r:pmsg_device:s0 +/dev/pn544 u:object_r:nfc_device:s0 +/dev/port u:object_r:port_device:s0 +/dev/ppp u:object_r:ppp_device:s0 +/dev/ptmx u:object_r:ptmx_device:s0 +/dev/pvrsrvkm u:object_r:gpu_device:s0 +/dev/kmsg u:object_r:kmsg_device:s0 +/dev/kmsg_debug u:object_r:kmsg_debug_device:s0 +/dev/null u:object_r:null_device:s0 +/dev/nvhdcp1 u:object_r:video_device:s0 +/dev/random u:object_r:random_device:s0 +/dev/rpmsg-omx[0-9] u:object_r:rpmsg_device:s0 +/dev/rproc_user u:object_r:rpmsg_device:s0 +/dev/rtc[0-9] u:object_r:rtc_device:s0 +/dev/snd(/.*)? u:object_r:audio_device:s0 +/dev/snd/audio_timer_device u:object_r:audio_timer_device:s0 +/dev/snd/audio_seq_device u:object_r:audio_seq_device:s0 +/dev/socket(/.*)? u:object_r:socket_device:s0 +/dev/socket/adbd u:object_r:adbd_socket:s0 +/dev/socket/dnsproxyd u:object_r:dnsproxyd_socket:s0 +/dev/socket/dumpstate u:object_r:dumpstate_socket:s0 +/dev/socket/fwmarkd u:object_r:fwmarkd_socket:s0 +/dev/socket/lmkd u:object_r:lmkd_socket:s0 +/dev/socket/logd u:object_r:logd_socket:s0 +/dev/socket/logdr u:object_r:logdr_socket:s0 +/dev/socket/logdw u:object_r:logdw_socket:s0 +/dev/socket/statsdw u:object_r:statsdw_socket:s0 +/dev/socket/mdns u:object_r:mdns_socket:s0 +/dev/socket/mdnsd u:object_r:mdnsd_socket:s0 +/dev/socket/mtpd u:object_r:mtpd_socket:s0 +/dev/socket/netd u:object_r:netd_socket:s0 +/dev/socket/pdx/system/buffer_hub u:object_r:pdx_bufferhub_dir:s0 +/dev/socket/pdx/system/buffer_hub/client u:object_r:pdx_bufferhub_client_endpoint_socket:s0 +/dev/socket/pdx/system/performance u:object_r:pdx_performance_dir:s0 +/dev/socket/pdx/system/performance/client u:object_r:pdx_performance_client_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display u:object_r:pdx_display_dir:s0 +/dev/socket/pdx/system/vr/display/client u:object_r:pdx_display_client_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/manager u:object_r:pdx_display_manager_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/screenshot u:object_r:pdx_display_screenshot_endpoint_socket:s0 +/dev/socket/pdx/system/vr/display/vsync u:object_r:pdx_display_vsync_endpoint_socket:s0 +/dev/socket/property_service u:object_r:property_socket:s0 +/dev/socket/racoon u:object_r:racoon_socket:s0 +/dev/socket/rild u:object_r:rild_socket:s0 +/dev/socket/rild-debug u:object_r:rild_debug_socket:s0 +/dev/socket/tombstoned_crash u:object_r:tombstoned_crash_socket:s0 +/dev/socket/tombstoned_java_trace u:object_r:tombstoned_java_trace_socket:s0 +/dev/socket/tombstoned_intercept u:object_r:tombstoned_intercept_socket:s0 +/dev/socket/traced_producer u:object_r:traced_producer_socket:s0 +/dev/socket/traced_consumer u:object_r:traced_consumer_socket:s0 +/dev/socket/uncrypt u:object_r:uncrypt_socket:s0 +/dev/socket/wpa_eth[0-9] u:object_r:wpa_socket:s0 +/dev/socket/wpa_wlan[0-9] u:object_r:wpa_socket:s0 +/dev/socket/zygote u:object_r:zygote_socket:s0 +/dev/socket/zygote_secondary u:object_r:zygote_socket:s0 +/dev/spdif_out.* u:object_r:audio_device:s0 +/dev/tegra.* u:object_r:video_device:s0 +/dev/tty u:object_r:owntty_device:s0 +/dev/tty[0-9]* u:object_r:tty_device:s0 +/dev/ttyS[0-9]* u:object_r:serial_device:s0 +/dev/tun u:object_r:tun_device:s0 +/dev/uhid u:object_r:uhid_device:s0 +/dev/uinput u:object_r:uhid_device:s0 +/dev/uio[0-9]* u:object_r:uio_device:s0 +/dev/urandom u:object_r:random_device:s0 +/dev/usb_accessory u:object_r:usbaccessory_device:s0 +/dev/v4l-touch[0-9]* u:object_r:input_device:s0 +/dev/vcs[0-9a-z]* u:object_r:vcs_device:s0 +/dev/video[0-9]* u:object_r:video_device:s0 +/dev/vndbinder u:object_r:vndbinder_device:s0 +/dev/watchdog u:object_r:watchdog_device:s0 +/dev/xt_qtaguid u:object_r:qtaguid_device:s0 +/dev/zero u:object_r:zero_device:s0 +/dev/__properties__ u:object_r:properties_device:s0 +/dev/__properties__/property_info u:object_r:property_info:s0 +############################# +# System files +# +/system(/.*)? u:object_r:system_file:s0 +/system/bin/atrace u:object_r:atrace_exec:s0 +/system/bin/blank_screen u:object_r:blank_screen_exec:s0 +/system/bin/e2fsdroid u:object_r:e2fs_exec:s0 +/system/bin/mke2fs u:object_r:e2fs_exec:s0 +/system/bin/e2fsck -- u:object_r:fsck_exec:s0 +/system/bin/fsck\.f2fs -- u:object_r:fsck_exec:s0 +/system/bin/sload_f2fs -- u:object_r:e2fs_exec:s0 +/system/bin/make_f2fs -- u:object_r:e2fs_exec:s0 +/system/bin/fsck_msdos -- u:object_r:fsck_exec:s0 +/system/bin/tune2fs -- u:object_r:fsck_exec:s0 +/system/bin/toolbox -- u:object_r:toolbox_exec:s0 +/system/bin/toybox -- u:object_r:toolbox_exec:s0 +/system/bin/logcat -- u:object_r:logcat_exec:s0 +/system/bin/logcatd -- u:object_r:logcat_exec:s0 +/system/bin/sh -- u:object_r:shell_exec:s0 +/system/bin/run-as -- u:object_r:runas_exec:s0 +/system/bin/bootanimation u:object_r:bootanim_exec:s0 +/system/bin/bootstat u:object_r:bootstat_exec:s0 +/system/bin/app_process32 u:object_r:zygote_exec:s0 +/system/bin/app_process64 u:object_r:zygote_exec:s0 +/system/bin/servicemanager u:object_r:servicemanager_exec:s0 +/system/bin/hwservicemanager u:object_r:hwservicemanager_exec:s0 +/system/bin/surfaceflinger u:object_r:surfaceflinger_exec:s0 +/system/bin/bufferhubd u:object_r:bufferhubd_exec:s0 +/system/bin/performanced u:object_r:performanced_exec:s0 +/system/bin/drmserver u:object_r:drmserver_exec:s0 +/system/bin/dumpstate u:object_r:dumpstate_exec:s0 +/system/bin/incident u:object_r:incident_exec:s0 +/system/bin/incidentd u:object_r:incidentd_exec:s0 +/system/bin/incident_helper u:object_r:incident_helper_exec:s0 +/system/bin/netutils-wrapper-1\.0 u:object_r:netutils_wrapper_exec:s0 +/system/bin/vold u:object_r:vold_exec:s0 +/system/bin/netd u:object_r:netd_exec:s0 +/system/bin/wificond u:object_r:wificond_exec:s0 +/system/bin/audioserver u:object_r:audioserver_exec:s0 +/system/bin/mediadrmserver u:object_r:mediadrmserver_exec:s0 +/system/bin/mediaserver u:object_r:mediaserver_exec:s0 +/system/bin/mediametrics u:object_r:mediametrics_exec:s0 +/system/bin/cameraserver u:object_r:cameraserver_exec:s0 +/system/bin/mediaextractor u:object_r:mediaextractor_exec:s0 +/system/bin/mdnsd u:object_r:mdnsd_exec:s0 +/system/bin/installd u:object_r:installd_exec:s0 +/system/bin/otapreopt_chroot u:object_r:otapreopt_chroot_exec:s0 +/system/bin/otapreopt_slot u:object_r:otapreopt_slot_exec:s0 +/system/bin/keystore u:object_r:keystore_exec:s0 +/system/bin/fingerprintd u:object_r:fingerprintd_exec:s0 +/system/bin/gatekeeperd u:object_r:gatekeeperd_exec:s0 +/system/bin/crash_dump32 u:object_r:crash_dump_exec:s0 +/system/bin/crash_dump64 u:object_r:crash_dump_exec:s0 +/system/bin/tombstoned u:object_r:tombstoned_exec:s0 +/system/bin/recovery-persist u:object_r:recovery_persist_exec:s0 +/system/bin/recovery-refresh u:object_r:recovery_refresh_exec:s0 +/system/bin/sdcard u:object_r:sdcardd_exec:s0 +/system/bin/dhcpcd u:object_r:dhcp_exec:s0 +/system/bin/dhcpcd-6.8.2 u:object_r:dhcp_exec:s0 +/system/bin/mtpd u:object_r:mtp_exec:s0 +/system/bin/pppd u:object_r:ppp_exec:s0 +/system/bin/racoon u:object_r:racoon_exec:s0 +/system/bin/cph_su u:object_r:su_exec:s0 +/system/bin/su u:object_r:su_exec:s0 +/system/xbin/su u:object_r:su_exec:s0 +/system/bin/perfprofd u:object_r:perfprofd_exec:s0 +/system/bin/dnsmasq u:object_r:dnsmasq_exec:s0 +/system/bin/healthd u:object_r:healthd_exec:s0 +/system/bin/clatd u:object_r:clatd_exec:s0 +/system/bin/lmkd u:object_r:lmkd_exec:s0 +/system/bin/usbd u:object_r:usbd_exec:s0 +/system/bin/inputflinger u:object_r:inputflinger_exec:s0 +/system/bin/logd u:object_r:logd_exec:s0 +/system/bin/perfetto u:object_r:perfetto_exec:s0 +/system/bin/traced u:object_r:traced_exec:s0 +/system/bin/traced_probes u:object_r:traced_probes_exec:s0 +/system/bin/uncrypt u:object_r:uncrypt_exec:s0 +/system/bin/update_verifier u:object_r:update_verifier_exec:s0 +/system/bin/logwrapper u:object_r:system_file:s0 +/system/bin/vdc u:object_r:vdc_exec:s0 +/system/bin/cppreopts.sh u:object_r:cppreopts_exec:s0 +/system/bin/preopt2cachename u:object_r:preopt2cachename_exec:s0 +/system/bin/install-recovery.sh u:object_r:install_recovery_exec:s0 +/system/bin/dex2oat(d)? u:object_r:dex2oat_exec:s0 +/system/bin/dexoptanalyzer(d)? u:object_r:dexoptanalyzer_exec:s0 +# patchoat executable has (essentially) the same requirements as dex2oat. +/system/bin/patchoat(d)? u:object_r:dex2oat_exec:s0 +/system/bin/profman(d)? u:object_r:profman_exec:s0 +/system/bin/sgdisk u:object_r:sgdisk_exec:s0 +/system/bin/blkid u:object_r:blkid_exec:s0 +/system/bin/tzdatacheck u:object_r:tzdatacheck_exec:s0 +/system/bin/idmap u:object_r:idmap_exec:s0 +/system/bin/update_engine u:object_r:update_engine_exec:s0 +/system/bin/bspatch u:object_r:update_engine_exec:s0 +/system/bin/storaged u:object_r:storaged_exec:s0 +/system/bin/thermalserviced u:object_r:thermalserviced_exec:s0 +/system/bin/wpantund u:object_r:wpantund_exec:s0 +/system/bin/virtual_touchpad u:object_r:virtual_touchpad_exec:s0 +/system/bin/hw/android\.hidl\.allocator@1\.0-service u:object_r:hal_allocator_default_exec:s0 +/system/etc/selinux/mapping/[0-9]+\.[0-9]+\.cil u:object_r:sepolicy_file:s0 +/system/etc/selinux/plat_mac_permissions\.xml u:object_r:mac_perms_file:s0 +/system/etc/selinux/plat_property_contexts u:object_r:property_contexts_file:s0 +/system/etc/selinux/plat_service_contexts u:object_r:service_contexts_file:s0 +/system/etc/selinux/plat_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/system/etc/selinux/plat_file_contexts u:object_r:file_contexts_file:s0 +/system/etc/selinux/plat_seapp_contexts u:object_r:seapp_contexts_file:s0 +/system/etc/selinux/plat_sepolicy.cil u:object_r:sepolicy_file:s0 +/system/etc/selinux/plat_and_mapping_sepolicy\.cil\.sha256 u:object_r:sepolicy_file:s0 +/system/bin/vr_hwc u:object_r:vr_hwc_exec:s0 +/system/bin/adbd u:object_r:adbd_exec:s0 +/system/bin/vold_prepare_subdirs u:object_r:vold_prepare_subdirs_exec:s0 +/system/bin/stats u:object_r:stats_exec:s0 +/system/bin/statsd u:object_r:statsd_exec:s0 +/system/bin/bpfloader u:object_r:bpfloader_exec:s0 +/system/bin/wait_for_keymaster u:object_r:wait_for_keymaster_exec:s0 +############################# +# Vendor files +# +/(vendor|system/vendor)(/.*)? u:object_r:vendor_file:s0 +/(vendor|system/vendor)/bin/sh u:object_r:vendor_shell_exec:s0 +/(vendor|system/vendor)/bin/toybox_vendor u:object_r:vendor_toolbox_exec:s0 +/(vendor|system/vendor)/bin/toolbox u:object_r:vendor_toolbox_exec:s0 +/(vendor|system/vendor)/etc(/.*)? u:object_r:vendor_configs_file:s0 + +/(vendor|system/vendor)/lib(64)?/egl(/.*)? u:object_r:same_process_hal_file:s0 + +/(vendor|system/vendor)/lib(64)?/vndk-sp(/.*)? u:object_r:vndk_sp_file:s0 + +/(vendor|system/vendor)/manifest.xml u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/compatibility_matrix.xml u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/etc/vintf(/.*)? u:object_r:vendor_configs_file:s0 +/(vendor|system/vendor)/app(/.*)? u:object_r:vendor_app_file:s0 +/(vendor|system/vendor)/priv-app(/.*)? u:object_r:vendor_app_file:s0 +/(vendor|system/vendor)/overlay(/.*)? u:object_r:vendor_overlay_file:s0 +/(vendor|system/vendor)/framework(/.*)? u:object_r:vendor_framework_file:s0 + +# HAL location +/(vendor|system/vendor)/lib(64)?/hw u:object_r:vendor_hal_file:s0 + +############################# +# OEM and ODM files +# +/(odm|vendor/odm)(/.*)? u:object_r:vendor_file:s0 +/(odm|vendor/odm)/lib(64)?/egl(/.*)? u:object_r:same_process_hal_file:s0 +/(odm|vendor/odm)/lib(64)?/hw u:object_r:vendor_hal_file:s0 +/(odm|vendor/odm)/lib(64)?/vndk-sp(/.*)? u:object_r:vndk_sp_file:s0 +/(odm|vendor/odm)/bin/sh u:object_r:vendor_shell_exec:s0 +/(odm|vendor/odm)/etc(/.*)? u:object_r:vendor_configs_file:s0 +/(odm|vendor/odm)/app(/.*)? u:object_r:vendor_app_file:s0 +/(odm|vendor/odm)/priv-app(/.*)? u:object_r:vendor_app_file:s0 +/(odm|vendor/odm)/overlay(/.*)? u:object_r:vendor_overlay_file:s0 +/(odm|vendor/odm)/framework(/.*)? u:object_r:vendor_framework_file:s0 + +/oem(/.*)? u:object_r:oemfs:s0 + +# The precompiled monolithic sepolicy will be under /odm only when +# BOARD_USES_ODMIMAGE is true: a separate odm.img is built. +/odm/etc/selinux/precompiled_sepolicy u:object_r:sepolicy_file:s0 +/odm/etc/selinux/precompiled_sepolicy\.plat_and_mapping\.sha256 u:object_r:sepolicy_file:s0 + +/(odm|vendor/odm)/etc/selinux/odm_sepolicy.cil u:object_r:sepolicy_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_file_contexts u:object_r:file_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_seapp_contexts u:object_r:seapp_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_property_contexts u:object_r:property_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_hwservice_contexts u:object_r:hwservice_contexts_file:s0 +/(odm|vendor/odm)/etc/selinux/odm_mac_permissions.xml u:object_r:mac_perms_file:s0 + +############################# +# Product files +# +/(product|system/product)(/.*)? u:object_r:system_file:s0 + +############################# +# Data files +# +# NOTE: When modifying existing label rules, changes may also need to +# propagate to the "Expanded data files" section. +# +/data(/.*)? u:object_r:system_data_file:s0 +# for /data/data/xxx +/data/data u:object_r:app_data_file:s0 +/data/data(/.*)? u:object_r:app_data_file:s0 +/data/.layout_version u:object_r:install_data_file:s0 +/data/unencrypted(/.*)? u:object_r:unencrypted_data_file:s0 +/data/backup(/.*)? u:object_r:backup_data_file:s0 +/data/secure/backup(/.*)? u:object_r:backup_data_file:s0 +/data/system/ndebugsocket u:object_r:system_ndebug_socket:s0 +/data/drm(/.*)? u:object_r:drm_data_file:s0 +/data/resource-cache(/.*)? u:object_r:resourcecache_data_file:s0 +/data/dalvik-cache(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/ota(/.*)? u:object_r:ota_data_file:s0 +/data/ota_package(/.*)? u:object_r:ota_package_file:s0 +/data/adb(/.*)? u:object_r:adb_data_file:s0 +/data/anr(/.*)? u:object_r:anr_data_file:s0 +/data/app(/.*)? u:object_r:apk_data_file:s0 +/data/app/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/app/vmdl[^/]+\.tmp(/.*)? u:object_r:apk_tmp_file:s0 +/data/app/vmdl[^/]+\.tmp/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/data/app-private(/.*)? u:object_r:apk_private_data_file:s0 +/data/app-private/vmdl.*\.tmp(/.*)? u:object_r:apk_private_tmp_file:s0 +/data/tombstones(/.*)? u:object_r:tombstone_data_file:s0 +/data/vendor/tombstones/wifi(/.*)? u:object_r:tombstone_wifi_data_file:s0 +/data/local(/.*)? u:object_r:app_data_file:s0 +/data/local/tmp(/.*)? u:object_r:shell_data_file:s0 +/data/local/tmp/ltp(/.*)? u:object_r:nativetest_data_file:s0 +/data/local/traces(/.*)? u:object_r:trace_data_file:s0 +/data/media(/.*)? u:object_r:media_rw_data_file:s0 +/data/mediadrm(/.*)? u:object_r:media_data_file:s0 +/data/nativetest(/.*)? u:object_r:nativetest_data_file:s0 +/data/nativetest64(/.*)? u:object_r:nativetest_data_file:s0 +/data/property(/.*)? u:object_r:property_data_file:s0 +/data/preloads(/.*)? u:object_r:preloads_data_file:s0 +/data/preloads/media(/.*)? u:object_r:preloads_media_file:s0 +/data/preloads/demo(/.*)? u:object_r:preloads_media_file:s0 + +# Misc data +/data/misc/adb(/.*)? u:object_r:adb_keys_file:s0 +/data/misc/apns(/.*)? u:object_r:radio_data_file:s0 +/data/misc/audio(/.*)? u:object_r:audio_data_file:s0 +/data/misc/audioserver(/.*)? u:object_r:audioserver_data_file:s0 +/data/misc/audiohal(/.*)? u:object_r:audiohal_data_file:s0 +/data/misc/bootstat(/.*)? u:object_r:bootstat_data_file:s0 +/data/misc/boottrace(/.*)? u:object_r:boottrace_data_file:s0 +/data/misc/bluetooth(/.*)? u:object_r:bluetooth_data_file:s0 +/data/misc/bluetooth/logs(/.*)? u:object_r:bluetooth_logs_data_file:s0 +/data/misc/bluedroid(/.*)? u:object_r:bluetooth_data_file:s0 +/data/misc/bluedroid/\.a2dp_ctrl u:object_r:bluetooth_socket:s0 +/data/misc/bluedroid/\.a2dp_data u:object_r:bluetooth_socket:s0 +/data/misc/camera(/.*)? u:object_r:camera_data_file:s0 +/data/misc/carrierid(/.*)? u:object_r:radio_data_file:s0 +/data/misc/dhcp(/.*)? u:object_r:dhcp_data_file:s0 +/data/misc/dhcp-6.8.2(/.*)? u:object_r:dhcp_data_file:s0 +/data/misc/gatekeeper(/.*)? u:object_r:gatekeeper_data_file:s0 +/data/misc/incidents(/.*)? u:object_r:incident_data_file:s0 +/data/misc/keychain(/.*)? u:object_r:keychain_data_file:s0 +/data/misc/keystore(/.*)? u:object_r:keystore_data_file:s0 +/data/misc/logd(/.*)? u:object_r:misc_logd_file:s0 +/data/misc/media(/.*)? u:object_r:media_data_file:s0 +/data/misc/net(/.*)? u:object_r:net_data_file:s0 +/data/misc/network_watchlist(/.*)? u:object_r:network_watchlist_data_file:s0 +/data/misc/perfetto-traces(/.*)? u:object_r:perfetto_traces_data_file:s0 +/data/misc/recovery(/.*)? u:object_r:recovery_data_file:s0 +/data/misc/shared_relro(/.*)? u:object_r:shared_relro_file:s0 +/data/misc/sms(/.*)? u:object_r:radio_data_file:s0 +/data/misc/stats-data(/.*)? u:object_r:stats_data_file:s0 +/data/misc/stats-service(/.*)? u:object_r:stats_data_file:s0 +/data/misc/systemkeys(/.*)? u:object_r:systemkeys_data_file:s0 +/data/misc/textclassifier(/.*)? u:object_r:textclassifier_data_file:s0 +/data/misc/user(/.*)? u:object_r:misc_user_data_file:s0 +/data/misc/vpn(/.*)? u:object_r:vpn_data_file:s0 +/data/misc/wifi(/.*)? u:object_r:wifi_data_file:s0 +/data/misc/wifi/sockets(/.*)? u:object_r:wpa_socket:s0 +/data/misc/wifi/sockets/wpa_ctrl.* u:object_r:system_wpa_socket:s0 +/data/misc/zoneinfo(/.*)? u:object_r:zoneinfo_data_file:s0 +/data/misc/vold(/.*)? u:object_r:vold_data_file:s0 +/data/misc/perfprofd(/.*)? u:object_r:perfprofd_data_file:s0 +/data/misc/update_engine(/.*)? u:object_r:update_engine_data_file:s0 +/data/misc/update_engine_log(/.*)? u:object_r:update_engine_log_data_file:s0 +/data/system/heapdump(/.*)? u:object_r:heapdump_data_file:s0 +/data/misc/trace(/.*)? u:object_r:method_trace_data_file:s0 +/data/misc/wmtrace(/.*)? u:object_r:wm_trace_data_file:s0 +# TODO(calin) label profile reference differently so that only +# profman run as a special user can write to them +/data/misc/profiles/cur(/.*)? u:object_r:user_profile_data_file:s0 +/data/misc/profiles/ref(/.*)? u:object_r:user_profile_data_file:s0 +/data/misc/profman(/.*)? u:object_r:profman_dump_data_file:s0 +/data/vendor(/.*)? u:object_r:vendor_data_file:s0 +/data/vendor_ce(/.*)? u:object_r:vendor_data_file:s0 +/data/vendor_de(/.*)? u:object_r:vendor_data_file:s0 + +# storaged proto files +/data/misc_de/[0-9]+/storaged(/.*)? u:object_r:storaged_data_file:s0 +/data/misc_ce/[0-9]+/storaged(/.*)? u:object_r:storaged_data_file:s0 + +# Fingerprint data +/data/system/users/[0-9]+/fpdata(/.*)? u:object_r:fingerprintd_data_file:s0 + +# Fingerprint vendor data file +/data/vendor_de/[0-9]+/fpdata(/.*)? u:object_r:fingerprint_vendor_data_file:s0 + +# Bootchart data +/data/bootchart(/.*)? u:object_r:bootchart_data_file:s0 + +############################# +# Expanded data files +# +/mnt/expand(/.*)? u:object_r:mnt_expand_file:s0 +/mnt/expand/[^/]+(/.*)? u:object_r:system_data_file:s0 +/mnt/expand/[^/]+/app(/.*)? u:object_r:apk_data_file:s0 +/mnt/expand/[^/]+/app/[^/]+/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/mnt/expand/[^/]+/app/vmdl[^/]+\.tmp(/.*)? u:object_r:apk_tmp_file:s0 +/mnt/expand/[^/]+/app/vmdl[^/]+\.tmp/oat(/.*)? u:object_r:dalvikcache_data_file:s0 +/mnt/expand/[^/]+/local/tmp(/.*)? u:object_r:shell_data_file:s0 +/mnt/expand/[^/]+/media(/.*)? u:object_r:media_rw_data_file:s0 +/mnt/expand/[^/]+/misc/vold(/.*)? u:object_r:vold_data_file:s0 + +# coredump directory for userdebug/eng devices +/cores(/.*)? u:object_r:coredump_file:s0 + +# Wallpaper files +/data/system/users/[0-9]+/wallpaper_lock_orig u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper_lock u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper_orig u:object_r:wallpaper_file:s0 +/data/system/users/[0-9]+/wallpaper u:object_r:wallpaper_file:s0 + +# Ringtone files +/data/system_de/[0-9]+/ringtones(/.*)? u:object_r:ringtone_file:s0 + +# ShortcutManager icons, e.g. +# /data/system_ce/0/shortcut_service/bitmaps/com.example.app/1457472879282.png +/data/system_ce/[0-9]+/shortcut_service/bitmaps(/.*)? u:object_r:shortcut_manager_icons:s0 + +# User icon files +/data/system/users/[0-9]+/photo.png u:object_r:icon_file:s0 + +# vold per-user data +/data/misc_de/[0-9]+/vold(/.*)? u:object_r:vold_data_file:s0 +/data/misc_ce/[0-9]+/vold(/.*)? u:object_r:vold_data_file:s0 + +############################# +# efs files +# +/efs(/.*)? u:object_r:efs_file:s0 + +############################# +# Cache files +# +/cache(/.*)? u:object_r:cache_file:s0 +/cache/recovery(/.*)? u:object_r:cache_recovery_file:s0 +# General backup/restore interchange with apps +/cache/backup_stage(/.*)? u:object_r:cache_backup_file:s0 +# LocalTransport (backup) uses this subtree +/cache/backup(/.*)? u:object_r:cache_private_backup_file:s0 + +/data/cache(/.*)? u:object_r:cache_file:s0 +/data/cache/recovery(/.*)? u:object_r:cache_recovery_file:s0 +# General backup/restore interchange with apps +/data/cache/backup_stage(/.*)? u:object_r:cache_backup_file:s0 +# LocalTransport (backup) uses this subtree +/data/cache/backup(/.*)? u:object_r:cache_private_backup_file:s0 + +############################# +# Metadata files +# +/metadata(/.*)? u:object_r:metadata_file:s0 +/metadata/vold(/.*)? u:object_r:vold_metadata_file:s0 + +############################# +# asec containers +/mnt/asec(/.*)? u:object_r:asec_apk_file:s0 +/mnt/asec/[^/]+/[^/]+\.zip u:object_r:asec_public_file:s0 +/mnt/asec/[^/]+/lib(/.*)? u:object_r:asec_public_file:s0 +/data/app-asec(/.*)? u:object_r:asec_image_file:s0 + +############################# +# external storage +/mnt/media_rw(/.*)? u:object_r:mnt_media_rw_file:s0 +/mnt/user(/.*)? u:object_r:mnt_user_file:s0 +/mnt/runtime(/.*)? u:object_r:storage_file:s0 +/storage(/.*)? u:object_r:storage_file:s0 + +############################# +# mount point for read-write vendor partitions +/mnt/vendor(/.*)? u:object_r:mnt_vendor_file:s0 + +############################# +# mbox +/anbox-init.sh u:object_r:rootfs:s0 diff --git a/aosp/system/sepolicy/private/service_contexts b/aosp/system/sepolicy/private/service_contexts new file mode 100644 index 000000000..fd2c4305a --- /dev/null +++ b/aosp/system/sepolicy/private/service_contexts @@ -0,0 +1,191 @@ +accessibility u:object_r:accessibility_service:s0 +account u:object_r:account_service:s0 +activity u:object_r:activity_service:s0 +alarm u:object_r:alarm_service:s0 +android.os.UpdateEngineService u:object_r:update_engine_service:s0 +android.security.keystore u:object_r:keystore_service:s0 +android.service.gatekeeper.IGateKeeperService u:object_r:gatekeeper_service:s0 +appops u:object_r:appops_service:s0 +appwidget u:object_r:appwidget_service:s0 +assetatlas u:object_r:assetatlas_service:s0 +audio u:object_r:audio_service:s0 +autofill u:object_r:autofill_service:s0 +backup u:object_r:backup_service:s0 +batteryproperties u:object_r:batteryproperties_service:s0 +batterystats u:object_r:batterystats_service:s0 +battery u:object_r:battery_service:s0 +binder_calls_stats u:object_r:binder_calls_stats_service:s0 +bluetooth_manager u:object_r:bluetooth_manager_service:s0 +bluetooth u:object_r:bluetooth_service:s0 +broadcastradio u:object_r:broadcastradio_service:s0 +carrier_config u:object_r:radio_service:s0 +clipboard u:object_r:clipboard_service:s0 +com.android.net.IProxyService u:object_r:IProxyService_service:s0 +commontime_management u:object_r:commontime_management_service:s0 +common_time.clock u:object_r:mediaserver_service:s0 +common_time.config u:object_r:mediaserver_service:s0 +companiondevice u:object_r:companion_device_service:s0 +connectivity u:object_r:connectivity_service:s0 +connmetrics u:object_r:connmetrics_service:s0 +consumer_ir u:object_r:consumer_ir_service:s0 +content u:object_r:content_service:s0 +contexthub u:object_r:contexthub_service:s0 +country_detector u:object_r:country_detector_service:s0 +coverage u:object_r:coverage_service:s0 +cpuinfo u:object_r:cpuinfo_service:s0 +crossprofileapps u:object_r:crossprofileapps_service:s0 +dbinfo u:object_r:dbinfo_service:s0 +device_policy u:object_r:device_policy_service:s0 +device_identifiers u:object_r:device_identifiers_service:s0 +deviceidle u:object_r:deviceidle_service:s0 +devicestoragemonitor u:object_r:devicestoragemonitor_service:s0 +diskstats u:object_r:diskstats_service:s0 +display u:object_r:display_service:s0 +netd_listener u:object_r:netd_listener_service:s0 +network_watchlist u:object_r:network_watchlist_service:s0 +DockObserver u:object_r:DockObserver_service:s0 +dreams u:object_r:dreams_service:s0 +drm.drmManager u:object_r:drmserver_service:s0 +dropbox u:object_r:dropbox_service:s0 +dumpstate u:object_r:dumpstate_service:s0 +econtroller u:object_r:radio_service:s0 +euicc_card_controller u:object_r:radio_service:s0 +lowpan u:object_r:lowpan_service:s0 +ethernet u:object_r:ethernet_service:s0 +fingerprint u:object_r:fingerprint_service:s0 +font u:object_r:font_service:s0 +android.hardware.fingerprint.IFingerprintDaemon u:object_r:fingerprintd_service:s0 +gfxinfo u:object_r:gfxinfo_service:s0 +graphicsstats u:object_r:graphicsstats_service:s0 +gpu u:object_r:gpu_service:s0 +hardware u:object_r:hardware_service:s0 +hardware_properties u:object_r:hardware_properties_service:s0 +hdmi_control u:object_r:hdmi_control_service:s0 +incident u:object_r:incident_service:s0 +inputflinger u:object_r:inputflinger_service:s0 +input_method u:object_r:input_method_service:s0 +input u:object_r:input_service:s0 +installd u:object_r:installd_service:s0 +iphonesubinfo_msim u:object_r:radio_service:s0 +iphonesubinfo2 u:object_r:radio_service:s0 +iphonesubinfo u:object_r:radio_service:s0 +ims u:object_r:radio_service:s0 +imms u:object_r:imms_service:s0 +ipsec u:object_r:ipsec_service:s0 +isms_msim u:object_r:radio_service:s0 +isms2 u:object_r:radio_service:s0 +isms u:object_r:radio_service:s0 +isub u:object_r:radio_service:s0 +jobscheduler u:object_r:jobscheduler_service:s0 +launcherapps u:object_r:launcherapps_service:s0 +location u:object_r:location_service:s0 +lock_settings u:object_r:lock_settings_service:s0 +media.aaudio u:object_r:audioserver_service:s0 +media.audio_flinger u:object_r:audioserver_service:s0 +media.audio_policy u:object_r:audioserver_service:s0 +media.camera u:object_r:cameraserver_service:s0 +media.camera.proxy u:object_r:cameraproxy_service:s0 +media.log u:object_r:audioserver_service:s0 +media.player u:object_r:mediaserver_service:s0 +media.metrics u:object_r:mediametrics_service:s0 +media.extractor u:object_r:mediaextractor_service:s0 +media.extractor.update u:object_r:mediaextractor_update_service:s0 +media.codec u:object_r:mediacodec_service:s0 +media.resource_manager u:object_r:mediaserver_service:s0 +media.sound_trigger_hw u:object_r:audioserver_service:s0 +media.drm u:object_r:mediadrmserver_service:s0 +media_projection u:object_r:media_projection_service:s0 +media_resource_monitor u:object_r:media_session_service:s0 +media_router u:object_r:media_router_service:s0 +media_session u:object_r:media_session_service:s0 +meminfo u:object_r:meminfo_service:s0 +midi u:object_r:midi_service:s0 +mount u:object_r:mount_service:s0 +netd u:object_r:netd_service:s0 +netpolicy u:object_r:netpolicy_service:s0 +netstats u:object_r:netstats_service:s0 +network_management u:object_r:network_management_service:s0 +network_score u:object_r:network_score_service:s0 +network_time_update_service u:object_r:network_time_update_service:s0 +nfc u:object_r:nfc_service:s0 +notification u:object_r:notification_service:s0 +oem_lock u:object_r:oem_lock_service:s0 +otadexopt u:object_r:otadexopt_service:s0 +overlay u:object_r:overlay_service:s0 +package u:object_r:package_service:s0 +package_native u:object_r:package_native_service:s0 +perfprofd u:object_r:perfprofd_service:s0 +permission u:object_r:permission_service:s0 +persistent_data_block u:object_r:persistent_data_block_service:s0 +phone_msim u:object_r:radio_service:s0 +phone1 u:object_r:radio_service:s0 +phone2 u:object_r:radio_service:s0 +phone u:object_r:radio_service:s0 +pinner u:object_r:pinner_service:s0 +power u:object_r:power_service:s0 +print u:object_r:print_service:s0 +processinfo u:object_r:processinfo_service:s0 +procstats u:object_r:procstats_service:s0 +radio.phonesubinfo u:object_r:radio_service:s0 +radio.phone u:object_r:radio_service:s0 +radio.sms u:object_r:radio_service:s0 +recovery u:object_r:recovery_service:s0 +restrictions u:object_r:restrictions_service:s0 +rttmanager u:object_r:rttmanager_service:s0 +samplingprofiler u:object_r:samplingprofiler_service:s0 +scheduling_policy u:object_r:scheduling_policy_service:s0 +search u:object_r:search_service:s0 +secure_element u:object_r:secure_element_service:s0 +sec_key_att_app_id_provider u:object_r:sec_key_att_app_id_provider_service:s0 +sensorservice u:object_r:sensorservice_service:s0 +serial u:object_r:serial_service:s0 +servicediscovery u:object_r:servicediscovery_service:s0 +settings u:object_r:settings_service:s0 +shortcut u:object_r:shortcut_service:s0 +simphonebook_msim u:object_r:radio_service:s0 +simphonebook2 u:object_r:radio_service:s0 +simphonebook u:object_r:radio_service:s0 +sip u:object_r:radio_service:s0 +slice u:object_r:slice_service:s0 +stats u:object_r:stats_service:s0 +statscompanion u:object_r:statscompanion_service:s0 +soundtrigger u:object_r:voiceinteraction_service:s0 +statusbar u:object_r:statusbar_service:s0 +storaged u:object_r:storaged_service:s0 +storaged_pri u:object_r:storaged_service:s0 +storagestats u:object_r:storagestats_service:s0 +SurfaceFlinger u:object_r:surfaceflinger_service:s0 +system_update u:object_r:system_update_service:s0 +task u:object_r:task_service:s0 +telecom u:object_r:telecom_service:s0 +telephony.registry u:object_r:registry_service:s0 +textclassification u:object_r:textclassification_service:s0 +textservices u:object_r:textservices_service:s0 +timezone u:object_r:timezone_service:s0 +thermalservice u:object_r:thermal_service:s0 +trust u:object_r:trust_service:s0 +tv_input u:object_r:tv_input_service:s0 +uimode u:object_r:uimode_service:s0 +updatelock u:object_r:updatelock_service:s0 +usagestats u:object_r:usagestats_service:s0 +usb u:object_r:usb_service:s0 +user u:object_r:user_service:s0 +vibrator u:object_r:vibrator_service:s0 +virtual_touchpad u:object_r:virtual_touchpad_service:s0 +voiceinteraction u:object_r:voiceinteraction_service:s0 +vold u:object_r:vold_service:s0 +vr_hwc u:object_r:vr_hwc_service:s0 +vrmanager u:object_r:vr_manager_service:s0 +wallpaper u:object_r:wallpaper_service:s0 +webviewupdate u:object_r:webviewupdate_service:s0 +wifip2p u:object_r:wifip2p_service:s0 +wifiscanner u:object_r:wifiscanner_service:s0 +wifi u:object_r:wifi_service:s0 +wificond u:object_r:wificond_service:s0 +wifiaware u:object_r:wifiaware_service:s0 +wifirtt u:object_r:rttmanager_service:s0 +window u:object_r:window_service:s0 +cph_performance u:object_r:activity_service:s0 +phoneadjust u:object_r:activity_service:s0 +attributes u:object_r:activity_service:s0 +* u:object_r:default_android_service:s0 diff --git a/aosp/system/sepolicy/public/domain.te b/aosp/system/sepolicy/public/domain.te new file mode 100644 index 000000000..8a461343b --- /dev/null +++ b/aosp/system/sepolicy/public/domain.te @@ -0,0 +1,1403 @@ +# Rules for all domains. + +# Allow reaping by init. +allow domain init:process sigchld; + +# Intra-domain accesses. +allow domain self:process { + fork + sigchld + sigkill + sigstop + signull + signal + getsched + setsched + getsession + getpgid + setpgid + getcap + setcap + getattr + setrlimit +}; +allow domain self:fd use; +allow domain proc:dir r_dir_perms; +allow domain proc_net:dir search; +r_dir_file(domain, self) +allow domain self:{ fifo_file file } rw_file_perms; +allow domain self:unix_dgram_socket { create_socket_perms sendto }; +allow domain self:unix_stream_socket { create_stream_socket_perms connectto }; + +# Inherit or receive open files from others. +allow domain init:fd use; + +userdebug_or_eng(` + allow domain su:fd use; + allow domain su:unix_stream_socket { connectto getattr getopt read write shutdown }; + allow domain su:unix_dgram_socket sendto; + + allow { domain -init } su:binder { call transfer }; + + # Running something like "pm dump com.android.bluetooth" requires + # fifo writes + allow domain su:fifo_file { write getattr }; + + # allow "gdbserver --attach" to work for su. + allow domain su:process sigchld; + + # Allow writing coredumps to /cores/* + allow domain coredump_file:file create_file_perms; + allow domain coredump_file:dir ra_dir_perms; +') + +# Root fs. +allow domain rootfs:dir search; +allow domain rootfs:lnk_file { read getattr }; + +# Device accesses. +allow domain device:dir search; +allow domain dev_type:lnk_file r_file_perms; +allow domain devpts:dir search; +allow domain socket_device:dir r_dir_perms; +allow domain owntty_device:chr_file rw_file_perms; +allow domain null_device:chr_file rw_file_perms; +allow domain zero_device:chr_file rw_file_perms; +allow domain ashmem_device:chr_file rw_file_perms; +# /dev/binder can be accessed by non-vendor domains and by apps +allow { + coredomain + appdomain + binder_in_vendor_violators # TODO(b/35870313): Remove once all violations are gone + -hwservicemanager +} binder_device:chr_file rw_file_perms; +# Devices which are not full TREBLE have fewer restrictions on access to /dev/binder +not_full_treble(`allow { domain -hwservicemanager -vndservicemanager } binder_device:chr_file rw_file_perms;') +allow { domain -servicemanager -vndservicemanager -isolated_app } hwbinder_device:chr_file rw_file_perms; +allow domain ptmx_device:chr_file rw_file_perms; +allow domain alarm_device:chr_file r_file_perms; +allow domain random_device:chr_file rw_file_perms; +allow domain proc_random:dir r_dir_perms; +allow domain proc_random:file r_file_perms; +allow domain properties_device:dir { search getattr }; +allow domain properties_serial:file r_file_perms; +allow domain property_info:file r_file_perms; + +# For now, everyone can access core property files +# Device specific properties are not granted by default +not_compatible_property(` + get_prop(domain, core_property_type) + get_prop(domain, exported_dalvik_prop) + get_prop(domain, exported_ffs_prop) + get_prop(domain, exported_system_radio_prop) + get_prop(domain, exported2_config_prop) + get_prop(domain, exported2_radio_prop) + get_prop(domain, exported2_system_prop) + get_prop(domain, exported2_vold_prop) + get_prop(domain, exported3_default_prop) + get_prop(domain, exported3_radio_prop) + get_prop(domain, exported3_system_prop) + get_prop(domain, vendor_default_prop) +') +compatible_property_only(` + get_prop({coredomain appdomain shell}, core_property_type) + get_prop({coredomain appdomain shell}, exported_dalvik_prop) + get_prop({coredomain appdomain shell}, exported_ffs_prop) + get_prop({coredomain appdomain shell}, exported_system_radio_prop) + get_prop({coredomain appdomain shell}, exported2_config_prop) + get_prop({coredomain appdomain shell}, exported2_radio_prop) + get_prop({coredomain appdomain shell}, exported2_system_prop) + get_prop({coredomain appdomain shell}, exported2_vold_prop) + get_prop({coredomain appdomain shell}, exported3_default_prop) + get_prop({coredomain appdomain shell}, exported3_radio_prop) + get_prop({coredomain appdomain shell}, exported3_system_prop) + userdebug_or_eng(` + get_prop(su, core_property_type) + get_prop(su, exported_dalvik_prop) + get_prop(su, exported_ffs_prop) + get_prop(su, exported_system_radio_prop) + get_prop(su, exported2_config_prop) + get_prop(su, exported2_radio_prop) + get_prop(su, exported2_system_prop) + get_prop(su, exported2_vold_prop) + get_prop(su, exported3_default_prop) + get_prop(su, exported3_radio_prop) + get_prop(su, exported3_system_prop) + ') + get_prop({domain -coredomain -appdomain}, vendor_default_prop) +') + +# Public readable properties +get_prop(domain, debug_prop) +get_prop(domain, exported_config_prop) +get_prop(domain, exported_default_prop) +get_prop(domain, exported_dumpstate_prop) +get_prop(domain, exported_fingerprint_prop) +get_prop(domain, exported_radio_prop) +get_prop(domain, exported_secure_prop) +get_prop(domain, exported_system_prop) +get_prop(domain, exported_vold_prop) +get_prop(domain, exported2_default_prop) +get_prop(domain, logd_prop) + +# Let everyone read log properties, so that liblog can avoid sending unloggable +# messages to logd. +get_prop(domain, log_property_type) +dontaudit domain property_type:file audit_access; +allow domain property_contexts_file:file r_file_perms; + +allow domain init:key search; +allow domain vold:key search; + +# logd access +write_logd(domain) + +# System file accesses. +allow domain system_file:dir { search getattr }; +allow domain system_file:file { execute read open getattr map }; +allow domain system_file:lnk_file { getattr read }; + +# Make sure system/vendor split doesn not affect non-treble +# devices +not_full_treble(` + allow domain vendor_file_type:dir { search getattr }; + allow domain vendor_file_type:file { execute read open getattr map }; + allow domain vendor_file_type:lnk_file { getattr read }; +') + +# All domains are allowed to open and read directories +# that contain HAL implementations (e.g. passthrough +# HALs require clients to have these permissions) +allow domain vendor_hal_file:dir r_dir_perms; + +# Everyone can read and execute all same process HALs +allow domain same_process_hal_file:dir r_dir_perms; +allow domain same_process_hal_file:file { execute read open getattr map }; + +# Any process can load vndk-sp libraries, which are system libraries +# used by same process HALs +allow domain vndk_sp_file:dir r_dir_perms; +allow domain vndk_sp_file:file { execute read open getattr map }; + +# All domains get access to /vendor/etc +allow domain vendor_configs_file:dir r_dir_perms; +allow domain vendor_configs_file:file { read open getattr }; + +full_treble_only(` + # Allow all domains to be able to follow /system/vendor and/or + # /vendor/odm symlinks. + allow domain vendor_file_type:lnk_file { getattr open read }; + + # This is required to be able to search & read /vendor/lib64 + # in order to lookup vendor libraries. The execute permission + # for coredomains is granted *only* for same process HALs + allow domain vendor_file:dir { getattr search }; + + # Allow reading and executing out of /vendor to all vendor domains + allow { domain -coredomain } vendor_file_type:dir r_dir_perms; + allow { domain -coredomain } vendor_file_type:file { read open getattr execute map }; + allow { domain -coredomain } vendor_file_type:lnk_file { getattr read }; +') + +# read and stat any sysfs symlinks +allow domain sysfs:lnk_file { getattr read }; + +# libc references /data/misc/zoneinfo for timezone related information +# This directory is considered to be a VNDK-stable +allow domain zoneinfo_data_file:file r_file_perms; +allow domain zoneinfo_data_file:dir r_dir_perms; + +# Lots of processes access current CPU information +r_dir_file(domain, sysfs_devices_system_cpu) + +r_dir_file(domain, sysfs_usb); + +# files under /data. +not_full_treble(` + allow domain system_data_file:dir getattr; +') +allow { coredomain appdomain } system_data_file:dir getattr; +# /data has the label system_data_file. Vendor components need the search +# permission on system_data_file for path traversal to /data/vendor. +allow domain system_data_file:dir search; +# TODO restrict this to non-coredomain +allow domain vendor_data_file:dir { getattr search }; + +# required by the dynamic linker +allow domain proc:lnk_file { getattr read }; + +# /proc/cpuinfo +allow domain proc_cpuinfo:file r_file_perms; + +# jemalloc needs to read /proc/sys/vm/overcommit_memory +allow domain proc_overcommit_memory:file r_file_perms; + +# profiling needs to read /proc/sys/kernel/perf_event_max_sample_rate +allow domain proc_perf:file r_file_perms; + +# toybox loads libselinux which stats /sys/fs/selinux/ +allow domain selinuxfs:dir search; +allow domain selinuxfs:file getattr; +allow domain sysfs:dir search; +allow domain selinuxfs:filesystem getattr; + +# For /acct/uid/*/tasks. +allow domain cgroup:dir { search write }; +allow domain cgroup:file w_file_perms; + +# Almost all processes log tracing information to +# /sys/kernel/debug/tracing/trace_marker +# The reason behind this is documented in b/6513400 +allow domain debugfs:dir search; +allow domain debugfs_tracing:dir search; +allow domain debugfs_tracing_debug:dir search; +allow domain debugfs_trace_marker:file w_file_perms; + +# Filesystem access. +allow domain fs_type:filesystem getattr; +allow domain fs_type:dir getattr; + +# Restrict all domains to a whitelist for common socket types. Additional +# ioctl commands may be added to individual domains, but this sets safe +# defaults for all processes. Note that granting this whitelist to domain does +# not grant the ioctl permission on these socket types. That must be granted +# separately. +allowxperm domain domain:{ rawip_socket tcp_socket udp_socket } + ioctl { unpriv_sock_ioctls unpriv_tty_ioctls }; +# default whitelist for unix sockets. +allowxperm domain domain:{ unix_dgram_socket unix_stream_socket } + ioctl unpriv_unix_sock_ioctls; + +# Restrict PTYs to only whitelisted ioctls. +# Note that granting this whitelist to domain does +# not grant the wider ioctl permission. That must be granted +# separately. +allowxperm domain devpts:chr_file ioctl unpriv_tty_ioctls; + +# Workaround for policy compiler being too aggressive and removing hwservice_manager_type +# when it's not explicitly used in allow rules +allow { domain -domain } hwservice_manager_type:hwservice_manager { add find }; +# Workaround for policy compiler being too aggressive and removing vndservice_manager_type +# when it's not explicitly used in allow rules +allow { domain -domain } vndservice_manager_type:service_manager { add find }; + +# Under ASAN, processes will try to read /data, as the sanitized libraries are there. +with_asan(`allow domain system_data_file:dir getattr;') + +### +### neverallow rules +### + +# All socket ioctls must be restricted to a whitelist. +neverallowxperm domain domain:socket_class_set ioctl { 0 }; + +# b/68014825 and https://android-review.googlesource.com/516535 +# rfc6093 says that processes should not use the TCP urgent mechanism +neverallowxperm domain domain:socket_class_set ioctl { SIOCATMARK }; + +# TIOCSTI is only ever used for exploits. Block it. +# b/33073072, b/7530569 +# http://www.openwall.com/lists/oss-security/2016/09/26/14 +neverallowxperm * devpts:chr_file ioctl TIOCSTI; + +# Do not allow any domain other than init to create unlabeled files. +neverallow { domain -init -recovery } unlabeled:dir_file_class_set create; + +# Limit device node creation to these whitelisted domains. +neverallow { + domain + -kernel + -init + -ueventd + -vold +} self:global_capability_class_set mknod; + +# Limit raw I/O to these whitelisted domains. Do not apply to debug builds. +neverallow { + domain + userdebug_or_eng(`-domain') + -kernel + -init + -recovery + -ueventd + -healthd + -uncrypt + -tee +} self:global_capability_class_set sys_rawio; + +# No process can map low memory (< CONFIG_LSM_MMAP_MIN_ADDR). +neverallow * self:memprotect mmap_zero; + +# No domain needs mac_override as it is unused by SELinux. +neverallow * self:global_capability2_class_set mac_override; + +# Disallow attempts to set contexts not defined in current policy +# This helps guarantee that unknown or dangerous contents will not ever +# be set. +neverallow * self:global_capability2_class_set mac_admin; + +# Once the policy has been loaded there shall be none to modify the policy. +# It is sealed. +neverallow * kernel:security load_policy; + +# Only init prior to switching context should be able to set enforcing mode. +# init starts in kernel domain and switches to init domain via setcon in +# the init.rc, so the setenforce occurs while still in kernel. After +# switching domains, there is never any need to setenforce again by init. +neverallow * kernel:security setenforce; +neverallow { domain -kernel } kernel:security setcheckreqprot; + +# No booleans in AOSP policy, so no need to ever set them. +neverallow * kernel:security setbool; + +# Adjusting the AVC cache threshold. +# Not presently allowed to anything in policy, but possibly something +# that could be set from init.rc. +neverallow { domain -init } kernel:security setsecparam; + +# Only init, ueventd, shell and system_server should be able to access HW RNG +neverallow { + domain + -init + -shell # For CTS and is restricted to getattr in shell.te + -system_server + -ueventd +} hw_random_device:chr_file *; +# b/78174219 b/64114943 +neverallow { + domain + -init + -shell # stat of /dev, getattr only + -vendor_init + -ueventd +} keychord_device:chr_file *; + +# Ensure that all entrypoint executables are in exec_type or postinstall_file. +neverallow * { file_type -exec_type -postinstall_file }:file entrypoint; + +# Ensure that nothing in userspace can access /dev/mem or /dev/kmem +neverallow { + domain + -shell # For CTS and is restricted to getattr in shell.te + -ueventd # Further restricted in ueventd.te +} kmem_device:chr_file *; +neverallow * kmem_device:chr_file ~{ create relabelto unlink setattr getattr }; + +#Ensure that nothing in userspace can access /dev/port +neverallow { + domain + -shell # Shell user should not have any abilities outside of getattr + -ueventd +} port_device:chr_file *; +neverallow * port_device:chr_file ~{ create relabelto unlink setattr getattr }; +# Only init should be able to configure kernel usermodehelpers or +# security-sensitive proc settings. +neverallow { domain -init } usermodehelper:file { append write }; +neverallow { domain -init -ueventd } sysfs_usermodehelper:file { append write }; +neverallow { domain -init -vendor_init } proc_security:file { append open read write }; + +# No domain should be allowed to ptrace init. +neverallow * init:process ptrace; + +# Init can't do anything with binder calls. If this neverallow rule is being +# triggered, it's probably due to a service with no SELinux domain. +neverallow * init:binder *; +neverallow * vendor_init:binder *; + +# Don't allow raw read/write/open access to block_device +# Rather force a relabel to a more specific type +neverallow { domain -kernel -init -recovery } block_device:blk_file { open read write }; + +# Do not allow renaming of block files or character files +# Ability to do so can lead to possible use in an exploit chain +# e.g. https://googleprojectzero.blogspot.com/2016/12/chrome-os-exploit-one-byte-overflow-and.html +neverallow * *:{ blk_file chr_file } rename; + +# Don't allow raw read/write/open access to generic devices. +# Rather force a relabel to a more specific type. +neverallow domain device:chr_file { open read write }; + +# Limit what domains can mount filesystems or change their mount flags. +# sdcard_type / vfat is exempt as a larger set of domains need +# this capability, including device-specific domains. +neverallow { domain -kernel -init -recovery -vold -zygote -update_engine -otapreopt_chroot } { fs_type -sdcard_type }:filesystem { mount remount relabelfrom relabelto }; + +# +# Assert that, to the extent possible, we're not loading executable content from +# outside the rootfs or /system partition except for a few whitelisted domains. +# +neverallow { + domain + -appdomain + with_asan(`-asan_extract') + -dumpstate + -shell + userdebug_or_eng(`-su') + -webview_zygote + -zygote + userdebug_or_eng(`-mediaextractor') +} { + file_type + -system_file + -vendor_file_type + -exec_type + -postinstall_file +}:file execute; + +neverallow { + domain + -appdomain # for oemfs + -bootanim # for oemfs + -recovery # for /tmp/update_binary in tmpfs +} { fs_type -rootfs }:file execute; + +# Files from cache should never be executed +neverallow domain { cache_file cache_backup_file cache_private_backup_file cache_recovery_file }:file execute; + +# Protect most domains from executing arbitrary content from /data. +neverallow { + domain + -appdomain +} { + data_file_type + -dalvikcache_data_file + -system_data_file # shared libs in apks + -apk_data_file +}:file no_x_file_perms; + +# The test files and executables MUST not be accessible to any domain +neverallow { domain userdebug_or_eng(`-kernel') } nativetest_data_file:file_class_set no_w_file_perms; +neverallow domain nativetest_data_file:dir no_w_dir_perms; +neverallow { domain userdebug_or_eng(`-shell') } nativetest_data_file:file no_x_file_perms; + +# Only the init property service should write to /data/property and /dev/__properties__ +neverallow { domain -init } property_data_file:dir no_w_dir_perms; +neverallow { domain -init } property_data_file:file { no_w_file_perms no_x_file_perms }; +neverallow { domain -init } property_type:file { no_w_file_perms no_x_file_perms }; +neverallow { domain -init } properties_device:file { no_w_file_perms no_x_file_perms }; +neverallow { domain -init } properties_serial:file { no_w_file_perms no_x_file_perms }; + +# Nobody should be doing writes to /system & /vendor +# These partitions are intended to be read-only and must never be +# modified. Doing so would violate important Android security guarantees +# and invalidate dm-verity signatures. +neverallow { + domain + with_asan(`-asan_extract') +} { + system_file + vendor_file_type + exec_type +}:dir_file_class_set { create write setattr relabelfrom append unlink link rename }; + +neverallow { domain -kernel with_asan(`-asan_extract') } { system_file vendor_file_type exec_type }:dir_file_class_set relabelto; + +# Don't allow mounting on top of /system files or directories +neverallow * exec_type:dir_file_class_set mounton; +neverallow { domain -init } { system_file vendor_file_type }:dir_file_class_set mounton; + +# Nothing should be writing to files in the rootfs. +neverallow * rootfs:file { create write setattr relabelto append unlink link rename }; + +# Restrict context mounts to specific types marked with +# the contextmount_type attribute. +neverallow * {fs_type -contextmount_type}:filesystem relabelto; + +# Ensure that context mount types are not writable, to ensure that +# the write to /system restriction above is not bypassed via context= +# mount to another type. +neverallow * contextmount_type:dir_file_class_set + { create write setattr relabelfrom relabelto append unlink link rename }; + +# Do not allow service_manager add for default service labels. +# Instead domains should use a more specific type such as +# system_app_service rather than the generic type. +# New service_types are defined in {,hw,vnd}service.te and new mappings +# from service name to service_type are defined in {,hw,vnd}service_contexts. +neverallow * default_android_service:service_manager add; +neverallow * default_android_vndservice:service_manager { add find }; +neverallow * default_android_hwservice:hwservice_manager { add find }; + +# Looking up the base class/interface of all HwBinder services is a bad idea. +# hwservicemanager currently offer such lookups only to make it so that security +# decisions are expressed in SELinux policy. However, it's unclear whether this +# lookup has security implications. If it doesn't, hwservicemanager should be +# modified to not offer this lookup. +# This rule can be removed if hwservicemanager is modified to not permit these +# lookups. +neverallow * hidl_base_hwservice:hwservice_manager find; + +# Require that domains explicitly label unknown properties, and do not allow +# anyone but init to modify unknown properties. +neverallow { domain -init -vendor_init } default_prop:property_service set; +neverallow { domain -init -vendor_init } mmc_prop:property_service set; + +compatible_property_only(` + neverallow { domain -init } default_prop:property_service set; + neverallow { domain -init } mmc_prop:property_service set; + neverallow { domain -init -vendor_init } exported_default_prop:property_service set; + neverallow { domain -init } exported_secure_prop:property_service set; + neverallow { domain -init } exported2_default_prop:property_service set; + neverallow { domain -init -vendor_init } exported3_default_prop:property_service set; + neverallow { domain -init -vendor_init } vendor_default_prop:property_service set; +') + +# Only core domains are allowed to access package_manager properties +neverallow { domain -init -system_server } pm_prop:property_service set; +neverallow { domain -coredomain } pm_prop:file no_rw_file_perms; + +compatible_property_only(` + neverallow { domain -init -system_server -vendor_init } exported_pm_prop:property_service set; + neverallow { domain -coredomain -vendor_init } exported_pm_prop:file no_rw_file_perms; +') + +# Do not allow reading device's serial number from system properties except form +# a few whitelisted domains. +neverallow { + domain + -adbd + -dumpstate + -hal_drm_server + -hal_cas_server + -init + -mediadrmserver + -recovery + -shell + -system_server + -vendor_init +} serialno_prop:file r_file_perms; + +# Do not allow reading the last boot timestamp from system properties +neverallow { domain -init -system_server -dumpstate } firstboot_prop:file r_file_perms; + +neverallow { + domain + -init + -recovery + -system_server + -shell # Shell is further restricted in shell.te + -ueventd # Further restricted in ueventd.te +} frp_block_device:blk_file no_rw_file_perms; + +# The metadata block device is set aside for device encryption and +# verified boot metadata. It may be reset at will and should not +# be used by other domains. +neverallow { + domain + -init + -recovery + -vold + -e2fs + -fsck +} metadata_block_device:blk_file { append link rename write open read ioctl lock }; + +# No domain other than recovery and update_engine can write to system partition(s). +neverallow { domain -recovery -update_engine } system_block_device:blk_file { write append }; + +# No domains other than install_recovery or recovery can write to recovery. +neverallow { domain -install_recovery -recovery } recovery_block_device:blk_file { write append }; + +# No domains other than a select few can access the misc_block_device. This +# block device is reserved for OTA use. +# Do not assert this rule on userdebug/eng builds, due to some devices using +# this partition for testing purposes. +neverallow { + domain + userdebug_or_eng(`-domain') # exclude debuggable builds + -hal_bootctl_server + -init + -uncrypt + -update_engine + -vendor_init + -vold + -recovery + -ueventd +} misc_block_device:blk_file { append link relabelfrom rename write open read ioctl lock }; + +# Only (hw|vnd|)servicemanager should be able to register with binder as the context manager +neverallow { domain -servicemanager -hwservicemanager -vndservicemanager } *:binder set_context_mgr; +# The service managers are only allowed to access their own device node +neverallow servicemanager hwbinder_device:chr_file no_rw_file_perms; +neverallow servicemanager vndbinder_device:chr_file no_rw_file_perms; +neverallow hwservicemanager binder_device:chr_file no_rw_file_perms; +neverallow hwservicemanager vndbinder_device:chr_file no_rw_file_perms; +neverallow vndservicemanager binder_device:chr_file no_rw_file_perms; +neverallow vndservicemanager hwbinder_device:chr_file no_rw_file_perms; + +# On full TREBLE devices, only core components and apps can use Binder and servicemanager. Non-core +# domain apps need this because Android framework offers many of its services to apps as Binder +# services. +full_treble_only(` + neverallow { + domain + -coredomain + -appdomain + -binder_in_vendor_violators # TODO(b/35870313): Remove once all violations are gone + } binder_device:chr_file rw_file_perms; +') +full_treble_only(` + neverallow { + domain + -coredomain + -appdomain # restrictions for vendor apps are declared lower down + -binder_in_vendor_violators # TODO(b/35870313): Remove once all violations are gone + } service_manager_type:service_manager find; +') +full_treble_only(` + # Vendor apps are permited to use only stable public services. If they were to use arbitrary + # services which can change any time framework/core is updated, breakage is likely. + neverallow { + appdomain + -coredomain + } { + service_manager_type + -app_api_service + -ephemeral_app_api_service + -audioserver_service # TODO(b/36783122) remove exemptions below once app_api_service is fixed + -cameraserver_service + -drmserver_service + -keystore_service + -mediadrmserver_service + -mediaextractor_service + -mediametrics_service + -mediaserver_service + -nfc_service + -radio_service + -virtual_touchpad_service + -vr_hwc_service + -vr_manager_service + }:service_manager find; +') +full_treble_only(` + neverallow { + domain + -coredomain + -appdomain + -binder_in_vendor_violators # TODO(b/35870313): Remove once all violations are gone + } servicemanager:binder { call transfer }; +') + +# On full TREBLE devices, only vendor components, shell, and su can use VendorBinder. +full_treble_only(` + neverallow { + coredomain + -shell + userdebug_or_eng(`-su') + -ueventd # uevent is granted create for this device, but we still neverallow I/O below + } vndbinder_device:chr_file rw_file_perms; +') +full_treble_only(` + neverallow ueventd vndbinder_device:chr_file { read write append ioctl }; +') +full_treble_only(` + neverallow { + coredomain + -shell + userdebug_or_eng(`-su') + } vndservice_manager_type:service_manager *; +') +full_treble_only(` + neverallow { + coredomain + -shell + userdebug_or_eng(`-su') + } vndservicemanager:binder *; +') + +# On full TREBLE devices, socket communications between core components and vendor components are +# not permitted. + # Most general rules first, more specific rules below. + + # Core domains are not permitted to initiate communications to vendor domain sockets. + # We are not restricting the use of already established sockets because it is fine for a process + # to obtain an already established socket via some public/official/stable API and then exchange + # data with its peer over that socket. The wire format in this scenario is dicatated by the API + # and thus does not break the core-vendor separation. +full_treble_only(` + neverallow_establish_socket_comms({ + coredomain + -init + -adbd + }, { + domain + -coredomain + -socket_between_core_and_vendor_violators + }); +') + # Vendor domains are not permitted to initiate communications to core domain sockets +full_treble_only(` + neverallow_establish_socket_comms({ + domain + -coredomain + -appdomain + -socket_between_core_and_vendor_violators + }, { + coredomain + -logd # Logging by writing to logd Unix domain socket is public API + -netd # netdomain needs this + -mdnsd # netdomain needs this + userdebug_or_eng(`-su') # communications with su are permitted only on userdebug or eng builds + -init + -incidentd # TODO(b/35870313): Remove incidentd from this list once vendor domains no longer declare Binder services + -tombstoned # TODO(b/36604251): Remove tombstoned from this list once mediacodec (OMX HAL) no longer declares Binder services + }); +') + + # Vendor domains (except netdomain) are not permitted to initiate communications to netd sockets +full_treble_only(` + neverallow_establish_socket_comms({ + domain + -coredomain + -netdomain + -socket_between_core_and_vendor_violators + }, netd); +') + + # Vendor domains are not permitted to initiate create/open sockets owned by core domains +full_treble_only(` + neverallow { + domain + -coredomain + -appdomain # appdomain restrictions below + -data_between_core_and_vendor_violators # b/70393317 + -socket_between_core_and_vendor_violators + -vendor_init + } { + coredomain_socket + core_data_file_type + unlabeled # used only by core domains + }:sock_file ~{ append getattr ioctl read write }; +') +full_treble_only(` + neverallow { + appdomain + -coredomain + } { + coredomain_socket + unlabeled # used only by core domains + core_data_file_type + -app_data_file + -pdx_endpoint_socket_type # used by VR layer + -pdx_channel_socket_type # used by VR layer + }:sock_file ~{ append getattr ioctl read write }; +') + + # Core domains are not permitted to create/open sockets owned by vendor domains +full_treble_only(` + neverallow { + coredomain + -init + -ueventd + -socket_between_core_and_vendor_violators + } { + file_type + dev_type + -coredomain_socket + -core_data_file_type + -unlabeled + }:sock_file ~{ append getattr ioctl read write }; +') + +# On TREBLE devices, vendor and system components are only allowed to share +# files by passing open FDs over hwbinder. Ban all directory access and all file +# accesses other than what can be applied to an open FD such as +# ioctl/stat/read/write/append. This is enforced by segregating /data. +# Vendor domains may directly access file in /data/vendor by path, but may only +# access files outside of /data/vendor via an open FD passed over hwbinder. +# Likewise, core domains may only directly access files outside /data/vendor by +# path and files in /data/vendor by open FD. +full_treble_only(` + # only coredomains may only access core_data_file_type, particularly not + # /data/vendor + neverallow { + coredomain + -appdomain # TODO(b/34980020) remove exemption for appdomain + -data_between_core_and_vendor_violators + -init + -vold_prepare_subdirs + } { + data_file_type + -core_data_file_type + }:file_class_set ~{ append getattr ioctl read write }; +') +full_treble_only(` + neverallow { + coredomain + -appdomain # TODO(b/34980020) remove exemption for appdomain + -data_between_core_and_vendor_violators + -init + -vold_prepare_subdirs + } { + data_file_type + -core_data_file_type + # TODO(b/72998741) Remove exemption. Further restricted in a subsequent + # neverallow. Currently only getattr and search are allowed. + -vendor_data_file + }:dir *; + +') +full_treble_only(` + # vendor domains may only access files in /data/vendor, never core_data_file_types + neverallow { + domain + -appdomain # TODO(b/34980020) remove exemption for appdomain + -coredomain + -data_between_core_and_vendor_violators # TODO(b/34980020) Remove once all violators have been cleaned up + -vendor_init + } { + core_data_file_type + # libc includes functions like mktime and localtime which attempt to access + # files in /data/misc/zoneinfo/tzdata file. These functions are considered + # vndk-stable and thus must be allowed for all processes. + -zoneinfo_data_file + userdebug_or_eng(`-exagear_debug_file') + }:file_class_set ~{ append getattr ioctl read write }; + neverallow { + vendor_init + -data_between_core_and_vendor_violators + } { + core_data_file_type + -unencrypted_data_file + -zoneinfo_data_file + userdebug_or_eng(`-exagear_debug_file') + }:file_class_set ~{ append getattr ioctl read write }; + # vendor init needs to be able to read unencrypted_data_file to create directories with FBE. + # The vendor init binary lives on the system partition so there is not a concern with stability. + neverallow vendor_init unencrypted_data_file:file ~r_file_perms; +') +full_treble_only(` + # vendor domains may only access dirs in /data/vendor, never core_data_file_types + neverallow { + domain + -appdomain # TODO(b/34980020) remove exemption for appdomain + -coredomain + -data_between_core_and_vendor_violators + -vendor_init + } { + core_data_file_type + -system_data_file # default label for files on /data. Covered below... + -vendor_data_file + -zoneinfo_data_file + userdebug_or_eng(`-exagear_debug_file') + }:dir *; + neverallow { + vendor_init + -data_between_core_and_vendor_violators + } { + core_data_file_type + -unencrypted_data_file + -system_data_file + -vendor_data_file + -zoneinfo_data_file + userdebug_or_eng(`-exagear_debug_file') + }:dir *; + # vendor init needs to be able to read unencrypted_data_file to create directories with FBE. + # The vendor init binary lives on the system partition so there is not a concern with stability. + neverallow vendor_init unencrypted_data_file:dir ~search; +') +full_treble_only(` + # vendor domains may only access dirs in /data/vendor, never core_data_file_types + neverallow { + domain + -appdomain # TODO(b/34980020) remove exemption for appdomain + -coredomain + -data_between_core_and_vendor_violators # TODO(b/34980020) Remove once all violators have been cleaned up + } { + system_data_file # default label for files on /data. Covered below + }:dir ~{ getattr search }; +') + +full_treble_only(` + # coredomains may not access dirs in /data/vendor. + neverallow { + coredomain + -data_between_core_and_vendor_violators # TODO(b/34980020) Remove once all violators have been cleaned up + -init + -vold # vold creates per-user storage for both system and vendor + -vold_prepare_subdirs + } { + vendor_data_file # default label for files on /data. Covered below + }:dir ~{ getattr search }; +') + +full_treble_only(` + # coredomains may not access dirs in /data/vendor. + neverallow { + coredomain + -data_between_core_and_vendor_violators # TODO(b/34980020) Remove once all violators have been cleaned up + -init + } { + vendor_data_file # default label for files on /data/vendor{,_ce,_de}. + }:file_class_set ~{ append getattr ioctl read write }; +') + +# On TREBLE devices, a limited set of files in /vendor are accessible to +# only a few whitelisted coredomains to keep system/vendor separation. +full_treble_only(` + # Limit access to /vendor/app + neverallow { + coredomain + -appdomain + -dex2oat + -idmap + -init + -installd + userdebug_or_eng(`-perfprofd') + -postinstall_dexopt + -system_server + } vendor_app_file:dir { open read getattr search }; +') + +full_treble_only(` + neverallow { + coredomain + -appdomain + -dex2oat + -idmap + -init + -installd + userdebug_or_eng(`-perfprofd') + -postinstall_dexopt + -system_server + } vendor_app_file:file r_file_perms; +') + +full_treble_only(` + # Limit access to /vendor/overlay + neverallow { + coredomain + -appdomain + -idmap + -init + -installd + -system_server + -webview_zygote + -zygote + } vendor_overlay_file:dir { getattr open read search }; +') + +full_treble_only(` + neverallow { + coredomain + -appdomain + -idmap + -init + -installd + -system_server + -webview_zygote + -zygote + } vendor_overlay_file:file r_file_perms; +') + +full_treble_only(` + # Non-vendor domains are not allowed to file execute shell + # from vendor + neverallow { + coredomain + -init + -shell + } vendor_shell_exec:file { execute execute_no_trans }; +') + +full_treble_only(` + # Do not allow vendor components to execute files from system + # except for the ones whitelist here. + neverallow { + domain + -coredomain + -appdomain + -vendor_executes_system_violators + -vendor_init + } { + exec_type + -vendor_file_type + -crash_dump_exec + -netutils_wrapper_exec + }:file { entrypoint execute execute_no_trans }; +') + +full_treble_only(` + # Do not allow system components to execute files from vendor + # except for the ones whitelisted here. + neverallow { + coredomain + -init + -shell + -system_executes_vendor_violators + } { + vendor_file_type + -same_process_hal_file + -vndk_sp_file + -vendor_app_file + }:file execute; +') + +full_treble_only(` + neverallow { + coredomain + -shell + -system_executes_vendor_violators + } vendor_file_type:file execute_no_trans; +') + +# Only authorized processes should be writing to files in /data/dalvik-cache +neverallow { + domain + -init # TODO: limit init to relabelfrom for files + -zygote + -installd + -postinstall_dexopt + -cppreopts + -dex2oat + -otapreopt_slot +} dalvikcache_data_file:file no_w_file_perms; + +neverallow { + domain + -init + -installd + -postinstall_dexopt + -cppreopts + -dex2oat + -zygote + -otapreopt_slot +} dalvikcache_data_file:dir no_w_dir_perms; + +# Only system_server should be able to send commands via the zygote socket +neverallow { domain -zygote -system_server } zygote:unix_stream_socket connectto; +neverallow { domain -system_server } zygote_socket:sock_file write; + +neverallow { domain -system_server -webview_zygote } webview_zygote:unix_stream_socket connectto; +neverallow { domain -system_server } webview_zygote:sock_file write; + +neverallow { + domain + -tombstoned + -crash_dump + -dumpstate + -incidentd + -system_server + + # Processes that can't exec crash_dump + -mediacodec + -mediaextractor +} tombstoned_crash_socket:unix_stream_socket connectto; + +# Never allow anyone except dumpstate, incidentd, or the system server to connect or write to +# the tombstoned intercept socket. +neverallow { domain -dumpstate -incidentd -system_server } tombstoned_intercept_socket:sock_file write; +neverallow { domain -dumpstate -incidentd -system_server } tombstoned_intercept_socket:unix_stream_socket connectto; + +# Android does not support System V IPCs. +# +# The reason for this is due to the fact that, by design, they lead to global +# kernel resource leakage. +# +# For example, there is no way to automatically release a SysV semaphore +# allocated in the kernel when: +# +# - a buggy or malicious process exits +# - a non-buggy and non-malicious process crashes or is explicitly killed. +# +# Killing processes automatically to make room for new ones is an +# important part of Android's application lifecycle implementation. This means +# that, even assuming only non-buggy and non-malicious code, it is very likely +# that over time, the kernel global tables used to implement SysV IPCs will fill +# up. +neverallow * *:{ shm sem msg msgq } *; + +# Do not mount on top of symlinks, fifos, or sockets. +# Feature parity with Chromium LSM. +neverallow * { file_type fs_type dev_type }:{ lnk_file fifo_file sock_file } mounton; + +# Nobody should be able to execute su on user builds. +# On userdebug/eng builds, only dumpstate, shell, and +# su itself execute su. +neverallow { domain userdebug_or_eng(`-dumpstate -shell -su') } su_exec:file no_x_file_perms; + +# Do not allow the introduction of new execmod rules. Text relocations +# and modification of executable pages are unsafe. +# The only exceptions are for NDK text relocations associated with +# https://code.google.com/p/android/issues/detail?id=23203 +# which, long term, need to go away. +neverallow * { + file_type + -apk_data_file + -app_data_file + -asec_public_file +}:file execmod; + +# Do not allow making the stack or heap executable. +# We would also like to minimize execmem but it seems to be +# required by some device-specific service domains. +neverallow * self:process { execstack execheap }; + +# prohibit non-zygote spawned processes from using shared libraries +# with text relocations. b/20013628 . +neverallow { domain -untrusted_app_all } file_type:file execmod; + +neverallow { domain -init } proc:{ file dir } mounton; + +# Ensure that all types assigned to processes are included +# in the domain attribute, so that all allow and neverallow rules +# written on domain are applied to all processes. +# This is achieved by ensuring that it is impossible to transition +# from a domain to a non-domain type and vice versa. +# TODO - rework this: neverallow domain ~domain:process { transition dyntransition }; +neverallow ~domain domain:process { transition dyntransition }; + +# +# Only system_app and system_server should be creating or writing +# their files. The proper way to share files is to setup +# type transitions to a more specific type or assigning a type +# to its parent directory via a file_contexts entry. +# Example type transition: +# mydomain.te:file_type_auto_trans(mydomain, system_data_file, new_file_type) +# +neverallow { + domain + -system_server + -system_app + -init + -installd # for relabelfrom and unlink, check for this in explicit neverallow + -vold_prepare_subdirs # For unlink + with_asan(`-asan_extract') +} system_data_file:file no_w_file_perms; +# do not grant anything greater than r_file_perms and relabelfrom unlink +# to installd +neverallow installd system_data_file:file ~{ r_file_perms relabelfrom unlink }; + +# respect system_app sandboxes +neverallow { + domain + -appdomain # finer-grained rules for appdomain are listed below + -system_server #populate com.android.providers.settings/databases/settings.db. + -installd # creation of app sandbox + -traced_probes # resolve inodes for i/o tracing. + # only needs open and read, the rest is neverallow in + # traced_probes.te. +} system_app_data_file:dir_file_class_set { create unlink open }; +neverallow { + isolated_app + untrusted_app_all # finer-grained rules for appdomain are listed below + ephemeral_app + priv_app +} system_app_data_file:dir_file_class_set { create unlink open }; + + +# Services should respect app sandboxes +neverallow { + domain + -appdomain + -installd # creation of sandbox +} app_data_file:dir_file_class_set { create unlink }; + +# +# Only these domains should transition to shell domain. This domain is +# permissible for the "shell user". If you need a process to exec a shell +# script with differing privilege, define a domain and set up a transition. +# +neverallow { + domain + -adbd + -init + -runas + -zygote +} shell:process { transition dyntransition }; + +# Only domains spawned from zygote and runas may have the appdomain attribute. +neverallow { domain -runas -webview_zygote -zygote } { + appdomain -shell userdebug_or_eng(`-su') +}:process { transition dyntransition }; + +# Minimize read access to shell- or app-writable symlinks. +# This is to prevent malicious symlink attacks. +neverallow { + domain + -appdomain + -installd + -uncrypt # TODO: see if we can remove +} app_data_file:lnk_file read; + +neverallow { + domain + -shell + userdebug_or_eng(`-uncrypt') + -installd +} shell_data_file:lnk_file read; + +# In addition to the symlink reading restrictions above, restrict +# write access to shell owned directories. The /data/local/tmp +# directory is untrustworthy, and non-whitelisted domains should +# not be trusting any content in those directories. +neverallow { + domain + -adbd + -dumpstate + -installd + -init + -shell + -vold +} shell_data_file:dir no_w_dir_perms; + +neverallow { + domain + -adbd + -appdomain + -dumpstate + -init + -installd + -system_server # why? + userdebug_or_eng(`-uncrypt') +} shell_data_file:dir { open search }; + +# Same as above for /data/local/tmp files. We allow shell files +# to be passed around by file descriptor, but not directly opened. +neverallow { + domain + -adbd + -appdomain + -dumpstate + -installd + userdebug_or_eng(`-uncrypt') +} shell_data_file:file open; + +# servicemanager and vndservicemanager are the only processes which handle the +# service_manager list request +neverallow * ~{ + servicemanager + vndservicemanager + }:service_manager list; + +# hwservicemanager is the only process which handles hw list requests +neverallow * ~{ + hwservicemanager + }:hwservice_manager list; + +# only service_manager_types can be added to service_manager +# TODO - rework this: neverallow * ~service_manager_type:service_manager { add find }; + +# Prevent assigning non property types to properties +# TODO - rework this: neverallow * ~property_type:property_service set; + +# Domain types should never be assigned to any files other +# than the /proc/pid files associated with a process. The +# executable file used to enter a domain should be labeled +# with its own _exec type, not with the domain type. +# Conventionally, this looks something like: +# $ cat mydaemon.te +# type mydaemon, domain; +# type mydaemon_exec, exec_type, file_type; +# init_daemon_domain(mydaemon) +# $ grep mydaemon file_contexts +# /system/bin/mydaemon -- u:object_r:mydaemon_exec:s0 +neverallow * domain:file { execute execute_no_trans entrypoint }; + +# Do not allow access to the generic debugfs label. This is too broad. +# Instead, if access to part of debugfs is desired, it should have a +# more specific label. +# TODO: fix system_server and dumpstate +neverallow { domain -init -vendor_init -system_server -dumpstate } debugfs:file no_rw_file_perms; + +# Profiles contain untrusted data and profman parses that. We should only run +# in from installd forked processes. +neverallow { + domain + -installd + -profman +} profman_exec:file no_x_file_perms; + +# Enforce restrictions on kernel module origin. +# Do not allow kernel module loading except from system, +# vendor, and boot partitions. +neverallow * ~{ system_file vendor_file rootfs }:system module_load; + +# Only allow filesystem caps to be set at build time. Runtime changes +# to filesystem capabilities are not permitted. +neverallow * self:global_capability_class_set setfcap; + +# Enforce AT_SECURE for executing crash_dump. +neverallow domain crash_dump:process noatsecure; + +# Do not permit non-core domains to register HwBinder services which are +# guaranteed to be provided by core domains only. +neverallow ~coredomain coredomain_hwservice:hwservice_manager add; + +# Do not permit the registeration of HwBinder services which are guaranteed to +# be passthrough only (i.e., run in the process of their clients instead of a +# separate server process). +neverallow * same_process_hwservice:hwservice_manager add; + +# On TREBLE devices, most coredomains should not access vendor_files. +# TODO(b/71553434): Remove exceptions here. +full_treble_only(` + neverallow { + coredomain + -appdomain + -bootanim + -crash_dump + -init + -kernel + -perfprofd + -ueventd + } vendor_file:file { no_w_file_perms no_x_file_perms open }; +') + +# Minimize dac_override and dac_read_search. +# Instead of granting them it is usually better to add the domain to +# a Unix group or change the permissions of a file. +neverallow { + domain + -dnsmasq + -dumpstate + -init + -installd + -install_recovery + -lmkd + -netd + -perfprofd + -postinstall_dexopt + -recovery + -sdcardd + -tee + -ueventd + -uncrypt + -vendor_init + -vold + -vold_prepare_subdirs + -zygote +} self:capability dac_override; +neverallow { domain -traced_probes } self:capability dac_read_search; + +# If an already existing file is opened with O_CREAT, the kernel might generate +# a false report of a create denial. Silence these denials and make sure that +# inappropriate permissions are not granted. + +# These filesystems don't allow files or directories to be created, so the permission +# to do so should never be granted. +neverallow domain { + proc_type + sysfs_type +}:dir { add_name create link remove_name rename reparent rmdir write }; + +# cgroupfs directories can be created, but not files within them. +neverallow domain cgroup:file create; + +dontaudit domain proc_type:dir write; +dontaudit domain sysfs_type:dir write; +dontaudit domain cgroup:file create; + +# These are only needed in permissive mode - in enforcing mode the +# directory write check fails and so these are never attempted. +userdebug_or_eng(` + dontaudit domain proc_type:dir add_name; + dontaudit domain sysfs_type:dir add_name; + dontaudit domain proc_type:file create; + dontaudit domain sysfs_type:file create; +') + +# Platform must not have access to /mnt/vendor. +neverallow { + coredomain + -init +} mnt_vendor_file:dir *; diff --git a/aosp/system/sepolicy/public/file.te b/aosp/system/sepolicy/public/file.te new file mode 100644 index 000000000..13a34b409 --- /dev/null +++ b/aosp/system/sepolicy/public/file.te @@ -0,0 +1,419 @@ +# Filesystem types +type labeledfs, fs_type; +type pipefs, fs_type; +type sockfs, fs_type; +type rootfs, fs_type; +type proc, fs_type, proc_type; +# Security-sensitive proc nodes that should not be writable to most. +type proc_security, fs_type, proc_type; +type proc_drop_caches, fs_type, proc_type; +type proc_overcommit_memory, fs_type, proc_type; +type proc_min_free_order_shift, fs_type, proc_type; +# proc, sysfs, or other nodes that permit configuration of kernel usermodehelpers. +type usermodehelper, fs_type, proc_type; +type sysfs_usermodehelper, fs_type, sysfs_type; +type qtaguid_proc, fs_type, mlstrustedobject, proc_type; +type proc_qtaguid_stat, fs_type, mlstrustedobject, proc_type; +type proc_bluetooth_writable, fs_type, proc_type; +type proc_abi, fs_type, proc_type; +type proc_asound, fs_type, proc_type; +type proc_buddyinfo, fs_type, proc_type; +type proc_cmdline, fs_type, proc_type; +type proc_cpuinfo, fs_type, proc_type; +type proc_dirty, fs_type, proc_type; +type proc_diskstats, fs_type, proc_type; +type proc_extra_free_kbytes, fs_type, proc_type; +type proc_filesystems, fs_type, proc_type; +type proc_hostname, fs_type, proc_type; +type proc_hung_task, fs_type, proc_type; +type proc_interrupts, fs_type, proc_type; +type proc_iomem, fs_type, proc_type; +type proc_kmsg, fs_type, proc_type; +type proc_loadavg, fs_type, proc_type; +type proc_max_map_count, fs_type, proc_type; +type proc_meminfo, fs_type, proc_type; +type proc_misc, fs_type, proc_type; +type proc_modules, fs_type, proc_type; +type proc_mounts, fs_type, proc_type; +type proc_net, fs_type, proc_type; +type proc_net_route, fs_type, proc_type; +type proc_page_cluster, fs_type, proc_type; +type proc_pagetypeinfo, fs_type, proc_type; +type proc_panic, fs_type, proc_type; +type proc_perf, fs_type, proc_type; +type proc_pid_max, fs_type, proc_type; +type proc_pipe_conf, fs_type, proc_type; +type proc_random, fs_type, proc_type; +type proc_sched, fs_type, proc_type; +type proc_stat, fs_type, proc_type; +type proc_swaps, fs_type, proc_type; +type proc_sysrq, fs_type, proc_type; +type proc_timer, fs_type, proc_type; +type proc_tty_drivers, fs_type, proc_type; +type proc_uid_cputime_showstat, fs_type, proc_type; +type proc_uid_cputime_removeuid, fs_type, proc_type; +type proc_uid_io_stats, fs_type, proc_type; +type proc_uid_procstat_set, fs_type, proc_type; +type proc_uid_time_in_state, fs_type, proc_type; +type proc_uid_concurrent_active_time, fs_type, proc_type; +type proc_uid_concurrent_policy_time, fs_type, proc_type; +type proc_uid_cpupower, fs_type, proc_type; +type proc_uptime, fs_type, proc_type; +type proc_version, fs_type, proc_type; +type proc_vmallocinfo, fs_type, proc_type; +type proc_vmstat, fs_type, proc_type; +type proc_zoneinfo, fs_type, proc_type; +type selinuxfs, fs_type, mlstrustedobject; +type cgroup, fs_type, mlstrustedobject; +type cgroup_bpf, fs_type; +type sysfs, fs_type, sysfs_type, mlstrustedobject; +type sysfs_android_usb, fs_type, sysfs_type; +type sysfs_uio, sysfs_type, fs_type; +type sysfs_batteryinfo, fs_type, sysfs_type; +type sysfs_bluetooth_writable, fs_type, sysfs_type, mlstrustedobject; +type sysfs_block, fs_type, sysfs_type; +type sysfs_bpd_virtio_pci, fs_type, sysfs_type; +type sysfs_b_virtio, fs_type, sysfs_type; +type sysfs_cn_wlan0, fs_type, sysfs_type; +type sysfs_dm, fs_type, sysfs_type; +type sysfs_dt_firmware_android, fs_type, sysfs_type; +type sysfs_ipv4, fs_type, sysfs_type; +type sysfs_kernel_notes, fs_type, sysfs_type, mlstrustedobject; +type sysfs_leds, fs_type, sysfs_type; +type sysfs_hwrandom, fs_type, sysfs_type; +type sysfs_nfc_power_writable, fs_type, sysfs_type, mlstrustedobject; +type sysfs_wake_lock, fs_type, sysfs_type; +type sysfs_m_virtio_pci, fs_type, sysfs_type; +type sysfs_mac_address, fs_type, sysfs_type; +type sysfs_net, fs_type, sysfs_type; +type sysfs_power, fs_type, sysfs_type; +type sysfs_rtc, fs_type, sysfs_type; +type sysfs_switch, fs_type, sysfs_type; +type sysfs_usb, fs_type, sysfs_type; +type sysfs_wakeup_reasons, fs_type, sysfs_type; +type sysfs_fs_ext4_features, sysfs_type, fs_type; +type fs_bpf, fs_type; +type configfs, fs_type; +# /sys/devices/system/cpu +type sysfs_devices_system_cpu, fs_type, sysfs_type; +# /sys/module/lowmemorykiller +type sysfs_lowmemorykiller, fs_type, sysfs_type; +# /sys/module/wlan/parameters/fwpath +type sysfs_wlan_fwpath, fs_type, sysfs_type; +type sysfs_vibrator, fs_type, sysfs_type; + +type sysfs_thermal, sysfs_type, fs_type; + +type sysfs_zram, fs_type, sysfs_type; +type sysfs_zram_uevent, fs_type, sysfs_type; +type inotify, fs_type, mlstrustedobject; +type devpts, fs_type, mlstrustedobject; +type tmpfs, fs_type; +type shm, fs_type; +type mqueue, fs_type; +type fuse, sdcard_type, fs_type, mlstrustedobject; +type sdcardfs, sdcard_type, fs_type, mlstrustedobject; +type vfat, sdcard_type, fs_type, mlstrustedobject; +type exfat, sdcard_type, fs_type, mlstrustedobject; +type debugfs, fs_type, debugfs_type; +type debugfs_mmc, fs_type, debugfs_type; +type debugfs_trace_marker, fs_type, debugfs_type, mlstrustedobject; +type debugfs_tracing, fs_type, debugfs_type, mlstrustedobject; +type debugfs_tracing_debug, fs_type, debugfs_type, mlstrustedobject; +type debugfs_tracing_instances, fs_type, debugfs_type; +type debugfs_wakeup_sources, fs_type, debugfs_type; +type debugfs_wifi_tracing, fs_type, debugfs_type; + +type pstorefs, fs_type; +type functionfs, fs_type, mlstrustedobject; +type oemfs, fs_type, contextmount_type; +type usbfs, fs_type; +type binfmt_miscfs, fs_type; +type app_fusefs, fs_type, contextmount_type; + +# File types +type unlabeled, file_type; + +# Default type for anything under /system. +type system_file, file_type; + +# Default type for directories search for +# HAL implementations +type vendor_hal_file, vendor_file_type, file_type; +# Default type for under /vendor or /system/vendor +type vendor_file, vendor_file_type, file_type; +# Default type for everything in /vendor/app +type vendor_app_file, vendor_file_type, file_type; +# Default type for everything under /vendor/etc/ +type vendor_configs_file, vendor_file_type, file_type; +# Default type for all *same process* HALs. +# e.g. libEGL_xxx.so, android.hardware.graphics.mapper@2.0-impl.so +type same_process_hal_file, vendor_file_type, file_type; +# Default type for vndk-sp libs. /vendor/lib/vndk-sp +type vndk_sp_file, vendor_file_type, file_type; +# Default type for everything in /vendor/framework +type vendor_framework_file, vendor_file_type, file_type; +# Default type for everything in /vendor/overlay +type vendor_overlay_file, vendor_file_type, file_type; + +# /metadata partition itself +type metadata_file, file_type; +# Vold files within /metadata +type vold_metadata_file, file_type; + +# Speedup access for trusted applications to the runtime event tags +type runtime_event_log_tags_file, file_type; +# Type for /system/bin/logcat. +type logcat_exec, exec_type, file_type; +# /cores for coredumps on userdebug / eng builds +type coredump_file, file_type; +# Default type for anything under /data. +type system_data_file, file_type, data_file_type, core_data_file_type; +# Default type for anything under /data/vendor{_ce,_de}. +type vendor_data_file, file_type, data_file_type; +# Unencrypted data +type unencrypted_data_file, file_type, data_file_type, core_data_file_type; +# /data/.layout_version or other installd-created files that +# are created in a system_data_file directory. +type install_data_file, file_type, data_file_type, core_data_file_type; +# /data/drm - DRM plugin data +type drm_data_file, file_type, data_file_type, core_data_file_type; +# /data/adb - adb debugging files +type adb_data_file, file_type, data_file_type, core_data_file_type; +# /data/anr - ANR traces +type anr_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/tombstones - core dumps +type tombstone_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/vendor/tombstones/wifi - vendor wifi dumps +type tombstone_wifi_data_file, file_type, data_file_type; +# /data/app - user-installed apps +type apk_data_file, file_type, data_file_type, core_data_file_type; +type apk_tmp_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/app-private - forward-locked apps +type apk_private_data_file, file_type, data_file_type, core_data_file_type; +type apk_private_tmp_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/dalvik-cache +type dalvikcache_data_file, file_type, data_file_type, core_data_file_type; +# /data/ota +type ota_data_file, file_type, data_file_type, core_data_file_type; +# /data/ota_package +type ota_package_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/misc/profiles +type user_profile_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/misc/profman +type profman_dump_data_file, file_type, data_file_type, core_data_file_type; +# /data/resource-cache +type resourcecache_data_file, file_type, data_file_type, core_data_file_type; +# /data/local - writable by shell +type shell_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/property +type property_data_file, file_type, data_file_type, core_data_file_type; +# /data/bootchart +type bootchart_data_file, file_type, data_file_type, core_data_file_type; +# /data/system/heapdump +type heapdump_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/nativetest +type nativetest_data_file, file_type, data_file_type, core_data_file_type; +# /data/system_de/0/ringtones +type ringtone_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# /data/preloads +type preloads_data_file, file_type, data_file_type, core_data_file_type; +# /data/preloads/media +type preloads_media_file, file_type, data_file_type, core_data_file_type; +# /data/misc/dhcp and /data/misc/dhcp-6.8.2 +type dhcp_data_file, file_type, data_file_type, core_data_file_type; + +# Mount locations managed by vold +type mnt_media_rw_file, file_type; +type mnt_user_file, file_type; +type mnt_expand_file, file_type; +type storage_file, file_type; + +# Label for storage dirs which are just mount stubs +type mnt_media_rw_stub_file, file_type; +type storage_stub_file, file_type; + +# Mount location for read-write vendor partitions. +type mnt_vendor_file, file_type; + +# /postinstall: Mount point used by update_engine to run postinstall. +type postinstall_mnt_dir, file_type; +# Files inside the /postinstall mountpoint are all labeled as postinstall_file. +type postinstall_file, file_type; + +# /data/misc subdirectories +type adb_keys_file, file_type, data_file_type, core_data_file_type; +type audio_data_file, file_type, data_file_type, core_data_file_type; +type audioserver_data_file, file_type, data_file_type, core_data_file_type; +type bluetooth_data_file, file_type, data_file_type, core_data_file_type; +type bluetooth_logs_data_file, file_type, data_file_type, core_data_file_type; +type bootstat_data_file, file_type, data_file_type, core_data_file_type; +type boottrace_data_file, file_type, data_file_type, core_data_file_type; +type camera_data_file, file_type, data_file_type, core_data_file_type; +type gatekeeper_data_file, file_type, data_file_type, core_data_file_type; +type incident_data_file, file_type, data_file_type, core_data_file_type; +type keychain_data_file, file_type, data_file_type, core_data_file_type; +type keystore_data_file, file_type, data_file_type, core_data_file_type; +type media_data_file, file_type, data_file_type, core_data_file_type; +type media_rw_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type misc_user_data_file, file_type, data_file_type, core_data_file_type; +type net_data_file, file_type, data_file_type, core_data_file_type; +type network_watchlist_data_file, file_type, data_file_type, core_data_file_type; +type nfc_data_file, file_type, data_file_type, core_data_file_type; +type radio_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type recovery_data_file, file_type, data_file_type, core_data_file_type; +type shared_relro_file, file_type, data_file_type, core_data_file_type; +type systemkeys_data_file, file_type, data_file_type, core_data_file_type; +type textclassifier_data_file, file_type, data_file_type, core_data_file_type; +type trace_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type vpn_data_file, file_type, data_file_type, core_data_file_type; +type wifi_data_file, file_type, data_file_type, core_data_file_type; +type zoneinfo_data_file, file_type, data_file_type, core_data_file_type; +type vold_data_file, file_type, data_file_type, core_data_file_type; +type perfprofd_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +type tee_data_file, file_type, data_file_type; +type update_engine_data_file, file_type, data_file_type, core_data_file_type; +type update_engine_log_data_file, file_type, data_file_type, core_data_file_type; +# /data/misc/trace for method traces on userdebug / eng builds +type method_trace_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; + +# /data/data subdirectories - app sandboxes +type app_data_file, file_type, data_file_type, core_data_file_type; +# /data/data subdirectory for system UID apps. +type system_app_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Compatibility with type name used in Android 4.3 and 4.4. +# Default type for anything under /cache +type cache_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Type for /cache/backup_stage/* (fd interchange with apps) +type cache_backup_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# type for anything under /cache/backup (local transport storage) +type cache_private_backup_file, file_type, data_file_type, core_data_file_type; +# Type for anything under /cache/recovery +type cache_recovery_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Default type for anything under /efs +type efs_file, file_type; +# Type for wallpaper file. +type wallpaper_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Type for shortcut manager icon file. +type shortcut_manager_icons, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Type for user icon file. +type icon_file, file_type, data_file_type, core_data_file_type; +# /mnt/asec +type asec_apk_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# Elements of asec files (/mnt/asec) that are world readable +type asec_public_file, file_type, data_file_type, core_data_file_type; +# /data/app-asec +type asec_image_file, file_type, data_file_type, core_data_file_type; +# /data/backup and /data/secure/backup +type backup_data_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; +# All devices have bluetooth efs files. But they +# vary per device, so this type is used in per +# device policy +type bluetooth_efs_file, file_type; +# Type for fingerprint template file +type fingerprintd_data_file, file_type, data_file_type, core_data_file_type; +# Type for _new_ fingerprint template file +type fingerprint_vendor_data_file, file_type, data_file_type; +# Type for appfuse file. +type app_fuse_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; + +# Socket types +type adbd_socket, file_type, coredomain_socket; +type bluetooth_socket, file_type, data_file_type, core_data_file_type, coredomain_socket; +type dnsproxyd_socket, file_type, coredomain_socket, mlstrustedobject; +type dumpstate_socket, file_type, coredomain_socket; +type fwmarkd_socket, file_type, coredomain_socket, mlstrustedobject; +type lmkd_socket, file_type, coredomain_socket; +type logd_socket, file_type, coredomain_socket, mlstrustedobject; +type logdr_socket, file_type, coredomain_socket, mlstrustedobject; +type logdw_socket, file_type, coredomain_socket, mlstrustedobject; +type mdns_socket, file_type, coredomain_socket; +type mdnsd_socket, file_type, coredomain_socket, mlstrustedobject; +type misc_logd_file, coredomain_socket, file_type, data_file_type, core_data_file_type; +type mtpd_socket, file_type, coredomain_socket; +type netd_socket, file_type, coredomain_socket; +type property_socket, file_type, coredomain_socket, mlstrustedobject; +type racoon_socket, file_type, coredomain_socket; +type rild_socket, file_type; +type rild_debug_socket, file_type; +type system_wpa_socket, file_type, data_file_type, core_data_file_type, coredomain_socket; +type system_ndebug_socket, file_type, data_file_type, core_data_file_type, coredomain_socket, mlstrustedobject; +type tombstoned_crash_socket, file_type, coredomain_socket, mlstrustedobject; +type tombstoned_java_trace_socket, file_type, mlstrustedobject; +type tombstoned_intercept_socket, file_type, coredomain_socket; +type traced_producer_socket, file_type, coredomain_socket, mlstrustedobject; +type traced_consumer_socket, file_type, coredomain_socket; +type uncrypt_socket, file_type, coredomain_socket; +type wpa_socket, file_type, data_file_type, core_data_file_type; +type zygote_socket, file_type, coredomain_socket; +# UART (for GPS) control proc file +type gps_control, file_type; + +# PDX endpoint types +type pdx_display_dir, pdx_endpoint_dir_type, file_type; +type pdx_performance_dir, pdx_endpoint_dir_type, file_type; +type pdx_bufferhub_dir, pdx_endpoint_dir_type, file_type; + +pdx_service_socket_types(display_client, pdx_display_dir) +pdx_service_socket_types(display_manager, pdx_display_dir) +pdx_service_socket_types(display_screenshot, pdx_display_dir) +pdx_service_socket_types(display_vsync, pdx_display_dir) +pdx_service_socket_types(performance_client, pdx_performance_dir) +pdx_service_socket_types(bufferhub_client, pdx_bufferhub_dir) + +# file_contexts files +type file_contexts_file, file_type; + +# mac_permissions file +type mac_perms_file, file_type; + +# property_contexts file +type property_contexts_file, file_type; + +# seapp_contexts file +type seapp_contexts_file, file_type; + +# sepolicy files binary and others +type sepolicy_file, file_type; + +# service_contexts file +type service_contexts_file, file_type; + +# nonplat service_contexts file (only accessible on non full-treble devices) +type nonplat_service_contexts_file, file_type; + +# hwservice_contexts file +type hwservice_contexts_file, file_type; + +# vndservice_contexts file +type vndservice_contexts_file, file_type; + +# Allow files to be created in their appropriate filesystems. +allow fs_type self:filesystem associate; +allow cgroup tmpfs:filesystem associate; +allow cgroup_bpf tmpfs:filesystem associate; +allow sysfs_type sysfs:filesystem associate; +allow debugfs_type { debugfs debugfs_tracing debugfs_tracing_debug }:filesystem associate; +allow file_type labeledfs:filesystem associate; +allow file_type tmpfs:filesystem associate; +allow file_type rootfs:filesystem associate; +allow dev_type tmpfs:filesystem associate; +allow app_fuse_file app_fusefs:filesystem associate; +allow postinstall_file self:filesystem associate; + +# asanwrapper (run a sanitized app_process, to be used with wrap properties) +with_asan(`type asanwrapper_exec, exec_type, file_type;') + +# Deprecated in SDK version 28 +type audiohal_data_file, file_type, data_file_type, core_data_file_type; + +# It's a bug to assign the file_type attribute and fs_type attribute +# to any type. Do not allow it. +# +# For example, the following is a bug: +# type apk_data_file, file_type, data_file_type, fs_type; +# Should be: +# type apk_data_file, file_type, data_file_type; +neverallow fs_type file_type:filesystem associate; + +type exagear_debug_file, file_type, data_file_type, core_data_file_type, mlstrustedobject; diff --git a/aosp/system/sepolicy/public/te_macros b/aosp/system/sepolicy/public/te_macros new file mode 100644 index 000000000..241c9ea8a --- /dev/null +++ b/aosp/system/sepolicy/public/te_macros @@ -0,0 +1,597 @@ +##################################### +# domain_trans(olddomain, type, newdomain) +# Allow a transition from olddomain to newdomain +# upon executing a file labeled with type. +# This only allows the transition; it does not +# cause it to occur automatically - use domain_auto_trans +# if that is what you want. +# +define(`domain_trans', ` +# Old domain may exec the file and transition to the new domain. +allow $1 $2:file { getattr open read execute map }; +allow $1 $3:process transition; +# New domain is entered by executing the file. +allow $3 $2:file { entrypoint open read execute getattr map }; +# New domain can send SIGCHLD to its caller. +ifelse($1, `init', `', `allow $3 $1:process sigchld;') +# Enable AT_SECURE, i.e. libc secure mode. +dontaudit $1 $3:process noatsecure; +# XXX dontaudit candidate but requires further study. +allow $1 $3:process { siginh rlimitinh }; +') + +##################################### +# domain_auto_trans(olddomain, type, newdomain) +# Automatically transition from olddomain to newdomain +# upon executing a file labeled with type. +# +define(`domain_auto_trans', ` +# Allow the necessary permissions. +domain_trans($1,$2,$3) +# Make the transition occur by default. +type_transition $1 $2:process $3; +') + +##################################### +# file_type_trans(domain, dir_type, file_type) +# Allow domain to create a file labeled file_type in a +# directory labeled dir_type. +# This only allows the transition; it does not +# cause it to occur automatically - use file_type_auto_trans +# if that is what you want. +# +define(`file_type_trans', ` +# Allow the domain to add entries to the directory. +allow $1 $2:dir ra_dir_perms; +# Allow the domain to create the file. +allow $1 $3:notdevfile_class_set create_file_perms; +allow $1 $3:dir create_dir_perms; +') + +##################################### +# file_type_auto_trans(domain, dir_type, file_type) +# Automatically label new files with file_type when +# they are created by domain in directories labeled dir_type. +# +define(`file_type_auto_trans', ` +# Allow the necessary permissions. +file_type_trans($1, $2, $3) +# Make the transition occur by default. +type_transition $1 $2:dir $3; +type_transition $1 $2:notdevfile_class_set $3; +') + +##################################### +# r_dir_file(domain, type) +# Allow the specified domain to read directories, files +# and symbolic links of the specified type. +define(`r_dir_file', ` +allow $1 $2:dir r_dir_perms; +allow $1 $2:{ file lnk_file } r_file_perms; +') + +##################################### +# tmpfs_domain(domain) +# Define and allow access to a unique type for +# this domain when creating tmpfs / shmem / ashmem files. +define(`tmpfs_domain', ` +type $1_tmpfs, file_type; +type_transition $1 tmpfs:file $1_tmpfs; +allow $1 $1_tmpfs:file { read write getattr map open ioctl }; +allow $1 tmpfs:dir { getattr search }; +') + +# pdx macros for IPC. pdx is a high-level name which contains transport-specific +# rules from underlying transport (e.g. UDS-based implementation). + +##################################### +# pdx_service_attributes(service) +# Defines type attribute used to identify various service-related types. +define(`pdx_service_attributes', ` +attribute pdx_$1_endpoint_dir_type; +attribute pdx_$1_endpoint_socket_type; +attribute pdx_$1_channel_socket_type; +attribute pdx_$1_server_type; +') + +##################################### +# pdx_service_socket_types(service, endpoint_dir_t) +# Define types for endpoint and channel sockets. +define(`pdx_service_socket_types', ` +typeattribute $2 pdx_$1_endpoint_dir_type; +type pdx_$1_endpoint_socket, pdx_$1_endpoint_socket_type, pdx_endpoint_socket_type, file_type, coredomain_socket, mlstrustedobject, mlstrustedsubject; +type pdx_$1_channel_socket, pdx_$1_channel_socket_type, pdx_channel_socket_type, coredomain_socket; +userdebug_or_eng(` +dontaudit su pdx_$1_endpoint_socket:unix_stream_socket *; +dontaudit su pdx_$1_channel_socket:unix_stream_socket *; +') +') + +##################################### +# pdx_server(server_domain, service) +define(`pdx_server', ` +# Mark the server domain as a PDX server. +typeattribute $1 pdx_$2_server_type; +# Allow the init process to create the initial endpoint socket. +allow init pdx_$2_endpoint_socket_type:unix_stream_socket { create bind }; +# Allow the server domain to use the endpoint socket and accept connections on it. +# Not using macro like "rw_socket_perms_no_ioctl" because it provides more rights +# than we need (e.g. we don"t need "bind" or "connect"). +allow $1 pdx_$2_endpoint_socket_type:unix_stream_socket { read getattr write setattr lock append getopt setopt shutdown listen accept }; +# Allow the server domain to apply security context label to the channel socket pair (allow process to use setsockcreatecon_raw()). +allow $1 self:process setsockcreate; +# Allow the server domain to create a client channel socket. +allow $1 pdx_$2_channel_socket_type:unix_stream_socket create_stream_socket_perms; +# Prevent other processes from claiming to be a server for the same service. +neverallow {domain -$1} pdx_$2_endpoint_socket_type:unix_stream_socket { listen accept }; +') + +##################################### +# pdx_connect(client, service) +define(`pdx_connect', ` +# Allow client to open the service endpoint file. +allow $1 pdx_$2_endpoint_dir_type:dir r_dir_perms; +allow $1 pdx_$2_endpoint_socket_type:sock_file rw_file_perms; +# Allow the client to connect to endpoint socket. +allow $1 pdx_$2_endpoint_socket_type:unix_stream_socket { connectto read write shutdown }; +') + +##################################### +# pdx_use(client, service) +define(`pdx_use', ` +# Allow the client to use the PDX channel socket. +# Not using macro like "rw_socket_perms_no_ioctl" because it provides more rights +# than we need (e.g. we don"t need "bind" or "connect"). +allow $1 pdx_$2_channel_socket_type:unix_stream_socket { read getattr write setattr lock append getopt setopt shutdown }; +# Client needs to use an channel event fd from the server. +allow $1 pdx_$2_server_type:fd use; +# Servers may receive sync fences, gralloc buffers, etc, from clients. +# This could be tightened on a per-server basis, but keeping track of service +# clients is error prone. +allow pdx_$2_server_type $1:fd use; +') + +##################################### +# pdx_client(client, service) +define(`pdx_client', ` +pdx_connect($1, $2) +pdx_use($1, $2) +') + +##################################### +# init_daemon_domain(domain) +# Set up a transition from init to the daemon domain +# upon executing its binary. +define(`init_daemon_domain', ` +domain_auto_trans(init, $1_exec, $1) +tmpfs_domain($1) +') + +##################################### +# app_domain(domain) +# Allow a base set of permissions required for all apps. +define(`app_domain', ` +typeattribute $1 appdomain; +# Label ashmem objects with our own unique type. +tmpfs_domain($1) +# Map with PROT_EXEC. +allow $1 $1_tmpfs:file execute; +neverallow { $1 -shell } { domain -$1 }:file no_rw_file_perms; +neverallow { appdomain -shell -$1 } $1:file no_rw_file_perms; +') + +##################################### +# untrusted_app_domain(domain) +# Allow a base set of permissions required for all untrusted apps. +define(`untrusted_app_domain', ` +typeattribute $1 untrusted_app_all; +') + +##################################### +# net_domain(domain) +# Allow a base set of permissions required for network access. +define(`net_domain', ` +typeattribute $1 netdomain; +') + +##################################### +# bluetooth_domain(domain) +# Allow a base set of permissions required for bluetooth access. +define(`bluetooth_domain', ` +typeattribute $1 bluetoothdomain; +') + +##################################### +# hal_attribute(hal_name) +# Add an attribute for hal implementations along with necessary +# restrictions. +define(`hal_attribute', ` +attribute hal_$1; +expandattribute hal_$1 true; +attribute hal_$1_client; +expandattribute hal_$1_client true; +attribute hal_$1_server; +expandattribute hal_$1_server false; + +neverallow { hal_$1_server -halserverdomain } domain:process fork; +') + +##################################### +# hal_server_domain(domain, hal_type) +# Allow a base set of permissions required for a domain to offer a +# HAL implementation of the specified type over HwBinder. +# +# For example, default implementation of Foo HAL: +# type hal_foo_default, domain; +# hal_server_domain(hal_foo_default, hal_foo) +# +define(`hal_server_domain', ` +typeattribute $1 halserverdomain; +typeattribute $1 $2_server; +typeattribute $1 $2; +') + +##################################### +# hal_client_domain(domain, hal_type) +# Allow a base set of permissions required for a domain to be a +# client of a HAL of the specified type. +# +# For example, make some_domain a client of Foo HAL: +# hal_client_domain(some_domain, hal_foo) +# +define(`hal_client_domain', ` +typeattribute $1 halclientdomain; +typeattribute $1 $2_client; + +# TODO(b/34170079): Make the inclusion of the rules below conditional also on +# non-Treble devices. For now, on non-Treble device, always grant clients of a +# HAL sufficient access to run the HAL in passthrough mode (i.e., in-process). +not_full_treble(` +typeattribute $1 $2; +# Find passthrough HAL implementations +allow $2 system_file:dir r_dir_perms; +allow $2 vendor_file:dir r_dir_perms; +allow $2 vendor_file:file { read open getattr execute map }; +') +') + +##################################### +# passthrough_hal_client_domain(domain, hal_type) +# Allow a base set of permissions required for a domain to be a +# client of a passthrough HAL of the specified type. +# +# For example, make some_domain a client of passthrough Foo HAL: +# passthrough_hal_client_domain(some_domain, hal_foo) +# +define(`passthrough_hal_client_domain', ` +typeattribute $1 halclientdomain; +typeattribute $1 $2_client; +typeattribute $1 $2; +# Find passthrough HAL implementations +allow $2 system_file:dir r_dir_perms; +allow $2 vendor_file:dir r_dir_perms; +allow $2 vendor_file:file { read open getattr execute map }; +') + +##################################### +# unix_socket_connect(clientdomain, socket, serverdomain) +# Allow a local socket connection from clientdomain via +# socket to serverdomain. +# +# Note: If you see denial records that distill to the +# following allow rules: +# allow clientdomain property_socket:sock_file write; +# allow clientdomain init:unix_stream_socket connectto; +# allow clientdomain something_prop:property_service set; +# +# This sequence is indicative of attempting to set a property. +# use set_prop(sourcedomain, targetproperty) +# +define(`unix_socket_connect', ` +allow $1 $2_socket:sock_file write; +allow $1 $3:unix_stream_socket connectto; +') + +##################################### +# set_prop(sourcedomain, targetproperty) +# Allows source domain to set the +# targetproperty. +# +define(`set_prop', ` +unix_socket_connect($1, property, init) +allow $1 $2:property_service set; +get_prop($1, $2) +') + +##################################### +# get_prop(sourcedomain, targetproperty) +# Allows source domain to read the +# targetproperty. +# +define(`get_prop', ` +allow $1 $2:file r_file_perms; +') + +##################################### +# unix_socket_send(clientdomain, socket, serverdomain) +# Allow a local socket send from clientdomain via +# socket to serverdomain. +define(`unix_socket_send', ` +allow $1 $2_socket:sock_file write; +allow $1 $3:unix_dgram_socket sendto; +') + +##################################### +# binder_use(domain) +# Allow domain to use Binder IPC. +define(`binder_use', ` +# Call the servicemanager and transfer references to it. +allow $1 servicemanager:binder { call transfer }; +# servicemanager performs getpidcon on clients. +allow servicemanager $1:dir search; +allow servicemanager $1:file { read open }; +allow servicemanager $1:process getattr; +# rw access to /dev/binder and /dev/ashmem is presently granted to +# all domains in domain.te. +') + +##################################### +# hwbinder_use(domain) +# Allow domain to use HwBinder IPC. +define(`hwbinder_use', ` +# Call the hwservicemanager and transfer references to it. +allow $1 hwservicemanager:binder { call transfer }; +# Allow hwservicemanager to send out callbacks +allow hwservicemanager $1:binder { call transfer }; +# hwservicemanager performs getpidcon on clients. +allow hwservicemanager $1:dir search; +allow hwservicemanager $1:file { read open }; +allow hwservicemanager $1:process getattr; +# rw access to /dev/hwbinder and /dev/ashmem is presently granted to +# all domains in domain.te. +') + +##################################### +# vndbinder_use(domain) +# Allow domain to use Binder IPC. +define(`vndbinder_use', ` +# Talk to the vndbinder device node +allow $1 vndbinder_device:chr_file rw_file_perms; +# Call the vndservicemanager and transfer references to it. +allow $1 vndservicemanager:binder { call transfer }; +# vndservicemanager performs getpidcon on clients. +allow vndservicemanager $1:dir search; +allow vndservicemanager $1:file { read open }; +allow vndservicemanager $1:process getattr; +') + +##################################### +# binder_call(clientdomain, serverdomain) +# Allow clientdomain to perform binder IPC to serverdomain. +define(`binder_call', ` +# Call the server domain and optionally transfer references to it. +allow $1 $2:binder { call transfer }; +# Allow the serverdomain to transfer references to the client on the reply. +allow $2 $1:binder transfer; +# Receive and use open files from the server. +allow $1 $2:fd use; +') + +##################################### +# binder_service(domain) +# Mark a domain as being a Binder service domain. +# Used to allow binder IPC to the various system services. +define(`binder_service', ` +typeattribute $1 binderservicedomain; +') + +##################################### +# wakelock_use(domain) +# Allow domain to manage wake locks +define(`wakelock_use', ` +# Access /sys/power/wake_lock and /sys/power/wake_unlock +allow $1 sysfs_wake_lock:file rw_file_perms; +# Accessing these files requires CAP_BLOCK_SUSPEND +allow $1 self:global_capability2_class_set block_suspend; +') + +##################################### +# selinux_check_access(domain) +# Allow domain to check SELinux permissions via selinuxfs. +define(`selinux_check_access', ` +r_dir_file($1, selinuxfs) +allow $1 selinuxfs:file w_file_perms; +allow $1 kernel:security compute_av; +allow $1 self:netlink_selinux_socket { read write create getattr setattr lock relabelfrom relabelto append bind connect listen accept getopt setopt shutdown recvfrom sendto name_bind }; +') + +##################################### +# selinux_check_context(domain) +# Allow domain to check SELinux contexts via selinuxfs. +define(`selinux_check_context', ` +r_dir_file($1, selinuxfs) +allow $1 selinuxfs:file w_file_perms; +allow $1 kernel:security check_context; +') + +##################################### +# create_pty(domain) +# Allow domain to create and use a pty, isolated from any other domain ptys. +define(`create_pty', ` +# Each domain gets a unique devpts type. +type $1_devpts, fs_type; +# Label the pty with the unique type when created. +type_transition $1 devpts:chr_file $1_devpts; +# Allow use of the pty after creation. +allow $1 $1_devpts:chr_file { open getattr read write ioctl }; +allowxperm $1 $1_devpts:chr_file ioctl unpriv_tty_ioctls; +# TIOCSTI is only ever used for exploits. Block it. +# b/33073072, b/7530569 +# http://www.openwall.com/lists/oss-security/2016/09/26/14 +neverallowxperm * $1_devpts:chr_file ioctl TIOCSTI; +# Note: devpts:dir search and ptmx_device:chr_file rw_file_perms +# allowed to everyone via domain.te. +') + +##################################### +# Non system_app application set +# +define(`non_system_app_set', `{ appdomain -system_app }') + +##################################### +# Recovery only +# SELinux rules which apply only to recovery mode +# +define(`recovery_only', ifelse(target_recovery, `true', $1, )) + +##################################### +# Full TREBLE only +# SELinux rules which apply only to full TREBLE devices +# +define(`full_treble_only', ifelse(target_full_treble, `true', $1, +ifelse(target_full_treble, `cts', +# BEGIN_TREBLE_ONLY -- this marker is used by CTS -- do not modify +$1 +# END_TREBLE_ONLY -- this marker is used by CTS -- do not modify +, ))) + +##################################### +# Not full TREBLE +# SELinux rules which apply only to devices which are not full TREBLE devices +# +define(`not_full_treble', ifelse(target_full_treble, `true', , $1)) + +##################################### +# Compatible property only +# SELinux rules which apply only to devices with compatible property +# +define(`compatible_property_only', ifelse(target_compatible_property, `true', $1, +ifelse(target_compatible_property, `cts', +# BEGIN_COMPATIBLE_PROPERTY_ONLY -- this marker is used by CTS -- do not modify +$1 +# END_COMPATIBLE_PROPERTY_ONLY -- this marker is used by CTS -- do not modify +, ))) + +##################################### +# Not compatible property +# SELinux rules which apply only to devices without compatible property +# +define(`not_compatible_property', ifelse(target_compatible_property, `true', , $1)) + +##################################### +# Userdebug or eng builds +# SELinux rules which apply only to userdebug or eng builds +# +define(`userdebug_or_eng', ifelse(target_build_variant, `eng', $1, ifelse(target_build_variant, `userdebug', $1))) + +##################################### +# asan builds +# SELinux rules which apply only to asan builds +# +define(`with_asan', ifelse(target_with_asan, `true', userdebug_or_eng(`$1'), )) + +#################################### +# Fallback crash handling for processes that can't exec crash_dump (e.g. because of seccomp). +# +define(`crash_dump_fallback', ` +userdebug_or_eng(` + allow $1 su:fifo_file append; +') +allow $1 anr_data_file:file append; +allow $1 dumpstate:fd use; +allow $1 incidentd:fd use; +# TODO: Figure out why write is needed. +allow $1 dumpstate:fifo_file { append write }; +allow $1 incidentd:fifo_file { append write }; +allow $1 system_server:fifo_file { append write }; +allow $1 tombstoned:unix_stream_socket connectto; +allow $1 tombstoned:fd use; +allow $1 tombstoned_crash_socket:sock_file write; +allow $1 tombstone_data_file:file append; +') + +##################################### +# WITH_DEXPREOPT builds +# SELinux rules which apply only when pre-opting. +# +define(`with_dexpreopt', ifelse(target_with_dexpreopt, `true', $1)) + +##################################### +# write_logd(domain) +# Ability to write to android log +# daemon via sockets +define(`write_logd', ` +unix_socket_send($1, logdw, logd) +allow $1 pmsg_device:chr_file w_file_perms; +') + +##################################### +# read_logd(domain) +# Ability to run logcat and read from android +# log daemon via sockets +define(`read_logd', ` +allow $1 logcat_exec:file rx_file_perms; +unix_socket_connect($1, logdr, logd) +') + +##################################### +# read_runtime_log_tags(domain) +# ability to directly map the runtime event log tags +define(`read_runtime_log_tags', ` +allow $1 runtime_event_log_tags_file:file r_file_perms; +') + +##################################### +# control_logd(domain) +# Ability to control +# android log daemon via sockets +define(`control_logd', ` +# Group AID_LOG checked by filesystem & logd +# to permit control commands +unix_socket_connect($1, logd, logd) +') + +##################################### +# use_keystore(domain) +# Ability to use keystore. +# Keystore is requires the following permissions +# to call getpidcon. +define(`use_keystore', ` + allow keystore $1:dir search; + allow keystore $1:file { read open }; + allow keystore $1:process getattr; + allow $1 keystore_service:service_manager find; + binder_call($1, keystore) + binder_call(keystore, $1) +') + +########################################### +# use_drmservice(domain) +# Ability to use DrmService which requires +# DrmService to call getpidcon. +define(`use_drmservice', ` + allow drmserver $1:dir search; + allow drmserver $1:file { read open }; + allow drmserver $1:process getattr; +') + +########################################### +# add_service(domain, service) +# Ability for domain to add a service to service_manager +# and find it. It also creates a neverallow preventing +# others from adding it. +define(`add_service', ` + allow $1 $2:service_manager { add find }; + neverallow { domain -$1 } $2:service_manager add; +') + +########################################### +# add_hwservice(domain, service) +# Ability for domain to add a service to hwservice_manager +# and find it. It also creates a neverallow preventing +# others from adding it. +define(`add_hwservice', ` + allow $1 $2:hwservice_manager { add find }; + allow $1 hidl_base_hwservice:hwservice_manager add; + neverallow { domain -$1 } $2:hwservice_manager add; +') -- Gitee From 3c010e85d3c908901c877c01e3b14482f4a80707 Mon Sep 17 00:00:00 2001 From: yayaws_zk <584363327@qq.com> Date: Sat, 6 Sep 2025 12:34:45 +0800 Subject: [PATCH 2/3] open source init --- aosp/system/core/init/Android.bp | 11 +- aosp/system/core/init/Android.mk | 14 +- aosp/system/core/init/builtins.cpp | 1248 ++++++++++++++++++++ aosp/system/core/init/devices.cpp | 443 +++++++ aosp/system/core/init/init.cpp | 970 +++++++++++++++ aosp/system/core/init/init.h | 60 + aosp/system/core/init/log.cpp | 90 ++ aosp/system/core/init/property_service.cpp | 905 ++++++++++++++ aosp/system/core/init/selinux.cpp | 553 +++++++++ aosp/system/core/init/selinux.h | 42 + aosp/system/core/init/service.cpp | 1244 +++++++++++++++++++ aosp/system/core/init/subcontext.cpp | 381 ++++++ aosp/system/core/init/ueventd.cpp | 300 +++++ aosp/system/core/init/util.cpp | 446 +++++++ 14 files changed, 6701 insertions(+), 6 deletions(-) create mode 100644 aosp/system/core/init/builtins.cpp create mode 100644 aosp/system/core/init/devices.cpp create mode 100644 aosp/system/core/init/init.cpp create mode 100644 aosp/system/core/init/init.h create mode 100644 aosp/system/core/init/log.cpp create mode 100644 aosp/system/core/init/property_service.cpp create mode 100644 aosp/system/core/init/selinux.cpp create mode 100644 aosp/system/core/init/selinux.h create mode 100644 aosp/system/core/init/service.cpp create mode 100644 aosp/system/core/init/subcontext.cpp create mode 100644 aosp/system/core/init/ueventd.cpp create mode 100644 aosp/system/core/init/util.cpp diff --git a/aosp/system/core/init/Android.bp b/aosp/system/core/init/Android.bp index d86a45f45..bf3cca43f 100644 --- a/aosp/system/core/init/Android.bp +++ b/aosp/system/core/init/Android.bp @@ -26,12 +26,13 @@ cc_defaults { "-Wextra", "-Wno-unused-parameter", "-Werror", - "-DALLOW_LOCAL_PROP_OVERRIDE=0", + "-DALLOW_LOCAL_PROP_OVERRIDE=1", "-DALLOW_PERMISSIVE_SELINUX=0", "-DREBOOT_BOOTLOADER_ON_PANIC=0", "-DWORLD_WRITABLE_KMSG=0", "-DDUMP_ON_UMOUNT_FAILURE=0", "-DSHUTDOWN_ZERO_TIMEOUT=0", + "-DCPH_INIT", ], product_variables: { debuggable: { @@ -125,6 +126,7 @@ cc_library_static { "ueventd_parser.cpp", "util.cpp", "watchdogd.cpp", + "prepare_filesystem.cpp", ], whole_static_libs: ["libcap"], header_libs: ["bootimg_headers"], @@ -132,6 +134,13 @@ cc_library_static { type: "lite", export_proto_headers: true, }, + cflags: [ + "-Wall", + "-Werror", + "-Wno-unused-parameter", + "-Wno-unused-function", + ], + } /* diff --git a/aosp/system/core/init/Android.mk b/aosp/system/core/init/Android.mk index 92e46bd13..32f503420 100644 --- a/aosp/system/core/init/Android.mk +++ b/aosp/system/core/init/Android.mk @@ -13,7 +13,7 @@ init_options += \ -DDUMP_ON_UMOUNT_FAILURE=1 else init_options += \ - -DALLOW_LOCAL_PROP_OVERRIDE=0 \ + -DALLOW_LOCAL_PROP_OVERRIDE=1 \ -DALLOW_PERMISSIVE_SELINUX=0 \ -DREBOOT_BOOTLOADER_ON_PANIC=0 \ -DWORLD_WRITABLE_KMSG=0 \ @@ -36,6 +36,8 @@ init_cflags += \ -Wno-unused-parameter \ -Werror \ -std=gnu++1z \ + -Wno-unused-function \ + -DCPH_INIT # -- @@ -45,7 +47,6 @@ LOCAL_SRC_FILES := main.cpp LOCAL_MODULE:= init_orig -LOCAL_FORCE_STATIC_EXECUTABLE := true LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT) LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_UNSTRIPPED) @@ -61,7 +62,6 @@ LOCAL_STATIC_LIBRARIES := \ libext4_utils \ libcutils \ libbase \ - libc \ libseccomp_policy \ libselinux \ liblog \ @@ -78,6 +78,11 @@ LOCAL_STATIC_LIBRARIES := \ libpropertyinfoserializer \ libpropertyinfoparser \ +LOCAL_SHARED_LIBRARIES := \ + libbinder \ + libpowermanager \ + libutils + LOCAL_REQUIRED_MODULES := \ e2fsdroid \ mke2fs \ @@ -86,8 +91,7 @@ LOCAL_REQUIRED_MODULES := \ # Create symlinks. LOCAL_POST_INSTALL_CMD := $(hide) mkdir -p $(TARGET_ROOT_OUT)/sbin; \ - ln -sf ../init $(TARGET_ROOT_OUT)/sbin/ueventd; \ - ln -sf ../init $(TARGET_ROOT_OUT)/sbin/watchdogd + ln -sf /init $(TARGET_OUT)/bin/ueventd; LOCAL_SANITIZE := signed-integer-overflow include $(BUILD_EXECUTABLE) diff --git a/aosp/system/core/init/builtins.cpp b/aosp/system/core/init/builtins.cpp new file mode 100644 index 000000000..bb24dc9cf --- /dev/null +++ b/aosp/system/core/init/builtins.cpp @@ -0,0 +1,1248 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "builtins.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "action_manager.h" +#include "bootchart.h" +#include "init.h" +#include "parser.h" +#include "property_service.h" +#include "reboot.h" +#include "rlimit_parser.h" +#include "selinux.h" +#include "service.h" +#include "subcontext.h" +#include "util.h" + +using namespace std::literals::string_literals; + +using android::base::unique_fd; + +#define chmod DO_NOT_USE_CHMOD_USE_FCHMODAT_SYMLINK_NOFOLLOW + +namespace android { +namespace init { + +static constexpr std::chrono::nanoseconds kCommandRetryTimeout = 5s; + +static Result reboot_into_recovery(const std::vector& options) { + LOG(ERROR) << "Rebooting into recovery"; + std::string err; + if (!write_bootloader_message(options, &err)) { + return Error() << "Failed to set bootloader message: " << err; + } + property_set("sys.powerctl", "reboot,recovery"); + return Success(); +} + +template +static void ForEachServiceInClass(const std::string& classname, F function) { + for (const auto& service : ServiceList::GetInstance()) { + if (service->classnames().count(classname)) std::invoke(function, service); + } +} + +static Result do_class_start(const BuiltinArguments& args) { + // Starting a class does not start services which are explicitly disabled. + // They must be started individually. + for (const auto& service : ServiceList::GetInstance()) { + if (service->classnames().count(args[1])) { + if (auto result = service->StartIfNotDisabled(); !result) { + LOG(ERROR) << "Could not start service '" << service->name() + << "' as part of class '" << args[1] << "': " << result.error(); + } + } + } + return Success(); +} + +static Result do_class_stop(const BuiltinArguments& args) { + ForEachServiceInClass(args[1], &Service::Stop); + return Success(); +} + +static Result do_class_reset(const BuiltinArguments& args) { + ForEachServiceInClass(args[1], &Service::Reset); + return Success(); +} + +static Result do_class_restart(const BuiltinArguments& args) { + ForEachServiceInClass(args[1], &Service::Restart); + return Success(); +} + +static Result do_domainname(const BuiltinArguments& args) { + if (auto result = WriteFile("/proc/sys/kernel/domainname", args[1]); !result) { + return Error() << "Unable to write to /proc/sys/kernel/domainname: " << result.error(); + } + return Success(); +} + +static Result do_enable(const BuiltinArguments& args) { + Service* svc = ServiceList::GetInstance().FindService(args[1]); + if (!svc) return Error() << "Could not find service"; + + if (auto result = svc->Enable(); !result) { + return Error() << "Could not enable service: " << result.error(); + } + + return Success(); +} + +static Result do_exec(const BuiltinArguments& args) { + auto service = Service::MakeTemporaryOneshotService(args.args); + if (!service) { + return Error() << "Could not create exec service"; + } + if (auto result = service->ExecStart(); !result) { + return Error() << "Could not start exec service: " << result.error(); + } + + ServiceList::GetInstance().AddService(std::move(service)); + return Success(); +} + +static Result do_exec_background(const BuiltinArguments& args) { + auto service = Service::MakeTemporaryOneshotService(args.args); + if (!service) { + return Error() << "Could not create exec background service"; + } + if (auto result = service->Start(); !result) { + return Error() << "Could not start exec background service: " << result.error(); + } + + ServiceList::GetInstance().AddService(std::move(service)); + return Success(); +} + +static Result do_exec_start(const BuiltinArguments& args) { + Service* service = ServiceList::GetInstance().FindService(args[1]); + if (!service) { + return Error() << "Service not found"; + } + + if (auto result = service->ExecStart(); !result) { + return Error() << "Could not start exec service: " << result.error(); + } + + return Success(); +} + +static Result do_export(const BuiltinArguments& args) { + if (setenv(args[1].c_str(), args[2].c_str(), 1) == -1) { + return ErrnoError() << "setenv() failed"; + } + return Success(); +} + +static Result do_hostname(const BuiltinArguments& args) { + if (auto result = WriteFile("/proc/sys/kernel/hostname", args[1]); !result) { + return Error() << "Unable to write to /proc/sys/kernel/hostname: " << result.error(); + } + return Success(); +} + +static Result do_ifup(const BuiltinArguments& args) { + struct ifreq ifr; + + strlcpy(ifr.ifr_name, args[1].c_str(), IFNAMSIZ); + + unique_fd s(TEMP_FAILURE_RETRY(socket(AF_INET, SOCK_DGRAM, 0))); + if (s < 0) return ErrnoError() << "opening socket failed"; + + if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0) { + return ErrnoError() << "ioctl(..., SIOCGIFFLAGS, ...) failed"; + } + + ifr.ifr_flags |= IFF_UP; + + if (ioctl(s, SIOCSIFFLAGS, &ifr) < 0) { + return ErrnoError() << "ioctl(..., SIOCSIFFLAGS, ...) failed"; + } + + return Success(); +} + +static Result do_insmod(const BuiltinArguments& args) { + int flags = 0; + auto it = args.begin() + 1; + + if (!(*it).compare("-f")) { + flags = MODULE_INIT_IGNORE_VERMAGIC | MODULE_INIT_IGNORE_MODVERSIONS; + it++; + } + + std::string filename = *it++; + std::string options = android::base::Join(std::vector(it, args.end()), ' '); + + unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC))); + if (fd == -1) return ErrnoError() << "open(\"" << filename << "\") failed"; + + int rc = syscall(__NR_finit_module, fd.get(), options.c_str(), flags); + if (rc == -1) return ErrnoError() << "finit_module for \"" << filename << "\" failed"; + + return Success(); +} + +// mkdir [mode] [owner] [group] +static Result do_mkdir(const BuiltinArguments& args) { + mode_t mode = 0755; + if (args.size() >= 3) { + mode = std::strtoul(args[2].c_str(), 0, 8); + } + + if (!make_dir(args[1], mode)) { + /* chmod in case the directory already exists */ + if (errno == EEXIST) { + if (fchmodat(AT_FDCWD, args[1].c_str(), mode, AT_SYMLINK_NOFOLLOW) == -1) { + return ErrnoError() << "fchmodat() failed"; + } + } else { + return ErrnoError() << "mkdir() failed"; + } + } + + if (args.size() >= 4) { + auto uid = DecodeUid(args[3]); + if (!uid) { + return Error() << "Unable to decode UID for '" << args[3] << "': " << uid.error(); + } + Result gid = -1; + + if (args.size() == 5) { + gid = DecodeUid(args[4]); + if (!gid) { + return Error() << "Unable to decode GID for '" << args[3] << "': " << gid.error(); + } + } + + if (lchown(args[1].c_str(), *uid, *gid) == -1) { + return ErrnoError() << "lchown failed"; + } + + /* chown may have cleared S_ISUID and S_ISGID, chmod again */ + if (mode & (S_ISUID | S_ISGID)) { + if (fchmodat(AT_FDCWD, args[1].c_str(), mode, AT_SYMLINK_NOFOLLOW) == -1) { + return ErrnoError() << "fchmodat failed"; + } + } + } + + if (e4crypt_is_native()) { + if (e4crypt_set_directory_policy(args[1].c_str())) { + return reboot_into_recovery( + {"--prompt_and_wipe_data", "--reason=set_policy_failed:"s + args[1]}); + } + } + return Success(); +} + +/* umount */ +static Result do_umount(const BuiltinArguments& args) { + if (umount(args[1].c_str()) < 0) { + return ErrnoError() << "umount() failed"; + } + return Success(); +} + +static struct { + const char *name; + unsigned flag; +} mount_flags[] = { + { "noatime", MS_NOATIME }, + { "noexec", MS_NOEXEC }, + { "nosuid", MS_NOSUID }, + { "nodev", MS_NODEV }, + { "nodiratime", MS_NODIRATIME }, + { "ro", MS_RDONLY }, + { "rw", 0 }, + { "remount", MS_REMOUNT }, + { "bind", MS_BIND }, + { "rec", MS_REC }, + { "unbindable", MS_UNBINDABLE }, + { "private", MS_PRIVATE }, + { "slave", MS_SLAVE }, + { "shared", MS_SHARED }, + { "defaults", 0 }, + { 0, 0 }, +}; + +#define DATA_MNT_POINT "/data" + +/* mount */ +static Result do_mount(const BuiltinArguments& args) { + const char* options = nullptr; + unsigned flags = 0; + bool wait = false; + + for (size_t na = 4; na < args.size(); na++) { + size_t i; + for (i = 0; mount_flags[i].name; i++) { + if (!args[na].compare(mount_flags[i].name)) { + flags |= mount_flags[i].flag; + break; + } + } + + if (!mount_flags[i].name) { + if (!args[na].compare("wait")) { + wait = true; + // If our last argument isn't a flag, wolf it up as an option string. + } else if (na + 1 == args.size()) { + options = args[na].c_str(); + } + } + } + + const char* system = args[1].c_str(); + const char* source = args[2].c_str(); + const char* target = args[3].c_str(); + + if (android::base::StartsWith(source, "loop@")) { + int mode = (flags & MS_RDONLY) ? O_RDONLY : O_RDWR; + unique_fd fd(TEMP_FAILURE_RETRY(open(source + 5, mode | O_CLOEXEC))); + if (fd < 0) return ErrnoError() << "open(" << source + 5 << ", " << mode << ") failed"; + + for (size_t n = 0;; n++) { + std::string tmp = android::base::StringPrintf("/dev/block/loop%zu", n); + unique_fd loop(TEMP_FAILURE_RETRY(open(tmp.c_str(), mode | O_CLOEXEC))); + if (loop < 0) return ErrnoError() << "open(" << tmp << ", " << mode << ") failed"; + + loop_info info; + /* if it is a blank loop device */ + if (ioctl(loop, LOOP_GET_STATUS, &info) < 0 && errno == ENXIO) { + /* if it becomes our loop device */ + if (ioctl(loop, LOOP_SET_FD, fd.get()) >= 0) { + if (mount(tmp.c_str(), target, system, flags, options) < 0) { + ioctl(loop, LOOP_CLR_FD, 0); + return ErrnoError() << "mount() failed"; + } + return Success(); + } + } + } + + return Error() << "out of loopback devices"; + } else { + if (wait) + wait_for_file(source, kCommandRetryTimeout); + if (mount(source, target, system, flags, options) < 0) { + return ErrnoError() << "mount() failed"; + } + + } + + return Success(); +} + +/* Imports .rc files from the specified paths. Default ones are applied if none is given. + * + * start_index: index of the first path in the args list + */ +static void import_late(const std::vector& args, size_t start_index, size_t end_index) { + auto& action_manager = ActionManager::GetInstance(); + auto& service_list = ServiceList::GetInstance(); + Parser parser = CreateParser(action_manager, service_list); + if (end_index <= start_index) { + // Fallbacks for partitions on which early mount isn't enabled. + for (const auto& path : late_import_paths) { + parser.ParseConfig(path); + } + late_import_paths.clear(); + } else { + for (size_t i = start_index; i < end_index; ++i) { + parser.ParseConfig(args[i]); + } + } + + // Turning this on and letting the INFO logging be discarded adds 0.2s to + // Nexus 9 boot time, so it's disabled by default. + if (false) DumpState(); +} + +/* mount_fstab + * + * Call fs_mgr_mount_all() to mount the given fstab + */ +static Result mount_fstab(const char* fstabfile, int mount_mode) { + /* + * Call fs_mgr_mount_all() to mount all filesystems. We fork(2) and + * do the call in the child to provide protection to the main init + * process if anything goes wrong (crash or memory leak), and wait for + * the child to finish in the parent. + */ + pid_t pid = fork(); + if (pid > 0) { + /* Parent. Wait for the child to return */ + int status; + int wp_ret = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0)); + if (wp_ret == -1) { + // Unexpected error code. We will continue anyway. + PLOG(WARNING) << "waitpid failed"; + } + + if (WIFEXITED(status)) { + return WEXITSTATUS(status); + } else { + return Error() << "child aborted"; + } + } else if (pid == 0) { + /* child, call fs_mgr_mount_all() */ + + // So we can always see what fs_mgr_mount_all() does. + // Only needed if someone explicitly changes the default log level in their init.rc. + android::base::ScopedLogSeverity info(android::base::INFO); + + struct fstab* fstab = fs_mgr_read_fstab(fstabfile); + int child_ret = fs_mgr_mount_all(fstab, mount_mode); + fs_mgr_free_fstab(fstab); + if (child_ret == -1) { + PLOG(ERROR) << "fs_mgr_mount_all returned an error"; + } + _exit(child_ret); + } else { + return Error() << "fork() failed"; + } +} + +/* Queue event based on fs_mgr return code. + * + * code: return code of fs_mgr_mount_all + * + * This function might request a reboot, in which case it will + * not return. + * + * return code is processed based on input code + */ +static Result queue_fs_event(int code) { + if (code == FS_MGR_MNTALL_DEV_NEEDS_ENCRYPTION) { + ActionManager::GetInstance().QueueEventTrigger("encrypt"); + return Success(); + } else if (code == FS_MGR_MNTALL_DEV_MIGHT_BE_ENCRYPTED) { + property_set("ro.crypto.state", "encrypted"); + property_set("ro.crypto.type", "block"); + ActionManager::GetInstance().QueueEventTrigger("defaultcrypto"); + return Success(); + } else if (code == FS_MGR_MNTALL_DEV_NOT_ENCRYPTED) { + property_set("ro.crypto.state", "unencrypted"); + ActionManager::GetInstance().QueueEventTrigger("nonencrypted"); + return Success(); + } else if (code == FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) { + property_set("ro.crypto.state", "unsupported"); + ActionManager::GetInstance().QueueEventTrigger("nonencrypted"); + return Success(); + } else if (code == FS_MGR_MNTALL_DEV_NEEDS_RECOVERY) { + /* Setup a wipe via recovery, and reboot into recovery */ + PLOG(ERROR) << "fs_mgr_mount_all suggested recovery, so wiping data via recovery."; + const std::vector options = {"--wipe_data", "--reason=fs_mgr_mount_all" }; + return reboot_into_recovery(options); + /* If reboot worked, there is no return. */ + } else if (code == FS_MGR_MNTALL_DEV_FILE_ENCRYPTED) { + if (e4crypt_install_keyring()) { + return Error() << "e4crypt_install_keyring() failed"; + } + property_set("ro.crypto.state", "encrypted"); + property_set("ro.crypto.type", "file"); + + // Although encrypted, we have device key, so we do not need to + // do anything different from the nonencrypted case. + ActionManager::GetInstance().QueueEventTrigger("nonencrypted"); + return Success(); + } else if (code == FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED) { + if (e4crypt_install_keyring()) { + return Error() << "e4crypt_install_keyring() failed"; + } + property_set("ro.crypto.state", "encrypted"); + property_set("ro.crypto.type", "file"); + + // Although encrypted, vold has already set the device up, so we do not need to + // do anything different from the nonencrypted case. + ActionManager::GetInstance().QueueEventTrigger("nonencrypted"); + return Success(); + } else if (code == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) { + if (e4crypt_install_keyring()) { + return Error() << "e4crypt_install_keyring() failed"; + } + property_set("ro.crypto.state", "encrypted"); + property_set("ro.crypto.type", "file"); + + // Although encrypted, vold has already set the device up, so we do not need to + // do anything different from the nonencrypted case. + ActionManager::GetInstance().QueueEventTrigger("nonencrypted"); + return Success(); + } else if (code > 0) { + Error() << "fs_mgr_mount_all() returned unexpected error " << code; + } + /* else ... < 0: error */ + + return Error() << "Invalid code: " << code; +} + +/* mount_all [ ]* [--]* + * + * This function might request a reboot, in which case it will + * not return. + */ +static Result do_mount_all(const BuiltinArguments& args) { + std::size_t na = 0; + bool import_rc = true; + bool queue_event = true; + int mount_mode = MOUNT_MODE_DEFAULT; + const char* fstabfile = args[1].c_str(); + std::size_t path_arg_end = args.size(); + const char* prop_post_fix = "default"; + + for (na = args.size() - 1; na > 1; --na) { + if (args[na] == "--early") { + path_arg_end = na; + queue_event = false; + mount_mode = MOUNT_MODE_EARLY; + prop_post_fix = "early"; + } else if (args[na] == "--late") { + path_arg_end = na; + import_rc = false; + mount_mode = MOUNT_MODE_LATE; + prop_post_fix = "late"; + } + } + + std::string prop_name = "ro.boottime.init.mount_all."s + prop_post_fix; + android::base::Timer t; + auto mount_fstab_return_code = mount_fstab(fstabfile, mount_mode); + if (!mount_fstab_return_code) { + return Error() << "mount_fstab() failed " << mount_fstab_return_code.error(); + } + property_set(prop_name, std::to_string(t.duration().count())); + + if (import_rc) { + /* Paths of .rc files are specified at the 2nd argument and beyond */ + import_late(args.args, 2, path_arg_end); + } + + if (queue_event) { + /* queue_fs_event will queue event based on mount_fstab return code + * and return processed return code*/ + auto queue_fs_result = queue_fs_event(*mount_fstab_return_code); + if (!queue_fs_result) { + return Error() << "queue_fs_event() failed: " << queue_fs_result.error(); + } + } + + return Success(); +} + +static Result do_swapon_all(const BuiltinArguments& args) { + struct fstab *fstab; + int ret; + + fstab = fs_mgr_read_fstab(args[1].c_str()); + ret = fs_mgr_swapon_all(fstab); + fs_mgr_free_fstab(fstab); + + if (ret != 0) return Error() << "fs_mgr_swapon_all() failed"; + return Success(); +} + +static Result do_setprop(const BuiltinArguments& args) { + property_set(args[1], args[2]); + return Success(); +} + +static Result do_setrlimit(const BuiltinArguments& args) { + auto rlimit = ParseRlimit(args.args); + if (!rlimit) return rlimit.error(); + + if (setrlimit(rlimit->first, &rlimit->second) == -1) { + return ErrnoError() << "setrlimit failed"; + } + return Success(); +} + +static Result do_start(const BuiltinArguments& args) { + Service* svc = ServiceList::GetInstance().FindService(args[1]); + if (!svc) return Error() << "service " << args[1] << " not found"; + if (auto result = svc->Start(); !result) { + return Error() << "Could not start service: " << result.error(); + } + return Success(); +} + +static Result do_stop(const BuiltinArguments& args) { + Service* svc = ServiceList::GetInstance().FindService(args[1]); + if (!svc) return Error() << "service " << args[1] << " not found"; + svc->Stop(); + return Success(); +} + +static Result do_restart(const BuiltinArguments& args) { + Service* svc = ServiceList::GetInstance().FindService(args[1]); + if (!svc) return Error() << "service " << args[1] << " not found"; + svc->Restart(); + return Success(); +} + +static Result do_trigger(const BuiltinArguments& args) { + ActionManager::GetInstance().QueueEventTrigger(args[1]); + return Success(); +} + +static int MakeSymlink(const std::string& target, const std::string& linkpath) { + std::string secontext; + // Passing 0 for mode should work. + if (SelabelLookupFileContext(linkpath, 0, &secontext) && !secontext.empty()) { + setfscreatecon(secontext.c_str()); + } + + int rc = symlink(target.c_str(), linkpath.c_str()); + + if (!secontext.empty()) { + int save_errno = errno; + setfscreatecon(nullptr); + errno = save_errno; + } + + return rc; +} + +static Result do_symlink(const BuiltinArguments& args) { + if (MakeSymlink(args[1], args[2]) < 0) { + // The symlink builtin is often used to create symlinks for older devices to be backwards + // compatible with new paths, therefore we skip reporting this error. + if (errno == EEXIST && android::base::GetMinimumLogSeverity() > android::base::DEBUG) { + return Success(); + } + return ErrnoError() << "symlink() failed"; + } + return Success(); +} + +static Result do_rm(const BuiltinArguments& args) { + if (unlink(args[1].c_str()) < 0) { + return ErrnoError() << "unlink() failed"; + } + return Success(); +} + +static Result do_rmdir(const BuiltinArguments& args) { + if (rmdir(args[1].c_str()) < 0) { + return ErrnoError() << "rmdir() failed"; + } + return Success(); +} + +static Result do_sysclktz(const BuiltinArguments& args) { + struct timezone tz = {}; + if (!android::base::ParseInt(args[1], &tz.tz_minuteswest)) { + return Error() << "Unable to parse mins_west_of_gmt"; + } + + if (settimeofday(nullptr, &tz) == -1) { + return ErrnoError() << "settimeofday() failed"; + } + return Success(); +} + +static Result do_verity_load_state(const BuiltinArguments& args) { + int mode = -1; + bool loaded = fs_mgr_load_verity_state(&mode); + if (loaded && mode != VERITY_MODE_DEFAULT) { + ActionManager::GetInstance().QueueEventTrigger("verity-logging"); + } + if (!loaded) return Error() << "Could not load verity state"; + + return Success(); +} + +static void verity_update_property(fstab_rec *fstab, const char *mount_point, + int mode, int status) { + property_set("partition."s + mount_point + ".verified", std::to_string(mode)); +} + +static Result do_verity_update_state(const BuiltinArguments& args) { + if (!fs_mgr_update_verity_state(verity_update_property)) { + return Error() << "fs_mgr_update_verity_state() failed"; + } + return Success(); +} + +static Result do_write(const BuiltinArguments& args) { + if (auto result = WriteFile(args[1], args[2]); !result) { + return Error() << "Unable to write to file '" << args[1] << "': " << result.error(); + } + + return Success(); +} + +static Result readahead_file(const std::string& filename, bool fully) { + android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY))); + if (fd == -1) { + return ErrnoError() << "Error opening file"; + } + if (posix_fadvise(fd, 0, 0, POSIX_FADV_WILLNEED)) { + return ErrnoError() << "Error posix_fadvise file"; + } + if (readahead(fd, 0, std::numeric_limits::max())) { + return ErrnoError() << "Error readahead file"; + } + if (fully) { + char buf[BUFSIZ]; + ssize_t n; + while ((n = TEMP_FAILURE_RETRY(read(fd, &buf[0], sizeof(buf)))) > 0) { + } + if (n != 0) { + return ErrnoError() << "Error reading file"; + } + } + return Success(); +} + +static Result do_readahead(const BuiltinArguments& args) { + struct stat sb; + + if (stat(args[1].c_str(), &sb)) { + return ErrnoError() << "Error opening " << args[1]; + } + + bool readfully = false; + if (args.size() == 3 && args[2] == "--fully") { + readfully = true; + } + // We will do readahead in a forked process in order not to block init + // since it may block while it reads the + // filesystem metadata needed to locate the requested blocks. This + // occurs frequently with ext[234] on large files using indirect blocks + // instead of extents, giving the appearance that the call blocks until + // the requested data has been read. + pid_t pid = fork(); + if (pid == 0) { + if (setpriority(PRIO_PROCESS, 0, static_cast(ANDROID_PRIORITY_LOWEST)) != 0) { + PLOG(WARNING) << "setpriority failed"; + } + if (android_set_ioprio(0, IoSchedClass_IDLE, 7)) { + PLOG(WARNING) << "ioprio_get failed"; + } + android::base::Timer t; + if (S_ISREG(sb.st_mode)) { + if (auto result = readahead_file(args[1], readfully); !result) { + LOG(WARNING) << "Unable to readahead '" << args[1] << "': " << result.error(); + _exit(EXIT_FAILURE); + } + } else if (S_ISDIR(sb.st_mode)) { + char* paths[] = {const_cast(args[1].data()), nullptr}; + std::unique_ptr fts( + fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr), fts_close); + if (!fts) { + PLOG(ERROR) << "Error opening directory: " << args[1]; + _exit(EXIT_FAILURE); + } + // Traverse the entire hierarchy and do readahead + for (FTSENT* ftsent = fts_read(fts.get()); ftsent != nullptr; + ftsent = fts_read(fts.get())) { + if (ftsent->fts_info & FTS_F) { + const std::string filename = ftsent->fts_accpath; + if (auto result = readahead_file(filename, readfully); !result) { + LOG(WARNING) + << "Unable to readahead '" << filename << "': " << result.error(); + } + } + } + } + LOG(INFO) << "Readahead " << args[1] << " took " << t << " asynchronously"; + _exit(0); + } else if (pid < 0) { + return ErrnoError() << "Fork failed"; + } + return Success(); +} + +static Result do_copy(const BuiltinArguments& args) { + auto file_contents = ReadFile(args[1]); + if (!file_contents) { + return Error() << "Could not read input file '" << args[1] << "': " << file_contents.error(); + } + if (auto result = WriteFile(args[2], *file_contents); !result) { + return Error() << "Could not write to output file '" << args[2] << "': " << result.error(); + } + + return Success(); +} + +static Result do_chown(const BuiltinArguments& args) { + auto uid = DecodeUid(args[1]); + if (!uid) { + return Error() << "Unable to decode UID for '" << args[1] << "': " << uid.error(); + } + + // GID is optional and pushes the index of path out by one if specified. + const std::string& path = (args.size() == 4) ? args[3] : args[2]; + Result gid = -1; + + if (args.size() == 4) { + gid = DecodeUid(args[2]); + if (!gid) { + return Error() << "Unable to decode GID for '" << args[2] << "': " << gid.error(); + } + } + + if (lchown(path.c_str(), *uid, *gid) == -1) { + return ErrnoError() << "lchown() failed"; + } + + return Success(); +} + +static mode_t get_mode(const char *s) { + mode_t mode = 0; + while (*s) { + if (*s >= '0' && *s <= '7') { + mode = (mode<<3) | (*s-'0'); + } else { + return -1; + } + s++; + } + return mode; +} + +static Result do_chmod(const BuiltinArguments& args) { + mode_t mode = get_mode(args[1].c_str()); + if (fchmodat(AT_FDCWD, args[2].c_str(), mode, AT_SYMLINK_NOFOLLOW) < 0) { + return ErrnoError() << "fchmodat() failed"; + } + return Success(); +} + +static Result do_restorecon(const BuiltinArguments& args) { + int ret = 0; + + struct flag_type {const char* name; int value;}; + static const flag_type flags[] = { + {"--recursive", SELINUX_ANDROID_RESTORECON_RECURSE}, + {"--skip-ce", SELINUX_ANDROID_RESTORECON_SKIPCE}, + {"--cross-filesystems", SELINUX_ANDROID_RESTORECON_CROSS_FILESYSTEMS}, + {0, 0} + }; + + int flag = 0; + + bool in_flags = true; + for (size_t i = 1; i < args.size(); ++i) { + if (android::base::StartsWith(args[i], "--")) { + if (!in_flags) { + return Error() << "flags must precede paths"; + } + bool found = false; + for (size_t j = 0; flags[j].name; ++j) { + if (args[i] == flags[j].name) { + flag |= flags[j].value; + found = true; + break; + } + } + if (!found) { + return Error() << "bad flag " << args[i]; + } + } else { + in_flags = false; + if (selinux_android_restorecon(args[i].c_str(), flag) < 0) { + ret = errno; + } + } + } + + if (ret) return ErrnoError() << "selinux_android_restorecon() failed"; + return Success(); +} + +static Result do_restorecon_recursive(const BuiltinArguments& args) { + std::vector non_const_args(args.args); + non_const_args.insert(std::next(non_const_args.begin()), "--recursive"); + return do_restorecon({std::move(non_const_args), args.context}); +} + +static Result do_loglevel(const BuiltinArguments& args) { + // TODO: support names instead/as well? + int log_level = -1; + android::base::ParseInt(args[1], &log_level); + android::base::LogSeverity severity; + switch (log_level) { + case 7: severity = android::base::DEBUG; break; + case 6: severity = android::base::INFO; break; + case 5: + case 4: severity = android::base::WARNING; break; + case 3: severity = android::base::ERROR; break; + case 2: + case 1: + case 0: severity = android::base::FATAL; break; + default: + return Error() << "invalid log level " << log_level; + } + android::base::SetMinimumLogSeverity(severity); + return Success(); +} + +static Result do_load_persist_props(const BuiltinArguments& args) { + load_persist_props(); + return Success(); +} + +static Result do_load_system_props(const BuiltinArguments& args) { + load_system_props(); + return Success(); +} + +struct CpuInfo { + unsigned m_kernel_index; + unsigned m_start_cpu_index; + unsigned m_end_cpu_index; + + CpuInfo(unsigned kernel_index, unsigned start_cpu_index, unsigned end_cpu_index) + :m_kernel_index(kernel_index), + m_start_cpu_index(start_cpu_index), + m_end_cpu_index(end_cpu_index) + {} +}; + +static std::unordered_map g_cpu_info_map; + +static Result parse_available_socs() { + std::ifstream ifs; + ifs.open("/proc/sys/container/cpu/available_socs", std::ios::in); + if (!ifs.good()) { + return Error() << "Failed to get available socs"; + } + /* + * CSV-like format: + * ,, + * e.g. + * kirin9000,0,0-7 + * kirin990,1,8-15 + * ... + **/ + std::string line; + while(std::getline(ifs, line)) { + if (line.empty()) { + continue; + } + + std::string tmp; + std::stringstream line_stream(line); + std::string name; + unsigned kernel_index; + std::string cpuset; + std::getline(line_stream, name, ','); + std::getline(line_stream, tmp, ','); + kernel_index = std::stoul(tmp); + std::getline(line_stream, cpuset, ','); + + std::stringstream cpu_stream(cpuset); + unsigned start_cpu_index; + unsigned end_cpu_index; + std::getline(cpu_stream, tmp, '-'); + start_cpu_index = std::stoul(tmp); + std::getline(cpu_stream, tmp, '-'); + end_cpu_index = std::stoul(tmp); + + CpuInfo info(kernel_index, start_cpu_index, end_cpu_index); + g_cpu_info_map.insert({name, info}); + } + + ifs.close(); + return Success(); +} + +static std::string get_soc() { + std::string manufacturer = android::base::GetProperty("ro.product.manufacturer", "huawei"); + std::transform(manufacturer.begin(), manufacturer.end(), manufacturer.begin(), ::tolower); + std::string platform = android::base::GetProperty("ro.board.platform", "kirin9000"); + std::transform(platform.begin(), platform.end(), platform.begin(), ::tolower); + + if (manufacturer == "huawei") { + std::string soc = "kirin9000"; + if (platform == "kirin9000") { + soc = "kirin9000"; + } else if (platform == "kirin990") { + soc = "kirin990"; + } else if (platform == "kirin980") { + soc = "kirin980"; + } + return soc; + } + + if (manufacturer == "samsung") { + return "exynos9611"; + } + + int sum = 0; + for (char c : platform) { + sum += c; + } + return sum % 2 ? "SM8475" : "Dimensity8100"; +} + +static Result mount_cpu_dir(const std::string &soc) { + auto it = g_cpu_info_map.find(soc); + if (it == g_cpu_info_map.end()) { + return Error() << "Failed to mount cpu. " << soc << " is not supported yet."; + } + + LOG(INFO) << "Emulating " << soc << ". Using cpu " << it->second.m_start_cpu_index << "-" << it->second.m_end_cpu_index; + + if (it->second.m_start_cpu_index == 0) { + LOG(INFO) << "starts from 0, no need to mount"; + return Success(); + } + + for (unsigned i = it->second.m_start_cpu_index; i <= it->second.m_end_cpu_index; i++) { + std::string src(std::string("/sys/devices/system/cpu/cpu") + std::to_string(i)); + std::string dst(std::string("/sys/devices/system/cpu/cpu") + std::to_string(i - it->second.m_start_cpu_index)); + umount2(dst.c_str(), MNT_DETACH); + int ret = mount(src.c_str(), dst.c_str(), "", MS_BIND | MS_SILENT, ""); + if (ret != 0) { + return Error() << "Failed to bind mount " << src << " to " << dst << " : " << strerror(errno); + } + } + return Success(); +} + +static Result tell_kernel_soc_model(const std::string &soc) { + auto it = g_cpu_info_map.find(soc); + if (it == g_cpu_info_map.end()) { + return Error() << "Failed to tell kernel soc model. " << soc << " is not supported yet."; + } + unsigned kernel_index = it->second.m_kernel_index; + + std::ofstream ofs; + ofs.open("/proc/sys/container/cpu/soc_model", std::ios::out); + if (!ofs.good()) { + return Error() << "Failed to write soc model to kernel"; + } + + ofs << kernel_index; + + ofs.close(); + return Success(); +} + +static Result do_init_kernel_drivers(const BuiltinArguments& args) { + g_cpu_info_map.clear(); + + auto result = parse_available_socs(); + if(!result) { + return result; + } + + std::string soc = get_soc(); + result = mount_cpu_dir(soc); + if(!result) { + return result; + } + + result = tell_kernel_soc_model(soc); + if(!result) { + return result; + } + return Success(); +} + +static Result do_wait(const BuiltinArguments& args) { + auto timeout = kCommandRetryTimeout; + if (args.size() == 3) { + int timeout_int; + if (!android::base::ParseInt(args[2], &timeout_int)) { + return Error() << "failed to parse timeout"; + } + timeout = std::chrono::seconds(timeout_int); + } + + if (wait_for_file(args[1].c_str(), timeout) != 0) { + return Error() << "wait_for_file() failed"; + } + + return Success(); +} + +static Result do_wait_for_prop(const BuiltinArguments& args) { + const char* name = args[1].c_str(); + const char* value = args[2].c_str(); + size_t value_len = strlen(value); + + if (!IsLegalPropertyName(name)) { + return Error() << "IsLegalPropertyName(" << name << ") failed"; + } + if (value_len >= PROP_VALUE_MAX) { + return Error() << "value too long"; + } + if (!start_waiting_for_property(name, value)) { + return Error() << "already waiting for a property"; + } + return Success(); +} + +static bool is_file_crypto() { + return android::base::GetProperty("ro.crypto.type", "") == "file"; +} + +static Result ExecWithRebootOnFailure(const std::string& reboot_reason, + const BuiltinArguments& args) { + auto service = Service::MakeTemporaryOneshotService(args.args); + if (!service) { + return Error() << "Could not create exec service"; + } + service->AddReapCallback([reboot_reason](const siginfo_t& siginfo) { + if (siginfo.si_code != CLD_EXITED || siginfo.si_status != 0) { + if (e4crypt_is_native()) { + LOG(ERROR) << "Rebooting into recovery, reason: " << reboot_reason; + reboot_into_recovery({"--prompt_and_wipe_data", "--reason="s + reboot_reason}); + } else { + LOG(ERROR) << "Failure (reboot suppressed): " << reboot_reason; + } + } + }); + if (auto result = service->ExecStart(); !result) { + return Error() << "Could not start exec service: " << result.error(); + } + ServiceList::GetInstance().AddService(std::move(service)); + return Success(); +} + +static Result do_installkey(const BuiltinArguments& args) { + if (!is_file_crypto()) return Success(); + + auto unencrypted_dir = args[1] + e4crypt_unencrypted_folder; + if (!make_dir(unencrypted_dir, 0700) && errno != EEXIST) { + return ErrnoError() << "Failed to create " << unencrypted_dir; + } + return ExecWithRebootOnFailure( + "enablefilecrypto_failed", + {{"exec", "/system/bin/vdc", "--wait", "cryptfs", "enablefilecrypto"}, args.context}); +} + +static Result do_init_user0(const BuiltinArguments& args) { + return ExecWithRebootOnFailure( + "init_user0_failed", + {{"exec", "/system/bin/vdc", "--wait", "cryptfs", "init_user0"}, args.context}); +} + +// Builtin-function-map start +const BuiltinFunctionMap::Map& BuiltinFunctionMap::map() const { + constexpr std::size_t kMax = std::numeric_limits::max(); + // clang-format off + static const Map builtin_functions = { + {"bootchart", {1, 1, {false, do_bootchart}}}, + {"chmod", {2, 2, {true, do_chmod}}}, + {"chown", {2, 3, {true, do_chown}}}, + {"class_reset", {1, 1, {false, do_class_reset}}}, + {"class_restart", {1, 1, {false, do_class_restart}}}, + {"class_start", {1, 1, {false, do_class_start}}}, + {"class_stop", {1, 1, {false, do_class_stop}}}, + {"copy", {2, 2, {true, do_copy}}}, + {"domainname", {1, 1, {true, do_domainname}}}, + {"enable", {1, 1, {false, do_enable}}}, + {"exec", {1, kMax, {false, do_exec}}}, + {"exec_background", {1, kMax, {false, do_exec_background}}}, + {"exec_start", {1, 1, {false, do_exec_start}}}, + {"export", {2, 2, {false, do_export}}}, + {"hostname", {1, 1, {true, do_hostname}}}, + {"ifup", {1, 1, {true, do_ifup}}}, + {"init_user0", {0, 0, {false, do_init_user0}}}, + {"insmod", {1, kMax, {true, do_insmod}}}, + {"installkey", {1, 1, {false, do_installkey}}}, + {"load_persist_props", {0, 0, {false, do_load_persist_props}}}, + {"load_system_props", {0, 0, {false, do_load_system_props}}}, + {"init_kernel_drivers", {0, 0, {false, do_init_kernel_drivers}}}, + {"loglevel", {1, 1, {false, do_loglevel}}}, + {"mkdir", {1, 4, {true, do_mkdir}}}, + // TODO: Do mount operations in vendor_init. + // mount_all is currently too complex to run in vendor_init as it queues action triggers, + // imports rc scripts, etc. It should be simplified and run in vendor_init context. + // mount and umount are run in the same context as mount_all for symmetry. + {"mount_all", {1, kMax, {false, do_mount_all}}}, + {"mount", {3, kMax, {false, do_mount}}}, + {"umount", {1, 1, {false, do_umount}}}, + {"readahead", {1, 2, {true, do_readahead}}}, + {"restart", {1, 1, {false, do_restart}}}, + {"restorecon", {1, kMax, {true, do_restorecon}}}, + {"restorecon_recursive", {1, kMax, {true, do_restorecon_recursive}}}, + {"rm", {1, 1, {true, do_rm}}}, + {"rmdir", {1, 1, {true, do_rmdir}}}, + {"setprop", {2, 2, {true, do_setprop}}}, + {"setrlimit", {3, 3, {false, do_setrlimit}}}, + {"start", {1, 1, {false, do_start}}}, + {"stop", {1, 1, {false, do_stop}}}, + {"swapon_all", {1, 1, {false, do_swapon_all}}}, + {"symlink", {2, 2, {true, do_symlink}}}, + {"sysclktz", {1, 1, {false, do_sysclktz}}}, + {"trigger", {1, 1, {false, do_trigger}}}, + {"verity_load_state", {0, 0, {false, do_verity_load_state}}}, + {"verity_update_state", {0, 0, {false, do_verity_update_state}}}, + {"wait", {1, 2, {true, do_wait}}}, + {"wait_for_prop", {2, 2, {false, do_wait_for_prop}}}, + {"write", {2, 2, {true, do_write}}}, + }; + // clang-format on + return builtin_functions; +} +// Builtin-function-map end + +} // namespace init +} // namespace android diff --git a/aosp/system/core/init/devices.cpp b/aosp/system/core/init/devices.cpp new file mode 100644 index 000000000..653c30d56 --- /dev/null +++ b/aosp/system/core/init/devices.cpp @@ -0,0 +1,443 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "devices.h" + +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include "selinux.h" +#include "ueventd.h" +#include "util.h" + +#ifdef _INIT_INIT_H +#error "Do not include init.h in files used by ueventd or watchdogd; it will expose init's globals" +#endif + +using android::base::Basename; +using android::base::Dirname; +using android::base::Readlink; +using android::base::Realpath; +using android::base::StartsWith; +using android::base::StringPrintf; + +namespace android { +namespace init { + +/* Given a path that may start with a PCI device, populate the supplied buffer + * with the PCI domain/bus number and the peripheral ID and return 0. + * If it doesn't start with a PCI device, or there is some error, return -1 */ +static bool FindPciDevicePrefix(const std::string& path, std::string* result) { + result->clear(); + + if (!StartsWith(path, "/devices/pci")) return false; + + /* Beginning of the prefix is the initial "pci" after "/devices/" */ + std::string::size_type start = 9; + + /* End of the prefix is two path '/' later, capturing the domain/bus number + * and the peripheral ID. Example: pci0000:00/0000:00:1f.2 */ + auto end = path.find('/', start); + if (end == std::string::npos) return false; + + end = path.find('/', end + 1); + if (end == std::string::npos) return false; + + auto length = end - start; + if (length <= 4) { + // The minimum string that will get to this check is 'pci/', which is malformed, + // so return false + return false; + } + + *result = path.substr(start, length); + return true; +} + +/* Given a path that may start with a virtual block device, populate + * the supplied buffer with the virtual block device ID and return 0. + * If it doesn't start with a virtual block device, or there is some + * error, return -1 */ +static bool FindVbdDevicePrefix(const std::string& path, std::string* result) { + result->clear(); + + if (!StartsWith(path, "/devices/vbd-")) return false; + + /* Beginning of the prefix is the initial "vbd-" after "/devices/" */ + std::string::size_type start = 13; + + /* End of the prefix is one path '/' later, capturing the + virtual block device ID. Example: 768 */ + auto end = path.find('/', start); + if (end == std::string::npos) return false; + + auto length = end - start; + if (length == 0) return false; + + *result = path.substr(start, length); + return true; +} + +Permissions::Permissions(const std::string& name, mode_t perm, uid_t uid, gid_t gid) + : name_(name), perm_(perm), uid_(uid), gid_(gid), prefix_(false), wildcard_(false) { + // Set 'prefix_' or 'wildcard_' based on the below cases: + // + // 1) No '*' in 'name' -> Neither are set and Match() checks a given path for strict + // equality with 'name' + // + // 2) '*' only appears as the last character in 'name' -> 'prefix'_ is set to true and + // Match() checks if 'name' is a prefix of a given path. + // + // 3) '*' appears elsewhere -> 'wildcard_' is set to true and Match() uses fnmatch() + // with FNM_PATHNAME to compare 'name' to a given path. + + auto wildcard_position = name_.find('*'); + if (wildcard_position != std::string::npos) { + if (wildcard_position == name_.length() - 1) { + prefix_ = true; + name_.pop_back(); + } else { + wildcard_ = true; + } + } +} + +bool Permissions::Match(const std::string& path) const { + if (prefix_) return StartsWith(path, name_); + if (wildcard_) return fnmatch(name_.c_str(), path.c_str(), FNM_PATHNAME) == 0; + return path == name_; +} + +bool SysfsPermissions::MatchWithSubsystem(const std::string& path, + const std::string& subsystem) const { + std::string path_basename = Basename(path); + if (name().find(subsystem) != std::string::npos) { + if (Match("/sys/class/" + subsystem + "/" + path_basename)) return true; + if (Match("/sys/bus/" + subsystem + "/devices/" + path_basename)) return true; + } + return Match(path); +} + +void SysfsPermissions::SetPermissions(const std::string& path) const { + std::string attribute_file = path + "/" + attribute_; + LOG(VERBOSE) << "fixup " << attribute_file << " " << uid() << " " << gid() << " " << std::oct + << perm(); + + if (access(attribute_file.c_str(), F_OK) == 0) { + if (chown(attribute_file.c_str(), uid(), gid()) != 0) { + PLOG(ERROR) << "chown(" << attribute_file << ", " << uid() << ", " << gid() + << ") failed"; + } + if (chmod(attribute_file.c_str(), perm()) != 0) { + PLOG(ERROR) << "chmod(" << attribute_file << ", " << perm() << ") failed"; + } + } +} + +// Given a path that may start with a platform device, find the parent platform device by finding a +// parent directory with a 'subsystem' symlink that points to the platform bus. +// If it doesn't start with a platform device, return false +bool DeviceHandler::FindPlatformDevice(std::string path, std::string* platform_device_path) const { + platform_device_path->clear(); + + // Uevents don't contain the mount point, so we need to add it here. + path.insert(0, sysfs_mount_point_); + + std::string directory = Dirname(path); + + while (directory != "/" && directory != ".") { + std::string subsystem_link_path; + if (Realpath(directory + "/subsystem", &subsystem_link_path) && + subsystem_link_path == sysfs_mount_point_ + "/bus/platform") { + // We need to remove the mount point that we added above before returning. + directory.erase(0, sysfs_mount_point_.size()); + *platform_device_path = directory; + return true; + } + + auto last_slash = path.rfind('/'); + if (last_slash == std::string::npos) return false; + + path.erase(last_slash); + directory = Dirname(path); + } + + return false; +} + +void DeviceHandler::FixupSysPermissions(const std::string& upath, + const std::string& subsystem) const { + // upaths omit the "/sys" that paths in this list + // contain, so we prepend it... + std::string path = "/sys" + upath; + + for (const auto& s : sysfs_permissions_) { + if (s.MatchWithSubsystem(path, subsystem)) s.SetPermissions(path); + } + + if (!skip_restorecon_ && access(path.c_str(), F_OK) == 0) { + LOG(VERBOSE) << "restorecon_recursive: " << path; + if (selinux_android_restorecon(path.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE) != 0) { + PLOG(ERROR) << "selinux_android_restorecon(" << path << ") failed"; + } + } +} + +std::tuple DeviceHandler::GetDevicePermissions( + const std::string& path, const std::vector& links) const { + // Search the perms list in reverse so that ueventd.$hardware can override ueventd.rc. + for (auto it = dev_permissions_.crbegin(); it != dev_permissions_.crend(); ++it) { + if (it->Match(path) || std::any_of(links.cbegin(), links.cend(), + [it](const auto& link) { return it->Match(link); })) { + return {it->perm(), it->uid(), it->gid()}; + } + } + /* Default if nothing found. */ + return {0600, 0, 0}; +} + +void DeviceHandler::MakeDevice(const std::string& path, bool block, int major, int minor, + const std::vector& links) const { + auto[mode, uid, gid] = GetDevicePermissions(path, links); + mode |= (block ? S_IFBLK : S_IFCHR); + + std::string secontext; + if (!SelabelLookupFileContextBestMatch(path, links, mode, &secontext)) { + PLOG(ERROR) << "Device '" << path << "' not created; cannot find SELinux label"; + return; + } + if (!secontext.empty()) { + setfscreatecon(secontext.c_str()); + } + + dev_t dev = makedev(major, minor); + /* Temporarily change egid to avoid race condition setting the gid of the + * device node. Unforunately changing the euid would prevent creation of + * some device nodes, so the uid has to be set with chown() and is still + * racy. Fixing the gid race at least fixed the issue with system_server + * opening dynamic input devices under the AID_INPUT gid. */ + if (setegid(gid)) { + PLOG(ERROR) << "setegid(" << gid << ") for " << path << " device failed"; + goto out; + } + /* If the node already exists update its SELinux label to handle cases when + * it was created with the wrong context during coldboot procedure. */ + if (mknod(path.c_str(), mode, dev) && (errno == EEXIST) && !secontext.empty()) { + char* fcon = nullptr; + int rc = lgetfilecon(path.c_str(), &fcon); + if (rc < 0) { + PLOG(ERROR) << "Cannot get SELinux label on '" << path << "' device"; + goto out; + } + + bool different = fcon != secontext; + freecon(fcon); + + if (different && lsetfilecon(path.c_str(), secontext.c_str())) { + PLOG(ERROR) << "Cannot set '" << secontext << "' SELinux label on '" << path + << "' device"; + } + } + +out: + chown(path.c_str(), uid, -1); + if (setegid(AID_ROOT)) { + PLOG(FATAL) << "setegid(AID_ROOT) failed"; + } + + if (!secontext.empty()) { + setfscreatecon(nullptr); + } +} + +// replaces any unacceptable characters with '_', the +// length of the resulting string is equal to the input string +void SanitizePartitionName(std::string* string) { + const char* accept = + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "_-."; + + if (!string) return; + + std::string::size_type pos = 0; + while ((pos = string->find_first_not_of(accept, pos)) != std::string::npos) { + (*string)[pos] = '_'; + } +} + +std::vector DeviceHandler::GetBlockDeviceSymlinks(const Uevent& uevent) const { + std::string device; + std::string type; + + if (FindPlatformDevice(uevent.path, &device)) { + // Skip /devices/platform or /devices/ if present + static const std::string devices_platform_prefix = "/devices/platform/"; + static const std::string devices_prefix = "/devices/"; + + if (StartsWith(device, devices_platform_prefix)) { + device = device.substr(devices_platform_prefix.length()); + } else if (StartsWith(device, devices_prefix)) { + device = device.substr(devices_prefix.length()); + } + + type = "platform"; + } else if (FindPciDevicePrefix(uevent.path, &device)) { + type = "pci"; + } else if (FindVbdDevicePrefix(uevent.path, &device)) { + type = "vbd"; + } else { + return {}; + } + + std::vector links; + + LOG(VERBOSE) << "found " << type << " device " << device; + + auto link_path = "/dev/block/" + type + "/" + device; + + if (!uevent.partition_name.empty()) { + std::string partition_name_sanitized(uevent.partition_name); + SanitizePartitionName(&partition_name_sanitized); + if (partition_name_sanitized != uevent.partition_name) { + LOG(VERBOSE) << "Linking partition '" << uevent.partition_name << "' as '" + << partition_name_sanitized << "'"; + } + links.emplace_back(link_path + "/by-name/" + partition_name_sanitized); + // Adds symlink: /dev/block/by-name/. + if (boot_devices_.find(device) != boot_devices_.end()) { + links.emplace_back("/dev/block/by-name/" + partition_name_sanitized); + } + } + + auto last_slash = uevent.path.rfind('/'); + links.emplace_back(link_path + "/" + uevent.path.substr(last_slash + 1)); + + return links; +} + +void DeviceHandler::HandleDevice(const std::string& action, const std::string& devpath, bool block, + int major, int minor, const std::vector& links) const { + // never mknod for /dev/input/eventX, because vInput(KAOPU) listen it, l00441614 2021/4/15 + if (StartsWith(devpath, "/dev/input/event")) { + return; + } + + if (action == "add") { + MakeDevice(devpath, block, major, minor, links); + for (const auto& link : links) { + if (!mkdir_recursive(Dirname(link), 0755)) { + PLOG(ERROR) << "Failed to create directory " << Dirname(link); + } + + if (symlink(devpath.c_str(), link.c_str())) { + if (errno != EEXIST) { + PLOG(ERROR) << "Failed to symlink " << devpath << " to " << link; + } else if (std::string link_path; + Readlink(link, &link_path) && link_path != devpath) { + PLOG(ERROR) << "Failed to symlink " << devpath << " to " << link + << ", which already links to: " << link_path; + } + } + } + } + + if (action == "remove") { + for (const auto& link : links) { + std::string link_path; + if (Readlink(link, &link_path) && link_path == devpath) { + unlink(link.c_str()); + } + } + unlink(devpath.c_str()); + } +} + +void DeviceHandler::HandleDeviceEvent(const Uevent& uevent) { + if (uevent.action == "add" || uevent.action == "change" || uevent.action == "online") { + FixupSysPermissions(uevent.path, uevent.subsystem); + } + + // if it's not a /dev device, nothing to do + if (uevent.major < 0 || uevent.minor < 0) return; + + std::string devpath; + std::vector links; + bool block = false; + + if (uevent.subsystem == "block") { + block = true; + devpath = "/dev/block/" + Basename(uevent.path); + + if (StartsWith(uevent.path, "/devices")) { + links = GetBlockDeviceSymlinks(uevent); + } + } else if (const auto subsystem = + std::find(subsystems_.cbegin(), subsystems_.cend(), uevent.subsystem); + subsystem != subsystems_.cend()) { + devpath = subsystem->ParseDevPath(uevent); + } else if (uevent.subsystem == "usb") { + if (!uevent.device_name.empty()) { + devpath = "/dev/" + uevent.device_name; + } else { + // This imitates the file system that would be created + // if we were using devfs instead. + // Minors are broken up into groups of 128, starting at "001" + int bus_id = uevent.minor / 128 + 1; + int device_id = uevent.minor % 128 + 1; + devpath = StringPrintf("/dev/bus/usb/%03d/%03d", bus_id, device_id); + } + } else if (StartsWith(uevent.subsystem, "usb")) { + // ignore other USB events + return; + } else { + devpath = "/dev/" + Basename(uevent.path); + } + + mkdir_recursive(Dirname(devpath), 0755); + + HandleDevice(uevent.action, devpath, block, uevent.major, uevent.minor, links); +} + +DeviceHandler::DeviceHandler(std::vector dev_permissions, + std::vector sysfs_permissions, + std::vector subsystems, std::set boot_devices, + bool skip_restorecon) + : dev_permissions_(std::move(dev_permissions)), + sysfs_permissions_(std::move(sysfs_permissions)), + subsystems_(std::move(subsystems)), + boot_devices_(std::move(boot_devices)), + skip_restorecon_(skip_restorecon), + sysfs_mount_point_("/sys") {} + +DeviceHandler::DeviceHandler() + : DeviceHandler(std::vector{}, std::vector{}, + std::vector{}, std::set{}, false) {} + +} // namespace init +} // namespace android diff --git a/aosp/system/core/init/init.cpp b/aosp/system/core/init/init.cpp new file mode 100644 index 000000000..9cd116bcf --- /dev/null +++ b/aosp/system/core/init/init.cpp @@ -0,0 +1,970 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "init.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "action_parser.h" +#include "import_parser.h" +#include "init_first_stage.h" +#include "keychords.h" +#include "log.h" +#include "property_service.h" +#include "reboot.h" +#include "security.h" +#include "selinux.h" +#include "sigchld_handler.h" +#include "ueventd.h" +#include "util.h" +#include "watchdogd.h" + +using namespace std::string_literals; + +using android::base::boot_clock; +using android::base::GetProperty; +using android::base::ReadFileToString; +using android::base::StringPrintf; +using android::base::Timer; +using android::base::Trim; + +namespace android { +namespace init { + +static int property_triggers_enabled = 0; + +static char qemu[32]; + +std::string default_console = "/dev/console"; + +static int epoll_fd = -1; +static int sigterm_signal_fd = -1; + +static std::unique_ptr waiting_for_prop(nullptr); +static std::string wait_prop_name; +static std::string wait_prop_value; +static bool shutting_down; +static std::string shutdown_command; +static bool do_shutdown = false; + +std::vector late_import_paths; + +static std::vector* subcontexts; + +void DumpState() { + ServiceList::GetInstance().DumpState(); + ActionManager::GetInstance().DumpState(); +} + +Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) { + Parser parser; + + parser.AddSectionParser("service", std::make_unique(&service_list, subcontexts)); + parser.AddSectionParser("on", std::make_unique(&action_manager, subcontexts)); + parser.AddSectionParser("import", std::make_unique(&parser)); + + return parser; +} + +static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) { + + Parser parser = CreateParser(action_manager, service_list); + + std::string bootscript = GetProperty("ro.boot.init_rc", ""); + if (bootscript.empty()) { + parser.ParseConfig("/init.rc"); + if (!parser.ParseConfig("/system/etc/init")) { + late_import_paths.emplace_back("/system/etc/init"); + } + if (!parser.ParseConfig("/product/etc/init")) { + late_import_paths.emplace_back("/product/etc/init"); + } + if (!parser.ParseConfig("/odm/etc/init")) { + late_import_paths.emplace_back("/odm/etc/init"); + } + if (!parser.ParseConfig("/vendor/etc/init")) { + late_import_paths.emplace_back("/vendor/etc/init"); + } + } else { + parser.ParseConfig(bootscript); + } +} + +void register_epoll_handler(int fd, void (*fn)()) { + epoll_event ev; + ev.events = EPOLLIN; + ev.data.ptr = reinterpret_cast(fn); + if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) { + PLOG(ERROR) << "epoll_ctl failed"; + } +} + +bool start_waiting_for_property(const char *name, const char *value) +{ + if (waiting_for_prop) { + return false; + } + if (GetProperty(name, "") != value) { + // Current property value is not equal to expected value + wait_prop_name = name; + wait_prop_value = value; + waiting_for_prop.reset(new Timer()); + } else { + LOG(INFO) << "start_waiting_for_property(\"" + << name << "\", \"" << value << "\"): already set"; + } + return true; +} + +void ResetWaitForProp() { + wait_prop_name.clear(); + wait_prop_value.clear(); + waiting_for_prop.reset(); +} + +void property_changed(const std::string& name, const std::string& value) { + // If the property is sys.powerctl, we bypass the event queue and immediately handle it. + // This is to ensure that init will always and immediately shutdown/reboot, regardless of + // if there are other pending events to process or if init is waiting on an exec service or + // waiting on a property. + // In non-thermal-shutdown case, 'shutdown' trigger will be fired to let device specific + // commands to be executed. + if (name == "sys.powerctl") { + // Despite the above comment, we can't call HandlePowerctlMessage() in this function, + // because it modifies the contents of the action queue, which can cause the action queue + // to get into a bad state if this function is called from a command being executed by the + // action queue. Instead we set this flag and ensure that shutdown happens before the next + // command is run in the main init loop. + // TODO: once property service is removed from init, this will never happen from a builtin, + // but rather from a callback from the property service socket, in which case this hack can + // go away. + shutdown_command = value; + do_shutdown = true; + } + + if (property_triggers_enabled) ActionManager::GetInstance().QueuePropertyChange(name, value); + + if (waiting_for_prop) { + if (wait_prop_name == name && wait_prop_value == value) { + LOG(INFO) << "Wait for property took " << *waiting_for_prop; + ResetWaitForProp(); + } + } +} + +static std::optional RestartProcesses() { + std::optional next_process_restart_time; + for (const auto& s : ServiceList::GetInstance()) { + if (!(s->flags() & SVC_RESTARTING)) continue; + + auto restart_time = s->time_started() + 5s; + if (boot_clock::now() > restart_time) { + if (auto result = s->Start(); !result) { + LOG(ERROR) << "Could not restart process '" << s->name() << "': " << result.error(); + } + } else { + if (!next_process_restart_time || restart_time < *next_process_restart_time) { + next_process_restart_time = restart_time; + } + } + } + return next_process_restart_time; +} + +static Result DoControlStart(Service* service) { + return service->Start(); +} + +static Result DoControlStop(Service* service) { + service->Stop(); + return Success(); +} + +static Result DoControlRestart(Service* service) { + service->Restart(); + return Success(); +} + +enum class ControlTarget { + SERVICE, // function gets called for the named service + INTERFACE, // action gets called for every service that holds this interface +}; + +struct ControlMessageFunction { + ControlTarget target; + std::function(Service*)> action; +}; + +static const std::map& get_control_message_map() { + // clang-format off + static const std::map control_message_functions = { + {"start", {ControlTarget::SERVICE, DoControlStart}}, + {"stop", {ControlTarget::SERVICE, DoControlStop}}, + {"restart", {ControlTarget::SERVICE, DoControlRestart}}, + {"interface_start", {ControlTarget::INTERFACE, DoControlStart}}, + {"interface_stop", {ControlTarget::INTERFACE, DoControlStop}}, + {"interface_restart", {ControlTarget::INTERFACE, DoControlRestart}}, + }; + // clang-format on + + return control_message_functions; +} + +void HandleControlMessage(const std::string& msg, const std::string& name, pid_t pid) { + const auto& map = get_control_message_map(); + const auto it = map.find(msg); + + if (it == map.end()) { + LOG(ERROR) << "Unknown control msg '" << msg << "'"; + return; + } + + std::string cmdline_path = StringPrintf("proc/%d/cmdline", pid); + std::string process_cmdline; + if (ReadFileToString(cmdline_path, &process_cmdline)) { + std::replace(process_cmdline.begin(), process_cmdline.end(), '\0', ' '); + process_cmdline = Trim(process_cmdline); + } else { + process_cmdline = "unknown process"; + } + + LOG(INFO) << "Received control message '" << msg << "' for '" << name << "' from pid: " << pid + << " (" << process_cmdline << ")"; + + const ControlMessageFunction& function = it->second; + + if (function.target == ControlTarget::SERVICE) { + Service* svc = ServiceList::GetInstance().FindService(name); + if (svc == nullptr) { + LOG(ERROR) << "No such service '" << name << "' for ctl." << msg; + return; + } + if (auto result = function.action(svc); !result) { + LOG(ERROR) << "Could not ctl." << msg << " for service " << name << ": " + << result.error(); + } + + return; + } + + if (function.target == ControlTarget::INTERFACE) { + for (const auto& svc : ServiceList::GetInstance()) { + if (svc->interfaces().count(name) == 0) { + continue; + } + + if (auto result = function.action(svc.get()); !result) { + LOG(ERROR) << "Could not handle ctl." << msg << " for service " << svc->name() + << " with interface " << name << ": " << result.error(); + } + + return; + } + + LOG(ERROR) << "Could not find service hosting interface " << name; + return; + } + + LOG(ERROR) << "Invalid function target from static map key '" << msg + << "': " << static_cast::type>(function.target); +} + +static Result wait_for_coldboot_done_action(const BuiltinArguments& args) { + Timer t; + + LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "..."; + + // Historically we had a 1s timeout here because we weren't otherwise + // tracking boot time, and many OEMs made their sepolicy regular + // expressions too expensive (http://b/19899875). + + // Now we're tracking boot time, just log the time taken to a system + // property. We still panic if it takes more than a minute though, + // because any build that slow isn't likely to boot at all, and we'd + // rather any test lab devices fail back to the bootloader. + if (wait_for_file(COLDBOOT_DONE, 60s) < 0) { + LOG(FATAL) << "Timed out waiting for " COLDBOOT_DONE; + } + + property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration().count())); + return Success(); +} + +static Result keychord_init_action(const BuiltinArguments& args) { + keychord_init(); + return Success(); +} + +static Result console_init_action(const BuiltinArguments& args) { +#if 0 + std::string console = GetProperty("ro.boot.console", ""); + if (!console.empty()) { + default_console = "/dev/" + console; + } +#endif + return Success(); +} + +static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) { + if (key.empty()) return; + + if (for_emulator) { + // In the emulator, export any kernel option with the "ro.kernel." prefix. + property_set("ro.kernel." + key, value); + return; + } + + if (key == "qemu") { + strlcpy(qemu, value.c_str(), sizeof(qemu)); + } else if (android::base::StartsWith(key, "androidboot.")) { + property_set("ro.boot." + key.substr(12), value); + } +} + +static void export_oem_lock_status() { + if (!android::base::GetBoolProperty("ro.oem_unlock_supported", false)) { + return; + } + + std::string value = GetProperty("ro.boot.verifiedbootstate", ""); + + if (!value.empty()) { + property_set("ro.boot.flash.locked", value == "orange" ? "0" : "1"); + } +} + +static std::string lTrim(const std::string& str) +{ + return str.substr(str.find_first_not_of(" \n\r\t")); +} + +static std::string rTrim(const std::string& str) +{ + return str.substr(0,str.find_last_not_of(" \n\r\t") + 1); +} + +static std::string sTrim(const std::string& str) +{ + return lTrim(rTrim(str)); +} + +static void export_kernel_boot_props() { + + std::ifstream ifile("/data/local.prop"); + if(ifile) { + std::string line; + std::regex ro_hardware_reg("^ro\\.hardware=(.*)$"); + std::smatch matchResult; + while (!ifile.eof()) { + std::getline(ifile, line); + if(std::regex_match(line, matchResult, ro_hardware_reg)) { + property_set("ro.boot.hardware", sTrim(matchResult[1]).c_str()); + } + } + ifile.close(); + } + + struct { + const char *src_prop; + const char *dst_prop; + const char *default_value; + } prop_map[] = { + { "ro.boot.serialno", "ro.serialno", "", }, + { "ro.boot.mode", "ro.bootmode", "normal", }, + { "ro.boot.baseband", "ro.baseband", "unknown", }, + { "ro.boot.bootloader", "ro.bootloader", "unknown", }, + { "ro.boot.hardware", "ro.hardware", "goldfish", }, + { "ro.boot.revision", "ro.revision", "0", }, + }; + for (size_t i = 0; i < arraysize(prop_map); i++) { + std::string value = GetProperty(prop_map[i].src_prop, ""); + property_set(prop_map[i].dst_prop, (!value.empty()) ? value : prop_map[i].default_value); + } +} + +static void process_kernel_dt() { + if (!is_android_dt_value_expected("compatible", "android,firmware")) { + return; + } + + std::unique_ptr dir(opendir(get_android_dt_dir().c_str()), closedir); + if (!dir) return; + + std::string dt_file; + struct dirent *dp; + while ((dp = readdir(dir.get())) != NULL) { + if (dp->d_type != DT_REG || !strcmp(dp->d_name, "compatible") || !strcmp(dp->d_name, "name")) { + continue; + } + + std::string file_name = get_android_dt_dir() + dp->d_name; + + android::base::ReadFileToString(file_name, &dt_file); + std::replace(dt_file.begin(), dt_file.end(), ',', '.'); + + property_set("ro.boot."s + dp->d_name, dt_file); + } +} + +static void process_kernel_cmdline() { + // The first pass does the common stuff, and finds if we are in qemu. + // The second pass is only necessary for qemu to export all kernel params + // as properties. + import_kernel_cmdline(false, import_kernel_nv); + if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv); +} + +static Result property_enable_triggers_action(const BuiltinArguments& args) { + /* Enable property triggers. */ + property_triggers_enabled = 1; + return Success(); +} + +static Result queue_property_triggers_action(const BuiltinArguments& args) { + ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger"); + ActionManager::GetInstance().QueueAllPropertyActions(); + return Success(); +} + +static void global_seccomp() { + import_kernel_cmdline(false, [](const std::string& key, const std::string& value, bool in_qemu) { + if (key == "androidboot.seccomp" && value == "global" && !set_global_seccomp_filter()) { + LOG(FATAL) << "Failed to globally enable seccomp!"; + } + }); +} + +// Set the UDC controller for the ConfigFS USB Gadgets. +// Read the UDC controller in use from "/sys/class/udc". +// In case of multiple UDC controllers select the first one. +static void set_usb_controller() { + std::unique_ptrdir(opendir("/sys/class/udc"), closedir); + if (!dir) return; + + dirent* dp; + while ((dp = readdir(dir.get())) != nullptr) { + if (dp->d_name[0] == '.') continue; + + property_set("sys.usb.controller", dp->d_name); + break; + } +} + +static void InstallRebootSignalHandlers() { + // Instead of panic'ing the kernel as is the default behavior when init crashes, + // we prefer to reboot to bootloader on development builds, as this will prevent + // boot looping bad configurations and allow both developers and test farms to easily + // recover. + struct sigaction action; + memset(&action, 0, sizeof(action)); + sigfillset(&action.sa_mask); + action.sa_handler = [](int signal) { + // These signal handlers are also caught for processes forked from init, however we do not + // want them to trigger reboot, so we directly call _exit() for children processes here. + if (getpid() != 1) { + _exit(signal); + } + + // Calling DoReboot() or LOG(FATAL) is not a good option as this is a signal handler. + // RebootSystem uses syscall() which isn't actually async-signal-safe, but our only option + // and probably good enough given this is already an error case and only enabled for + // development builds. + RebootSystem(ANDROID_RB_RESTART2, "bootloader"); + }; + action.sa_flags = SA_RESTART; + sigaction(SIGABRT, &action, nullptr); + sigaction(SIGBUS, &action, nullptr); + sigaction(SIGFPE, &action, nullptr); + sigaction(SIGILL, &action, nullptr); + sigaction(SIGSEGV, &action, nullptr); +#if defined(SIGSTKFLT) + sigaction(SIGSTKFLT, &action, nullptr); +#endif + sigaction(SIGSYS, &action, nullptr); + sigaction(SIGTRAP, &action, nullptr); +} + +static void HandleSigtermSignal() { + signalfd_siginfo siginfo; + ssize_t bytes_read = TEMP_FAILURE_RETRY(read(sigterm_signal_fd, &siginfo, sizeof(siginfo))); + if (bytes_read != sizeof(siginfo)) { + PLOG(ERROR) << "Failed to read siginfo from sigterm_signal_fd"; + return; + } + + if (siginfo.ssi_pid != 0) { + // Drop any userspace SIGTERM requests. + LOG(DEBUG) << "Ignoring SIGTERM from pid " << siginfo.ssi_pid; + return; + } + + HandlePowerctlMessage("shutdown,container"); +} + +static void UnblockSigterm() { + sigset_t mask; + sigemptyset(&mask); + sigaddset(&mask, SIGTERM); + + if (sigprocmask(SIG_UNBLOCK, &mask, nullptr) == -1) { + PLOG(FATAL) << "failed to unblock SIGTERM for PID " << getpid(); + } +} + +static void InstallSigtermHandler() { + sigset_t mask; + sigemptyset(&mask); + sigaddset(&mask, SIGTERM); + + if (sigprocmask(SIG_BLOCK, &mask, nullptr) == -1) { + PLOG(FATAL) << "failed to block SIGTERM"; + } + + // Register a handler to unblock SIGTERM in the child processes. + const int result = pthread_atfork(nullptr, nullptr, &UnblockSigterm); + if (result != 0) { + LOG(FATAL) << "Failed to register a fork handler: " << strerror(result); + } + + sigterm_signal_fd = signalfd(-1, &mask, SFD_CLOEXEC); + if (sigterm_signal_fd == -1) { + PLOG(FATAL) << "failed to create signalfd for SIGTERM"; + } + + register_epoll_handler(sigterm_signal_fd, HandleSigtermSignal); +} + +// selinux namespace接口 +const char namespace_interface[] = "/sys/fs/selinux/ns"; +// 供aosp9使用的selinux namespace名字固定为aosp9,注意这个值要跟主机侧的策略里面使用到的值保持一致。 +const char selinux_namespace[] = "aosp9"; + +/** + * @brief 创建容器使用的selinux namespace,等同于命令:echo aosp9 > /sys/fs/selinux/unshare, + * 因为namespace跟进程init关联,所以安卓所有的进程(均为init的子孙进程)都处在同样的namespace下面; + */ +void init_selinux_namespace() { + int fd = open(namespace_interface, O_RDWR | O_NOFOLLOW); + if (fd < 0) { + LOG(ERROR) << "error open " << namespace_interface << ", errno " << errno; + return; + } + int ret = write(fd, selinux_namespace, strlen(selinux_namespace)); + if (ret == -1) { + LOG(ERROR) << "error write " << namespace_interface << ", errno " << errno; + } else { + LOG(INFO) << "init selinux namespace " << selinux_namespace; + } + close(fd); +} + +/** + * @brief 读取当前的selinux namespace,主要用来校验namespace生效,等同于命令:cat /sys/fs/selinux/unshare + * + */ +void read_selinux_namespace() { + int fd = open(namespace_interface, O_RDWR | O_NOFOLLOW); + if (fd < 0) { + LOG(ERROR) << "error open " << namespace_interface << ", errno " << errno; + return; + } + char ns[51] = {0}; + int ret = read(fd, ns, 50); + if (ret == -1) { + LOG(ERROR) << "error read " << namespace_interface << ", errno " << errno; + } else { + LOG(INFO) << "read selinux namespace " << ns; + } + close(fd); +} + +void signalHandler(int signum) { + if (signum != SIGTERM) { + return; + } + + sp sm = defaultServiceManager(); + if (sm == NULL) { + // init process redirects stdout and stderr to /dev/kmsg + std::cout << "Failed to get service manager" << std::endl; + return; + } + + sp binder = sm->getService(String16("power")); + sp pm = interface_cast(binder); + + status_t res = pm->shutdown(false, String16("agentrequested"), false); + + std::cout << "pm->shutdown(false, " << "agentrequested" << ", false), returned: " << res << std::endl; +} + +//#define ENABLE_LOG 1 + +#if ENABLE_LOG +#define PRINT_LOG(x) std::cout << x << std::endl +#else +#define PRINT_LOG(x) do {} while (0) +#endif + +#define forceinline __inline__ __attribute__((always_inline)) + +forceinline void check_umount(const char *path) { + PRINT_LOG("CHECK_UMOUNT"); + if (umount2(path, MNT_FORCE) == 0) { + PRINT_LOG("This is not cph server"); + exit(-1); + } +} + +forceinline void check_settimeofday() { + PRINT_LOG("CHECK_SETTIMEOFDAY"); + struct timeval newTime; + gettimeofday(&newTime, 0); + if (settimeofday(&newTime, NULL) == 0) { + PRINT_LOG("This is not cph server"); + exit(-1); + } +} + +forceinline void check_address() { + PRINT_LOG("CHECK_ADDRESS"); + int probe = 0; + uintptr_t address = reinterpret_cast(&probe); + bool is47thAnd48thBitZero = (address & (3ULL << 46)) == 0; + if (!is47thAnd48thBitZero) { + PRINT_LOG("This is not cph server"); + exit(-1); + } +} + + +int main(int argc, char** argv) { + if (!strcmp(basename(argv[0]), "ueventd")) { + return ueventd_main(argc, argv); + } + + if (!strcmp(basename(argv[0]), "watchdogd")) { + return watchdogd_main(argc, argv); + } + + if (argc > 1 && !strcmp(argv[1], "subcontext")) { + InitKernelLogging(argv); + const BuiltinFunctionMap function_map; + return SubcontextMain(argc, argv, &function_map); + } + + // We are in the process init now. + signal(SIGTERM, signalHandler); + + if (REBOOT_BOOTLOADER_ON_PANIC) { + InstallRebootSignalHandlers(); + } + bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr); + if (is_first_stage) { + check_umount("/"); + prepare_filesystem(); + check_settimeofday(); + boot_clock::time_point start_time = boot_clock::now(); + + // Clear the umask. + umask(0); + + clearenv(); + setenv("PATH", _PATH_DEFPATH, 1); + // Get the basic filesystem setup we need put together in the initramdisk + // on / and then we'll let the rc file figure out the rest. + chmod("/dev", 0755); + chmod("/dev/binder",0777); + chmod("/dev/hwbinder",0777); + chmod("/dev/vndbinder",0777); + chmod("/dev/fuse",0777); + chmod("/dev/ashmem",0777); + mkdir("/dev/pts", 0755); + chmod("/dev/pts",0755); + mkdir("/dev/socket", 0755); + chmod("/dev/socket", 0755); + + // Don't expose the raw commandline to unprivileged processes. + chmod("/proc/cmdline", 0440); + gid_t groups[] = { AID_READPROC }; + setgroups(arraysize(groups), groups); + mount("sysfs", "/sys", "sysfs", 0, NULL); + + if constexpr (WORLD_WRITABLE_KMSG) { + mknod("/dev/kmsg_debug", S_IFCHR | 0622, makedev(1, 11)); + } + + mknod("/dev/random", S_IFCHR | 0666, makedev(1, 8)); + mknod("/dev/urandom", S_IFCHR | 0666, makedev(1, 9)); + + // Mount staging areas for devices managed by vold + // See storage config details at http://source.android.com/devices/storage/ + mount("tmpfs", "/mnt", "tmpfs", MS_NOEXEC | MS_NOSUID | MS_NODEV, + "mode=0755,uid=0,gid=1000,size=16m"); + // /mnt/vendor is used to mount vendor-specific partitions that can not be + // part of the vendor partition, e.g. because they are mounted read-write. + mkdir("/mnt/vendor", 0755); + + check_address(); + // Now that tmpfs is mounted on /dev and we have /dev/kmsg, we can actually + // talk to the outside world... + InitKernelLogging(argv); + + LOG(INFO) << "init first stage started!"; + if (is_selinux_enabled()) { + init_selinux_namespace(); + read_selinux_namespace(); + } + + if (!DoFirstStageMount()) { + LOG(FATAL) << "Failed to mount required partitions early ..."; + } + + SetInitAvbVersionInRecovery(); + + // Enable seccomp if global boot option was passed (otherwise it is enabled in zygote). + global_seccomp(); + + if (is_selinux_enabled()) { + // Set up SELinux, loading the SELinux policy. + SelinuxSetupKernelLogging(); + //SelinuxInitialize(); + SelinuxInitializeWithoutLoadPolicy(); + } + + // We're in the kernel domain, so re-exec init to transition to the init domain now + // that the SELinux policy has been loaded. + if (selinux_android_restorecon("/init", 0) == -1) { + PLOG(FATAL) << "restorecon failed of /init failed"; + } + + if (is_selinux_enabled()) { + if (setcon("u:r:init:s0") < 0) { + LOG(INFO) << "set context for init failed."; + } + LOG(INFO) << "set context for init success."; + } + + setenv("INIT_SECOND_STAGE", "true", 1); + + static constexpr uint32_t kNanosecondsPerMillisecond = 1e6; + uint64_t start_ms = start_time.time_since_epoch().count() / kNanosecondsPerMillisecond; + setenv("INIT_STARTED_AT", std::to_string(start_ms).c_str(), 1); + + char* path = argv[0]; + char* args[] = { path, nullptr }; + execv(path, args); + + // execv() only returns if an error happened, in which case we + // panic and never fall through this conditional. + PLOG(FATAL) << "execv(\"" << path << "\") failed"; + } + + // At this point we're in the second stage of init. + if (is_selinux_enabled()) { + InitKernelLogging(argv); + } + LOG(INFO) << "init second stage started!"; + + // Set up a session keyring that all processes will have access to. It + // will hold things like FBE encryption keys. No process should override + // its session keyring. + keyctl_get_keyring_ID(KEY_SPEC_SESSION_KEYRING, 1); + + // Indicate that booting is in progress to background fw loaders, etc. + close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000)); + property_init(); +#if 0 + // If arguments are passed both on the command line and in DT, + // properties set in DT always have priority over the command-line ones. + process_kernel_dt(); + process_kernel_cmdline(); +#endif + // Propagate the kernel variables to internal variables + // used by init as well as the current required properties. + export_kernel_boot_props(); + + // Make the time that init started available for bootstat to log. + property_set("ro.boottime.init", getenv("INIT_STARTED_AT"));//getenv("INIT_STARTED_AT") = null + if (is_selinux_enabled()) { + property_set("ro.boottime.init.selinux", getenv("INIT_SELINUX_TOOK")); + } + + // Set libavb version for Framework-only OTA match in Treble build. + //const char* avb_version = getenv("INIT_AVB_VERSION"); + + //if (avb_version) property_set("ro.boot.avb_version", avb_version); + + // Clean up our environment. + unsetenv("INIT_SECOND_STAGE"); + unsetenv("INIT_STARTED_AT"); + unsetenv("INIT_SELINUX_TOOK"); + unsetenv("INIT_AVB_VERSION"); + + // Now set up SELinux for second stage. + if (is_selinux_enabled()) { + SelinuxSetupKernelLogging(); + SelabelInitialize(); + SelinuxRestoreContext(); + } + + epoll_fd = epoll_create1(EPOLL_CLOEXEC); + if (epoll_fd == -1) { + PLOG(FATAL) << "epoll_create1 failed"; + } + sigchld_handler_init(); + + if (!IsRebootCapable()) { + // If init does not have the CAP_SYS_BOOT capability, it is running in a container. + // In that case, receiving SIGTERM will cause the system to shut down. + InstallSigtermHandler(); + } + property_load_boot_defaults(); + export_oem_lock_status(); + + start_property_service(); + + set_usb_controller(); + + const BuiltinFunctionMap function_map; + Action::set_function_map(&function_map); + + subcontexts = InitializeSubcontexts(); + + ActionManager& am = ActionManager::GetInstance(); + ServiceList& sm = ServiceList::GetInstance(); + + LoadBootScripts(am, sm); + + // Turning this on and letting the INFO logging be discarded adds 0.2s to + // Nexus 9 boot time, so it's disabled by default. + if (false) DumpState(); + + am.QueueEventTrigger("early-init"); + // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev... + am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done"); + // ... so that we can start queuing up actions that require stuff from /dev. + + am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng"); + //am.QueueBuiltinAction(SetMmapRndBitsAction, "SetMmapRndBits"); + //am.QueueBuiltinAction(SetKptrRestrictAction, "SetKptrRestrict"); + am.QueueBuiltinAction(keychord_init_action, "keychord_init"); + am.QueueBuiltinAction(console_init_action, "console_init"); + + // Trigger all the boot actions to get us started. + am.QueueEventTrigger("init"); + +#if 0 + // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random + // wasn't ready immediately after wait_for_coldboot_done + am.QueueBuiltinAction(MixHwrngIntoLinuxRngAction, "MixHwrngIntoLinuxRng"); +#endif + + // Don't mount filesystems or start core system services in charger mode. + std::string bootmode = GetProperty("ro.bootmode", ""); + if (bootmode == "charger") { + am.QueueEventTrigger("charger"); + } else { + am.QueueEventTrigger("late-init"); + } + + // Run all property triggers based on current state of the properties. + am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers"); + + while (true) { + // By default, sleep until something happens. + int epoll_timeout_ms = -1; + + if (do_shutdown && !shutting_down) { + do_shutdown = false; + if (HandlePowerctlMessage(shutdown_command)) { + shutting_down = true; + } + } + + if (!(waiting_for_prop || Service::is_exec_service_running())) { + am.ExecuteOneCommand(); + } + if (!(waiting_for_prop || Service::is_exec_service_running())) { + if (!shutting_down) { + auto next_process_restart_time = RestartProcesses(); + + // If there's a process that needs restarting, wake up in time for that. + if (next_process_restart_time) { + epoll_timeout_ms = std::chrono::ceil( + *next_process_restart_time - boot_clock::now()) + .count(); + if (epoll_timeout_ms < 0) epoll_timeout_ms = 0; + } + } + + // If there's more work to do, wake up again immediately. + if (am.HasMoreCommands()) epoll_timeout_ms = 0; + } + + epoll_event ev; + int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms)); + if (nr == -1) { + PLOG(ERROR) << "epoll_wait failed"; + } else if (nr == 1) { + ((void (*)()) ev.data.ptr)(); + } + } + + return 0; +} + +} // namespace init +} // namespace android diff --git a/aosp/system/core/init/init.h b/aosp/system/core/init/init.h new file mode 100644 index 000000000..490ba1fe1 --- /dev/null +++ b/aosp/system/core/init/init.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _INIT_INIT_H +#define _INIT_INIT_H + +#include + +#include +#include + +#include "action.h" +#include "action_manager.h" +#include "parser.h" +#include "service.h" + +namespace android { +namespace init { + +// Note: These globals are *only* valid in init, so they should not be used in ueventd, +// watchdogd, or any files that may be included in those, such as devices.cpp and util.cpp. +// TODO: Have an Init class and remove all globals. +extern std::string default_console; +extern std::vector late_import_paths; + +extern void prepare_filesystem(void); + +Parser CreateParser(ActionManager& action_manager, ServiceList& service_list); + +void HandleControlMessage(const std::string& msg, const std::string& arg, pid_t pid); + +void property_changed(const std::string& name, const std::string& value); + +void register_epoll_handler(int fd, void (*fn)()); + +bool start_waiting_for_property(const char *name, const char *value); + +void DumpState(); + +void ResetWaitForProp(); + +int main(int argc, char** argv); + +} // namespace init +} // namespace android + +#endif /* _INIT_INIT_H */ diff --git a/aosp/system/core/init/log.cpp b/aosp/system/core/init/log.cpp new file mode 100644 index 000000000..7b45b7de0 --- /dev/null +++ b/aosp/system/core/init/log.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (C) 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "log.h" + +#include +#include +#include +#include + +#include +#include +#include + +#include "reboot.h" + +namespace android { +namespace init { + +static void InitAborter(const char* abort_message) { + // When init forks, it continues to use this aborter for LOG(FATAL), but we want children to + // simply abort instead of trying to reboot the system. + if (getpid() != 1) { + android::base::DefaultAborter(abort_message); + return; + } + + // DoReboot() does a lot to try to shutdown the system cleanly. If something happens to call + // LOG(FATAL) in the shutdown path, we want to catch this and immediately use the syscall to + // reboot instead of recursing here. + static bool has_aborted = false; + if (!has_aborted) { + has_aborted = true; + // Do not queue "shutdown" trigger since we want to shutdown immediately and it's not likely + // that we can even run the ActionQueue at this point. + DoReboot(ANDROID_RB_RESTART2, "reboot", "bootloader", false); + } else { + RebootSystem(ANDROID_RB_RESTART2, "bootloader"); + } +} + +void InitKernelLogging(char* argv[]) { + if (is_selinux_enabled()) { + // Make stdin/stdout/stderr all point to /dev/null. + int fd = open("/sys/fs/selinux/null", O_RDWR); + if (fd == -1) { + int saved_errno = errno; + android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter); + errno = saved_errno; + PLOG(FATAL) << "Couldn't open /sys/fs/selinux/null"; + } + dup2(fd, 0); + dup2(fd, 1); + dup2(fd, 2); + if (fd > 2) close(fd); + } + android::base::InitLogging(argv, &android::base::KernelLogger, InitAborter); +} + +int selinux_klog_callback(int type, const char *fmt, ...) { + android::base::LogSeverity severity = android::base::ERROR; + if (type == SELINUX_WARNING) { + severity = android::base::WARNING; + } else if (type == SELINUX_INFO) { + severity = android::base::INFO; + } + char buf[1024]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + android::base::KernelLogger(android::base::MAIN, severity, "selinux", nullptr, 0, buf); + return 0; +} + +} // namespace init +} // namespace android diff --git a/aosp/system/core/init/property_service.cpp b/aosp/system/core/init/property_service.cpp new file mode 100644 index 000000000..57fccbd12 --- /dev/null +++ b/aosp/system/core/init/property_service.cpp @@ -0,0 +1,905 @@ +/* + * Copyright (C) 2007 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "property_service.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "init.h" +#include "persistent_properties.h" +#include "property_type.h" +#include "selinux.h" +#include "subcontext.h" +#include "util.h" + +using namespace std::literals; + +using android::base::GetIntProperty; +using android::base::ReadFileToString; +using android::base::Split; +using android::base::StartsWith; +using android::base::StringPrintf; +using android::base::Timer; +using android::base::Trim; +using android::base::WriteStringToFile; +using android::properties::BuildTrie; +using android::properties::ParsePropertyInfoFile; +using android::properties::PropertyInfoAreaFile; +using android::properties::PropertyInfoEntry; + +#define RECOVERY_MOUNT_POINT "/recovery" + +namespace android { +namespace init { + +static bool persistent_properties_loaded = false; + +static int property_set_fd = -1; + +static PropertyInfoAreaFile property_info_area; + +uint32_t InitPropertySet(const std::string& name, const std::string& value); + +uint32_t (*property_set)(const std::string& name, const std::string& value) = InitPropertySet; + +void CreateSerializedPropertyInfo(); + +struct PropertyAuditData { + const ucred* cr; + const char* name; +}; + +void property_init() { + mkdir("/dev/__properties__", S_IRWXU | S_IXGRP | S_IXOTH); + CreateSerializedPropertyInfo(); + if (__system_property_area_init()) { + LOG(FATAL) << "Failed to initialize property area"; + } + if (!property_info_area.LoadDefaultPath()) { + LOG(FATAL) << "Failed to load serialized property info file"; + } +} +static bool CheckMacPerms(const std::string& name, const char* target_context, + const char* source_context, const ucred& cr) { + (void)name; + (void)target_context; + (void)source_context; + (void)cr; + return true; +/* + if (!target_context || !source_context) { + return false; + } + + PropertyAuditData audit_data; + + audit_data.name = name.c_str(); + audit_data.cr = &cr; + + bool has_access = (selinux_check_access(source_context, target_context, "property_service", + "set", &audit_data) == 0); + + return has_access; +*/ +} + +static uint32_t PropertySetOri(const std::string& name, const std::string& value, std::string* error) { + size_t valuelen = value.size(); + + if (!IsLegalPropertyName(name)) { + *error = "Illegal property name"; + return PROP_ERROR_INVALID_NAME; + } + + if (valuelen >= PROP_VALUE_MAX && !StartsWith(name, "ro.")) { + *error = "Property value too long"; + return PROP_ERROR_INVALID_VALUE; + } + + if (mbstowcs(nullptr, value.data(), 0) == static_cast(-1)) { + *error = "Value is not a UTF8 encoded string"; + return PROP_ERROR_INVALID_VALUE; + } + + prop_info* pi = (prop_info*) __system_property_find(name.c_str()); + if (pi != nullptr) { + // modify by lzl , we need to modify ro property + /* + // ro.* properties are actually "write-once". + if (StartsWith(name, "ro.")) { + *error = "Read-only property was already set"; + return PROP_ERROR_READ_ONLY_PROPERTY; + } + */ + + __system_property_update(pi, value.c_str(), valuelen); + } else { + int rc = __system_property_add(name.c_str(), name.size(), value.c_str(), valuelen); + if (rc < 0) { + *error = "__system_property_add failed"; + return PROP_ERROR_SET_FAILED; + } + } + + // Don't write properties to disk until after we have read all default + // properties to prevent them from being overwritten by default values. + if (persistent_properties_loaded && StartsWith(name, "persist.")) { + WritePersistentProperty(name, value); + } + property_changed(name, value); + return PROP_SUCCESS; +} + +// Changed by CPH dongshi 2021/1/28 +std::string property_name; +std::string property_value; +static int legacy_mainkeys_value = 0; +static int new_mainkeys_value = 0; + +static uint32_t PropertySet(const std::string& name, const std::string& value, std::string* error) { + property_name = name; + property_value = value; + + if (name == "qemu.hw.mainkeys") { + property_name = "com.cph.mainkeys"; + if (value == "1") { + legacy_mainkeys_value = 1; + } + if (new_mainkeys_value || legacy_mainkeys_value) { + property_value = "1"; + } + } + if (name == "com.cph.mainkeys") { + if (value == "1") { + new_mainkeys_value = 1; + } + if (legacy_mainkeys_value || new_mainkeys_value) { + property_value = "1"; + } + } + + return PropertySetOri(property_name, property_value, error); +} + +typedef int (*PropertyAsyncFunc)(const std::string&, const std::string&); + +struct PropertyChildInfo { + pid_t pid; + PropertyAsyncFunc func; + std::string name; + std::string value; +}; + +static std::queue property_children; + +static void PropertyChildLaunch() { + auto& info = property_children.front(); + pid_t pid = fork(); + if (pid < 0) { + LOG(ERROR) << "Failed to fork for property_set_async"; + while (!property_children.empty()) { + property_children.pop(); + } + return; + } + if (pid != 0) { + info.pid = pid; + } else { + if (info.func(info.name, info.value) != 0) { + LOG(ERROR) << "property_set_async(\"" << info.name << "\", \"" << info.value + << "\") failed"; + } + _exit(0); + } +} + +bool PropertyChildReap(pid_t pid) { + if (property_children.empty()) { + return false; + } + auto& info = property_children.front(); + if (info.pid != pid) { + return false; + } + std::string error; + if (PropertySet(info.name, info.value, &error) != PROP_SUCCESS) { + LOG(ERROR) << "Failed to set async property " << info.name << " to " << info.value << ": " + << error; + } + property_children.pop(); + if (!property_children.empty()) { + PropertyChildLaunch(); + } + return true; +} + +static uint32_t PropertySetAsync(const std::string& name, const std::string& value, + PropertyAsyncFunc func, std::string* error) { + if (value.empty()) { + return PropertySet(name, value, error); + } + + PropertyChildInfo info; + info.func = func; + info.name = name; + info.value = value; + property_children.push(info); + if (property_children.size() == 1) { + PropertyChildLaunch(); + } + return PROP_SUCCESS; +} + +static int RestoreconRecursiveAsync(const std::string& name, const std::string& value) { + return selinux_android_restorecon(value.c_str(), SELINUX_ANDROID_RESTORECON_RECURSE); +} + +uint32_t InitPropertySet(const std::string& name, const std::string& value) { + if (StartsWith(name, "ctl.")) { + LOG(ERROR) << "InitPropertySet: Do not set ctl. properties from init; call the Service " + "functions directly"; + return PROP_ERROR_INVALID_NAME; + } + if (name == "selinux.restorecon_recursive") { + LOG(ERROR) << "InitPropertySet: Do not set selinux.restorecon_recursive from init; use the " + "restorecon builtin directly"; + return PROP_ERROR_INVALID_NAME; + } + + uint32_t result = 0; + ucred cr = {.pid = 1, .uid = 0, .gid = 0}; + std::string error; + result = HandlePropertySet(name, value, kInitContext.c_str(), cr, &error); + if (result != PROP_SUCCESS) { + LOG(ERROR) << "Init cannot set '" << name << "' to '" << value << "': " << error; + } + + return result; +} + +class SocketConnection { + public: + SocketConnection(int socket, const ucred& cred) : socket_(socket), cred_(cred) {} + + ~SocketConnection() { close(socket_); } + + bool RecvUint32(uint32_t* value, uint32_t* timeout_ms) { + return RecvFully(value, sizeof(*value), timeout_ms); + } + + bool RecvChars(char* chars, size_t size, uint32_t* timeout_ms) { + return RecvFully(chars, size, timeout_ms); + } + + bool RecvString(std::string* value, uint32_t* timeout_ms) { + uint32_t len = 0; + if (!RecvUint32(&len, timeout_ms)) { + return false; + } + + if (len == 0) { + *value = ""; + return true; + } + + // http://b/35166374: don't allow init to make arbitrarily large allocations. + if (len > 0xffff) { + LOG(ERROR) << "sys_prop: RecvString asked to read huge string: " << len; + errno = ENOMEM; + return false; + } + + std::vector chars(len); + if (!RecvChars(&chars[0], len, timeout_ms)) { + return false; + } + + *value = std::string(&chars[0], len); + return true; + } + + bool SendUint32(uint32_t value) { + int result = TEMP_FAILURE_RETRY(send(socket_, &value, sizeof(value), 0)); + return result == sizeof(value); + } + + int socket() { return socket_; } + + const ucred& cred() { return cred_; } + + std::string source_context() const { + if (!is_selinux_enabled()) { + return ""; + } + + char* source_context = nullptr; + getpeercon(socket_, &source_context); + std::string result = source_context; + freecon(source_context); + return result; + } + + private: + bool PollIn(uint32_t* timeout_ms) { + struct pollfd ufds[1]; + ufds[0].fd = socket_; + ufds[0].events = POLLIN; + ufds[0].revents = 0; + while (*timeout_ms > 0) { + auto start_time = std::chrono::steady_clock::now(); + int nr = poll(ufds, 1, *timeout_ms); + auto now = std::chrono::steady_clock::now(); + auto time_elapsed = + std::chrono::duration_cast(now - start_time); + uint64_t millis = time_elapsed.count(); + *timeout_ms = (millis > *timeout_ms) ? 0 : *timeout_ms - millis; + + if (nr > 0) { + return true; + } + + if (nr == 0) { + // Timeout + break; + } + + if (nr < 0 && errno != EINTR) { + PLOG(ERROR) << "sys_prop: error waiting for uid " << cred_.uid + << " to send property message"; + return false; + } else { // errno == EINTR + // Timer rounds milliseconds down in case of EINTR we want it to be rounded up + // to avoid slowing init down by causing EINTR with under millisecond timeout. + if (*timeout_ms > 0) { + --(*timeout_ms); + } + } + } + + LOG(ERROR) << "sys_prop: timeout waiting for uid " << cred_.uid + << " to send property message."; + return false; + } + + bool RecvFully(void* data_ptr, size_t size, uint32_t* timeout_ms) { + size_t bytes_left = size; + char* data = static_cast(data_ptr); + while (*timeout_ms > 0 && bytes_left > 0) { + if (!PollIn(timeout_ms)) { + return false; + } + + int result = TEMP_FAILURE_RETRY(recv(socket_, data, bytes_left, MSG_DONTWAIT)); + if (result <= 0) { + return false; + } + + bytes_left -= result; + data += result; + } + + return bytes_left == 0; + } + + int socket_; + ucred cred_; + + DISALLOW_IMPLICIT_CONSTRUCTORS(SocketConnection); +}; + +bool CheckControlPropertyPerms(const std::string& name, const std::string& value, + const std::string& source_context, const ucred& cr) { + // We check the legacy method first but these properties are dontaudit, so we only log an audit + // if the newer method fails as well. We only do this with the legacy ctl. properties. + if (name == "ctl.start" || name == "ctl.stop" || name == "ctl.restart") { + // The legacy permissions model is that ctl. properties have their name ctl. and + // their value is the name of the service to apply that action to. Permissions for these + // actions are based on the service, so we must create a fake name of ctl. to + // check permissions. + auto control_string_legacy = "ctl." + value; + const char* target_context_legacy = nullptr; + const char* type_legacy = nullptr; + property_info_area->GetPropertyInfo(control_string_legacy.c_str(), &target_context_legacy, + &type_legacy); + + if (CheckMacPerms(control_string_legacy, target_context_legacy, source_context.c_str(), cr)) { + return true; + } + } + + auto control_string_full = name + "$" + value; + const char* target_context_full = nullptr; + const char* type_full = nullptr; + property_info_area->GetPropertyInfo(control_string_full.c_str(), &target_context_full, + &type_full); + + return CheckMacPerms(control_string_full, target_context_full, source_context.c_str(), cr); +} + +// This returns one of the enum of PROP_SUCCESS or PROP_ERROR*. +uint32_t HandlePropertySet(const std::string& name, const std::string& value, + const std::string& source_context, const ucred& cr, std::string* error) { + if (!IsLegalPropertyName(name)) { + *error = "Illegal property name"; + return PROP_ERROR_INVALID_NAME; + } + + if (StartsWith(name, "ctl.")) { + if (!CheckControlPropertyPerms(name, value, source_context, cr)) { + *error = StringPrintf("Invalid permissions to perform '%s' on '%s'", name.c_str() + 4, + value.c_str()); + return PROP_ERROR_HANDLE_CONTROL_MESSAGE; + } + + HandleControlMessage(name.c_str() + 4, value, cr.pid); + return PROP_SUCCESS; + } + + const char* target_context = nullptr; + const char* type = nullptr; + property_info_area->GetPropertyInfo(name.c_str(), &target_context, &type); + + if (!CheckMacPerms(name, target_context, source_context.c_str(), cr)) { + *error = "SELinux permission check failed"; + return PROP_ERROR_PERMISSION_DENIED; + } + + if (type == nullptr || !CheckType(type, value)) { + *error = StringPrintf("Property type check failed, value doesn't match expected type '%s'", + (type ?: "(null)")); + return PROP_ERROR_INVALID_VALUE; + } + + // sys.powerctl is a special property that is used to make the device reboot. We want to log + // any process that sets this property to be able to accurately blame the cause of a shutdown. + if (name == "sys.powerctl") { + std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid); + std::string process_cmdline; + std::string process_log_string; + if (ReadFileToString(cmdline_path, &process_cmdline)) { + // Since cmdline is null deliminated, .c_str() conveniently gives us just the process + // path. + process_log_string = StringPrintf(" (%s)", process_cmdline.c_str()); + } + LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid + << process_log_string; + } +#if 0 + if (name == "selinux.restorecon_recursive") { + return PropertySetAsync(name, value, RestoreconRecursiveAsync, error); + } +#endif + return PropertySet(name, value, error); +} + +static void handle_property_set_fd() { + static constexpr uint32_t kDefaultSocketTimeout = 2000; /* ms */ + + int s = accept4(property_set_fd, nullptr, nullptr, SOCK_CLOEXEC); + if (s == -1) { + return; + } + + ucred cr; + socklen_t cr_size = sizeof(cr); + if (getsockopt(s, SOL_SOCKET, SO_PEERCRED, &cr, &cr_size) < 0) { + close(s); + PLOG(ERROR) << "sys_prop: unable to get SO_PEERCRED"; + return; + } + + SocketConnection socket(s, cr); + uint32_t timeout_ms = kDefaultSocketTimeout; + + uint32_t cmd = 0; + if (!socket.RecvUint32(&cmd, &timeout_ms)) { + PLOG(ERROR) << "sys_prop: error while reading command from the socket"; + socket.SendUint32(PROP_ERROR_READ_CMD); + return; + } + + switch (cmd) { + case PROP_MSG_SETPROP: { + char prop_name[PROP_NAME_MAX]; + char prop_value[PROP_VALUE_MAX]; + + if (!socket.RecvChars(prop_name, PROP_NAME_MAX, &timeout_ms) || + !socket.RecvChars(prop_value, PROP_VALUE_MAX, &timeout_ms)) { + PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP): error while reading name/value from the socket"; + return; + } + + prop_name[PROP_NAME_MAX-1] = 0; + prop_value[PROP_VALUE_MAX-1] = 0; + + const auto& cr = socket.cred(); + std::string error; + uint32_t result = + HandlePropertySet(prop_name, prop_value, socket.source_context(), cr, &error); + if (result != PROP_SUCCESS) { + LOG(ERROR) << "Unable to set property '" << prop_name << "' to '" << prop_value + << "' from uid:" << cr.uid << " gid:" << cr.gid << " pid:" << cr.pid << ": " + << error; + } + + break; + } + + case PROP_MSG_SETPROP2: { + std::string name; + std::string value; + if (!socket.RecvString(&name, &timeout_ms) || + !socket.RecvString(&value, &timeout_ms)) { + PLOG(ERROR) << "sys_prop(PROP_MSG_SETPROP2): error while reading name/value from the socket"; + socket.SendUint32(PROP_ERROR_READ_DATA); + return; + } + + const auto& cr = socket.cred(); + std::string error; + uint32_t result = HandlePropertySet(name, value, socket.source_context(), cr, &error); + if (result != PROP_SUCCESS) { + LOG(ERROR) << "Unable to set property '" << name << "' to '" << value + << "' from uid:" << cr.uid << " gid:" << cr.gid << " pid:" << cr.pid << ": " + << error; + } + socket.SendUint32(result); + break; + } + + default: + LOG(ERROR) << "sys_prop: invalid command " << cmd; + socket.SendUint32(PROP_ERROR_INVALID_CMD); + break; + } +} + +static bool load_properties_from_file(const char *, const char *); + +/* + * Filter is used to decide which properties to load: NULL loads all keys, + * "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match. + */ +static void LoadProperties(char* data, const char* filter, const char* filename) { + char *key, *value, *eol, *sol, *tmp, *fn; + size_t flen = 0; + + const char* context = kInitContext.c_str(); + if (SelinuxHasVendorInit()) { + for (const auto& [path_prefix, secontext] : paths_and_secontexts) { + if (StartsWith(filename, path_prefix)) { + context = secontext; + } + } + } + + if (filter) { + flen = strlen(filter); + } + + sol = data; + while ((eol = strchr(sol, '\n'))) { + key = sol; + *eol++ = 0; + sol = eol; + + while (isspace(*key)) key++; + if (*key == '#') continue; + + tmp = eol - 2; + while ((tmp > key) && isspace(*tmp)) *tmp-- = 0; + + if (!strncmp(key, "import ", 7) && flen == 0) { + fn = key + 7; + while (isspace(*fn)) fn++; + + key = strchr(fn, ' '); + if (key) { + *key++ = 0; + while (isspace(*key)) key++; + } + + load_properties_from_file(fn, key); + + } else { + value = strchr(key, '='); + if (!value) continue; + *value++ = 0; + + tmp = value - 2; + while ((tmp > key) && isspace(*tmp)) *tmp-- = 0; + + while (isspace(*value)) value++; + + if (flen > 0) { + if (filter[flen - 1] == '*') { + if (strncmp(key, filter, flen - 1)) continue; + } else { + if (strcmp(key, filter)) continue; + } + } + + if (StartsWith(key, "ctl.") || key == "sys.powerctl"s || + key == "selinux.restorecon_recursive"s) { + LOG(ERROR) << "Ignoring disallowed property '" << key + << "' with special meaning in prop file '" << filename << "'"; + continue; + } + + uint32_t result = 0; + ucred cr = {.pid = 1, .uid = 0, .gid = 0}; + std::string error; + result = HandlePropertySet(key, value, context, cr, &error); + if (result != PROP_SUCCESS) { + LOG(ERROR) << "Unable to set property '" << key << "' to '" << value + << "' in property file '" << filename << "': " << error; + } + } + } +} + +// Filter is used to decide which properties to load: NULL loads all keys, +// "ro.foo.*" is a prefix match, and "ro.foo.bar" is an exact match. +static bool load_properties_from_file(const char* filename, const char* filter) { + Timer t; + auto file_contents = ReadFile(filename); + if (!file_contents) { + PLOG(WARNING) << "Couldn't load property file '" << filename + << "': " << file_contents.error(); + return false; + } + file_contents->push_back('\n'); + + LoadProperties(file_contents->data(), filter, filename); + LOG(VERBOSE) << "(Loading properties from " << filename << " took " << t << ".)"; + return true; +} + +// persist.sys.usb.config values can't be combined on build-time when property +// files are split into each partition. +// So we need to apply the same rule of build/make/tools/post_process_props.py +// on runtime. +static void update_sys_usb_config() { + bool is_debuggable = android::base::GetBoolProperty("ro.debuggable", false); + std::string config = android::base::GetProperty("persist.sys.usb.config", ""); + if (config.empty()) { + property_set("persist.sys.usb.config", is_debuggable ? "adb" : "none"); + } else if (is_debuggable && config.find("adb") == std::string::npos && + config.length() + 4 < PROP_VALUE_MAX) { + config.append(",adb"); + property_set("persist.sys.usb.config", config); + } +} + +void property_load_boot_defaults() { + if (!load_properties_from_file("/system/etc/prop.default", NULL)) { + // Try recovery path + if (!load_properties_from_file("/prop.default", NULL)) { + // Try legacy path + load_properties_from_file("/default.prop", NULL); + } + } + load_properties_from_file("/product/build.prop", NULL); + load_properties_from_file("/odm/default.prop", NULL); + load_properties_from_file("/vendor/default.prop", NULL); + + update_sys_usb_config(); +} + +static void load_override_properties() { + if (ALLOW_LOCAL_PROP_OVERRIDE) { + load_properties_from_file("/data/local.prop", NULL); + } +} + +/* When booting an encrypted system, /data is not mounted when the + * property service is started, so any properties stored there are + * not loaded. Vold triggers init to load these properties once it + * has mounted /data. + */ +void load_persist_props(void) { + // Devices with FDE have load_persist_props called twice; the first time when the temporary + // /data partition is mounted and then again once /data is truly mounted. We do not want to + // read persistent properties from the temporary /data partition or mark persistent properties + // as having been loaded during the first call, so we return in that case. + std::string crypto_state = android::base::GetProperty("ro.crypto.state", ""); + std::string crypto_type = android::base::GetProperty("ro.crypto.type", ""); + if (crypto_state == "encrypted" && crypto_type == "block") { + static size_t num_calls = 0; + if (++num_calls == 1) return; + } + + load_override_properties(); + /* Read persistent properties after all default values have been loaded. */ + auto persistent_properties = LoadPersistentProperties(); + for (const auto& persistent_property_record : persistent_properties.properties()) { + property_set(persistent_property_record.name(), persistent_property_record.value()); + } + persistent_properties_loaded = true; + property_set("ro.persistent_properties.ready", "true"); +} + +void load_recovery_id_prop() { + std::unique_ptr fstab(fs_mgr_read_fstab_default(), + fs_mgr_free_fstab); + if (!fstab) { + PLOG(ERROR) << "unable to read default fstab"; + return; + } + + fstab_rec* rec = fs_mgr_get_entry_for_mount_point(fstab.get(), RECOVERY_MOUNT_POINT); + if (rec == NULL) { + LOG(ERROR) << "/recovery not specified in fstab"; + return; + } + + int fd = open(rec->blk_device, O_RDONLY); + if (fd == -1) { + PLOG(ERROR) << "error opening block device " << rec->blk_device; + return; + } + + boot_img_hdr hdr; + if (android::base::ReadFully(fd, &hdr, sizeof(hdr))) { + std::string hex = bytes_to_hex(reinterpret_cast(hdr.id), sizeof(hdr.id)); + property_set("ro.recovery_id", hex); + } else { + PLOG(ERROR) << "error reading /recovery"; + } + + close(fd); +} + +void load_system_props() { + load_properties_from_file("/system/build.prop", NULL); + load_properties_from_file("/odm/build.prop", NULL); + load_properties_from_file("/vendor/build.prop", NULL); + load_properties_from_file("/factory/factory.prop", "ro.*"); + load_recovery_id_prop(); +} + +static int SelinuxAuditCallback(void* data, security_class_t /*cls*/, char* buf, size_t len) { + auto* d = reinterpret_cast(data); + + if (!d || !d->name || !d->cr) { + LOG(ERROR) << "AuditCallback invoked with null data arguments!"; + return 0; + } + + snprintf(buf, len, "property=%s pid=%d uid=%d gid=%d", d->name, d->cr->pid, d->cr->uid, + d->cr->gid); + return 0; +} + +bool LoadPropertyInfoFromFile(const std::string& filename, + std::vector* property_infos) { + auto file_contents = std::string(); + if (!ReadFileToString(filename, &file_contents)) { + PLOG(ERROR) << "Could not read properties from '" << filename << "'"; + return false; + } + + auto errors = std::vector{}; + ParsePropertyInfoFile(file_contents, property_infos, &errors); + // Individual parsing errors are reported but do not cause a failed boot, which is what + // returning false would do here. + for (const auto& error : errors) { + LOG(ERROR) << "Could not read line from '" << filename << "': " << error; + } + + return true; +} + +void CreateSerializedPropertyInfo() { + auto property_infos = std::vector(); + if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) { + if (!LoadPropertyInfoFromFile("/system/etc/selinux/plat_property_contexts", + &property_infos)) { + return; + } + // Don't check for failure here, so we always have a sane list of properties. + // E.g. In case of recovery, the vendor partition will not have mounted and we + // still need the system / platform properties to function. + if (!LoadPropertyInfoFromFile("/vendor/etc/selinux/vendor_property_contexts", + &property_infos)) { + // Fallback to nonplat_* if vendor_* doesn't exist. + LoadPropertyInfoFromFile("/vendor/etc/selinux/nonplat_property_contexts", + &property_infos); + } + } else { + if (!LoadPropertyInfoFromFile("/plat_property_contexts", &property_infos)) { + return; + } + if (!LoadPropertyInfoFromFile("/vendor_property_contexts", &property_infos)) { + // Fallback to nonplat_* if vendor_* doesn't exist. + LoadPropertyInfoFromFile("/nonplat_property_contexts", &property_infos); + } + } + + auto serialized_contexts = std::string(); + auto error = std::string(); + if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts, + &error)) { + LOG(ERROR) << "Unable to serialize property contexts: " << error; + return; + } + + constexpr static const char kPropertyInfosPath[] = "/dev/__properties__/property_info"; + if (!WriteStringToFile(serialized_contexts, kPropertyInfosPath, 0444, 0, 0, false)) { + PLOG(ERROR) << "Unable to write serialized property infos to file"; + } + selinux_android_restorecon(kPropertyInfosPath, 0); +} + +void start_property_service() { +#if 0 + selinux_callback cb; + cb.func_audit = SelinuxAuditCallback; + selinux_set_callback(SELINUX_CB_AUDIT, cb); +#endif + property_set("ro.property_service.version", "2"); + + property_set_fd = CreateSocket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, + false, 0666, 0, 0, nullptr); + if (property_set_fd == -1) { + PLOG(FATAL) << "start_property_service socket creation failed"; + } + + listen(property_set_fd, 8); + + register_epoll_handler(property_set_fd, handle_property_set_fd); +} + +} // namespace init +} // namespace android diff --git a/aosp/system/core/init/selinux.cpp b/aosp/system/core/init/selinux.cpp new file mode 100644 index 000000000..c3519414e --- /dev/null +++ b/aosp/system/core/init/selinux.cpp @@ -0,0 +1,553 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// This file contains the functions that initialize SELinux during boot as well as helper functions +// for SELinux operation for init. + +// When the system boots, there is no SEPolicy present and init is running in the kernel domain. +// Init loads the SEPolicy from the file system, restores the context of /init based on this +// SEPolicy, and finally exec()'s itself to run in the proper domain. + +// The SEPolicy on Android comes in two variants: monolithic and split. + +// The monolithic policy variant is for legacy non-treble devices that contain a single SEPolicy +// file located at /sepolicy and is directly loaded into the kernel SELinux subsystem. + +// The split policy is for supporting treble devices. It splits the SEPolicy across files on +// /system/etc/selinux (the 'plat' portion of the policy) and /vendor/etc/selinux (the 'nonplat' +// portion of the policy). This is necessary to allow the system image to be updated independently +// of the vendor image, while maintaining contributions from both partitions in the SEPolicy. This +// is especially important for VTS testing, where the SEPolicy on the Google System Image may not be +// identical to the system image shipped on a vendor's device. + +// The split SEPolicy is loaded as described below: +// 1) There is a precompiled SEPolicy located at /vendor/etc/selinux/precompiled_sepolicy. +// Stored along with this file is the sha256 hash of the parts of the SEPolicy on /system that +// were used to compile this precompiled policy. The system partition contains a similar sha256 +// of the parts of the SEPolicy that it currently contains. If these two hashes match, then the +// system loads this precompiled_sepolicy directly. +// 2) If these hashes do not match, then /system has been updated out of sync with /vendor and the +// init needs to compile the SEPolicy. /system contains the SEPolicy compiler, secilc, and it +// is used by the LoadSplitPolicy() function below to compile the SEPolicy to a temp directory +// and load it. That function contains even more documentation with the specific implementation +// details of how the SEPolicy is compiled if needed. + +#include "selinux.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "log.h" +#include "util.h" + +using android::base::ParseInt; +using android::base::Timer; +using android::base::unique_fd; + +namespace android { +namespace init { + +namespace { + +selabel_handle* sehandle = nullptr; + +enum EnforcingStatus { SELINUX_PERMISSIVE, SELINUX_ENFORCING }; + +EnforcingStatus StatusFromCmdline() { + EnforcingStatus status = SELINUX_ENFORCING; + + import_kernel_cmdline(false, + [&](const std::string& key, const std::string& value, bool in_qemu) { + if (key == "androidboot.selinux" && value == "permissive") { + status = SELINUX_PERMISSIVE; + } + }); + + return status; +} + +bool IsEnforcing() { + if (ALLOW_PERMISSIVE_SELINUX) { + return StatusFromCmdline() == SELINUX_ENFORCING; + } + return true; +} + +// Forks, executes the provided program in the child, and waits for the completion in the parent. +// Child's stderr is captured and logged using LOG(ERROR). +bool ForkExecveAndWaitForCompletion(const char* filename, char* const argv[]) { + // Create a pipe used for redirecting child process's output. + // * pipe_fds[0] is the FD the parent will use for reading. + // * pipe_fds[1] is the FD the child will use for writing. + int pipe_fds[2]; + if (pipe(pipe_fds) == -1) { + PLOG(ERROR) << "Failed to create pipe"; + return false; + } + + pid_t child_pid = fork(); + if (child_pid == -1) { + PLOG(ERROR) << "Failed to fork for " << filename; + return false; + } + + if (child_pid == 0) { + // fork succeeded -- this is executing in the child process + + // Close the pipe FD not used by this process + close(pipe_fds[0]); + + // Redirect stderr to the pipe FD provided by the parent + if (TEMP_FAILURE_RETRY(dup2(pipe_fds[1], STDERR_FILENO)) == -1) { + PLOG(ERROR) << "Failed to redirect stderr of " << filename; + _exit(127); + return false; + } + close(pipe_fds[1]); + + if (execv(filename, argv) == -1) { + PLOG(ERROR) << "Failed to execve " << filename; + return false; + } + // Unreachable because execve will have succeeded and replaced this code + // with child process's code. + _exit(127); + return false; + } else { + // fork succeeded -- this is executing in the original/parent process + + // Close the pipe FD not used by this process + close(pipe_fds[1]); + + // Log the redirected output of the child process. + // It's unfortunate that there's no standard way to obtain an istream for a file descriptor. + // As a result, we're buffering all output and logging it in one go at the end of the + // invocation, instead of logging it as it comes in. + const int child_out_fd = pipe_fds[0]; + std::string child_output; + if (!android::base::ReadFdToString(child_out_fd, &child_output)) { + PLOG(ERROR) << "Failed to capture full output of " << filename; + } + close(child_out_fd); + if (!child_output.empty()) { + // Log captured output, line by line, because LOG expects to be invoked for each line + std::istringstream in(child_output); + std::string line; + while (std::getline(in, line)) { + LOG(ERROR) << filename << ": " << line; + } + } + + // Wait for child to terminate + int status; + if (TEMP_FAILURE_RETRY(waitpid(child_pid, &status, 0)) != child_pid) { + PLOG(ERROR) << "Failed to wait for " << filename; + return false; + } + + if (WIFEXITED(status)) { + int status_code = WEXITSTATUS(status); + if (status_code == 0) { + return true; + } else { + LOG(ERROR) << filename << " exited with status " << status_code; + } + } else if (WIFSIGNALED(status)) { + LOG(ERROR) << filename << " killed by signal " << WTERMSIG(status); + } else if (WIFSTOPPED(status)) { + LOG(ERROR) << filename << " stopped by signal " << WSTOPSIG(status); + } else { + LOG(ERROR) << "waitpid for " << filename << " returned unexpected status: " << status; + } + + return false; + } +} + +bool ReadFirstLine(const char* file, std::string* line) { + line->clear(); + + std::string contents; + if (!android::base::ReadFileToString(file, &contents, true /* follow symlinks */)) { + return false; + } + std::istringstream in(contents); + std::getline(in, *line); + return true; +} + +bool FindPrecompiledSplitPolicy(std::string* file) { + file->clear(); + // If there is an odm partition, precompiled_sepolicy will be in + // odm/etc/selinux. Otherwise it will be in vendor/etc/selinux. + static constexpr const char vendor_precompiled_sepolicy[] = + "/vendor/etc/selinux/precompiled_sepolicy"; + static constexpr const char odm_precompiled_sepolicy[] = + "/odm/etc/selinux/precompiled_sepolicy"; + if (access(odm_precompiled_sepolicy, R_OK) == 0) { + *file = odm_precompiled_sepolicy; + } else if (access(vendor_precompiled_sepolicy, R_OK) == 0) { + *file = vendor_precompiled_sepolicy; + } else { + PLOG(INFO) << "No precompiled sepolicy"; + return false; + } + std::string actual_plat_id; + if (!ReadFirstLine("/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256", &actual_plat_id)) { + PLOG(INFO) << "Failed to read " + "/system/etc/selinux/plat_and_mapping_sepolicy.cil.sha256"; + return false; + } + + std::string precompiled_plat_id; + std::string precompiled_sha256 = *file + ".plat_and_mapping.sha256"; + if (!ReadFirstLine(precompiled_sha256.c_str(), &precompiled_plat_id)) { + PLOG(INFO) << "Failed to read " << precompiled_sha256; + file->clear(); + return false; + } + if ((actual_plat_id.empty()) || (actual_plat_id != precompiled_plat_id)) { + file->clear(); + return false; + } + return true; +} + +bool GetVendorMappingVersion(std::string* plat_vers) { + if (!ReadFirstLine("/vendor/etc/selinux/plat_sepolicy_vers.txt", plat_vers)) { + PLOG(ERROR) << "Failed to read /vendor/etc/selinux/plat_sepolicy_vers.txt"; + return false; + } + if (plat_vers->empty()) { + LOG(ERROR) << "No version present in plat_sepolicy_vers.txt"; + return false; + } + return true; +} + +constexpr const char plat_policy_cil_file[] = "/system/etc/selinux/plat_sepolicy.cil"; + +bool IsSplitPolicyDevice() { + return access(plat_policy_cil_file, R_OK) != -1; +} + +bool LoadSplitPolicy() { + // IMPLEMENTATION NOTE: Split policy consists of three CIL files: + // * platform -- policy needed due to logic contained in the system image, + // * non-platform -- policy needed due to logic contained in the vendor image, + // * mapping -- mapping policy which helps preserve forward-compatibility of non-platform policy + // with newer versions of platform policy. + // + // secilc is invoked to compile the above three policy files into a single monolithic policy + // file. This file is then loaded into the kernel. + + // Load precompiled policy from vendor image, if a matching policy is found there. The policy + // must match the platform policy on the system image. + std::string precompiled_sepolicy_file; + if (FindPrecompiledSplitPolicy(&precompiled_sepolicy_file)) { + unique_fd fd(open(precompiled_sepolicy_file.c_str(), O_RDONLY | O_CLOEXEC | O_BINARY)); + if (fd != -1) { + if (selinux_android_load_policy_from_fd(fd, precompiled_sepolicy_file.c_str()) < 0) { + LOG(ERROR) << "Failed to load SELinux policy from " << precompiled_sepolicy_file; + return false; + } + return true; + } + } + // No suitable precompiled policy could be loaded + + LOG(INFO) << "Compiling SELinux policy"; + + // Determine the highest policy language version supported by the kernel + set_selinuxmnt("/sys/fs/selinux"); + int max_policy_version = security_policyvers(); + if (max_policy_version == -1) { + PLOG(ERROR) << "Failed to determine highest policy version supported by kernel"; + return false; + } + + // We store the output of the compilation on /dev because this is the most convenient tmpfs + // storage mount available this early in the boot sequence. + char compiled_sepolicy[] = "/dev/sepolicy.XXXXXX"; + unique_fd compiled_sepolicy_fd(mkostemp(compiled_sepolicy, O_CLOEXEC)); + if (compiled_sepolicy_fd < 0) { + PLOG(ERROR) << "Failed to create temporary file " << compiled_sepolicy; + return false; + } + + // Determine which mapping file to include + std::string vend_plat_vers; + if (!GetVendorMappingVersion(&vend_plat_vers)) { + return false; + } + std::string mapping_file("/system/etc/selinux/mapping/" + vend_plat_vers + ".cil"); + + // vendor_sepolicy.cil and plat_pub_versioned.cil are the new design to replace + // nonplat_sepolicy.cil. + std::string plat_pub_versioned_cil_file("/vendor/etc/selinux/plat_pub_versioned.cil"); + std::string vendor_policy_cil_file("/vendor/etc/selinux/vendor_sepolicy.cil"); + + if (access(vendor_policy_cil_file.c_str(), F_OK) == -1) { + // For backward compatibility. + // TODO: remove this after no device is using nonplat_sepolicy.cil. + vendor_policy_cil_file = "/vendor/etc/selinux/nonplat_sepolicy.cil"; + plat_pub_versioned_cil_file.clear(); + } else if (access(plat_pub_versioned_cil_file.c_str(), F_OK) == -1) { + LOG(ERROR) << "Missing " << plat_pub_versioned_cil_file; + return false; + } + + // odm_sepolicy.cil is default but optional. + std::string odm_policy_cil_file("/odm/etc/selinux/odm_sepolicy.cil"); + if (access(odm_policy_cil_file.c_str(), F_OK) == -1) { + odm_policy_cil_file.clear(); + } + const std::string version_as_string = std::to_string(max_policy_version); + + // clang-format off + std::vector compile_args { + "/system/bin/secilc", + plat_policy_cil_file, + "-m", "-M", "true", "-G", "-N", + // Target the highest policy language version supported by the kernel + "-c", version_as_string.c_str(), + mapping_file.c_str(), + "-o", compiled_sepolicy, + // We don't care about file_contexts output by the compiler + "-f", "/sys/fs/selinux/null", // /dev/null is not yet available + }; + // clang-format on + + if (!plat_pub_versioned_cil_file.empty()) { + compile_args.push_back(plat_pub_versioned_cil_file.c_str()); + } + if (!vendor_policy_cil_file.empty()) { + compile_args.push_back(vendor_policy_cil_file.c_str()); + } + if (!odm_policy_cil_file.empty()) { + compile_args.push_back(odm_policy_cil_file.c_str()); + } + compile_args.push_back(nullptr); + + if (!ForkExecveAndWaitForCompletion(compile_args[0], (char**)compile_args.data())) { + unlink(compiled_sepolicy); + return false; + } + unlink(compiled_sepolicy); + + LOG(INFO) << "Loading compiled SELinux policy"; + if (selinux_android_load_policy_from_fd(compiled_sepolicy_fd, compiled_sepolicy) < 0) { + LOG(ERROR) << "Failed to load SELinux policy from " << compiled_sepolicy; + return false; + } + + return true; +} + +bool LoadMonolithicPolicy() { + LOG(VERBOSE) << "Loading SELinux policy from monolithic file"; + if (selinux_android_load_policy() < 0) { + PLOG(ERROR) << "Failed to load monolithic SELinux policy"; + return false; + } + return true; +} + +bool LoadPolicy() { + return IsSplitPolicyDevice() ? LoadSplitPolicy() : LoadMonolithicPolicy(); +} + +} // namespace + +void SelinuxInitialize() { + Timer t; + + LOG(INFO) << "Loading SELinux policy"; + if (!LoadPolicy()) { + LOG(FATAL) << "Unable to load SELinux policy"; + } + + bool kernel_enforcing = (security_getenforce() == 1); + bool is_enforcing = IsEnforcing(); + if (kernel_enforcing != is_enforcing) { + if (security_setenforce(is_enforcing)) { + PLOG(FATAL) << "security_setenforce(%s) failed" << (is_enforcing ? "true" : "false"); + } + } + + if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result) { + LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error(); + } + + // init's first stage can't set properties, so pass the time to the second stage. + setenv("INIT_SELINUX_TOOK", std::to_string(t.duration().count()).c_str(), 1); +} + +/** + * @brief 精简版本SelinuxInitialize,不做加载SELinux策略的动作,只设置selinux_mnt变量 + * + */ +void SelinuxInitializeWithoutLoadPolicy() { + Timer t; + + LOG(INFO) << "Skip Loading SELinux policy"; + set_selinuxmnt("/sys/fs/selinux"); + // init's first stage can't set properties, so pass the time to the second stage. + setenv("INIT_SELINUX_TOOK", std::to_string(t.duration().count()).c_str(), 1); +} + +// The files and directories that were created before initial sepolicy load or +// files on ramdisk need to have their security context restored to the proper +// value. This must happen before /dev is populated by ueventd. +void SelinuxRestoreContext() { + LOG(INFO) << "Running restorecon..."; +// selinux_android_restorecon("/dev", 0); +// selinux_android_restorecon("/dev/kmsg", 0); +// if constexpr (WORLD_WRITABLE_KMSG) { +// selinux_android_restorecon("/dev/kmsg_debug", 0); +// } +// selinux_android_restorecon("/dev/socket", 0); +// selinux_android_restorecon("/dev/random", 0); +// selinux_android_restorecon("/dev/urandom", 0); +// selinux_android_restorecon("/dev/__properties__", 0); +// +// selinux_android_restorecon("/plat_file_contexts", 0); +// selinux_android_restorecon("/nonplat_file_contexts", 0); +// selinux_android_restorecon("/vendor_file_contexts", 0); +// selinux_android_restorecon("/plat_property_contexts", 0); +// selinux_android_restorecon("/nonplat_property_contexts", 0); +// selinux_android_restorecon("/vendor_property_contexts", 0); +// selinux_android_restorecon("/plat_seapp_contexts", 0); +// selinux_android_restorecon("/nonplat_seapp_contexts", 0); +// selinux_android_restorecon("/vendor_seapp_contexts", 0); +// selinux_android_restorecon("/plat_service_contexts", 0); +// selinux_android_restorecon("/nonplat_service_contexts", 0); +// selinux_android_restorecon("/vendor_service_contexts", 0); +// selinux_android_restorecon("/plat_hwservice_contexts", 0); +// selinux_android_restorecon("/nonplat_hwservice_contexts", 0); +// selinux_android_restorecon("/vendor_hwservice_contexts", 0); +// selinux_android_restorecon("/sepolicy", 0); +// selinux_android_restorecon("/vndservice_contexts", 0); +// +// selinux_android_restorecon("/dev/block", SELINUX_ANDROID_RESTORECON_RECURSE); +// selinux_android_restorecon("/dev/device-mapper", 0); +// +// selinux_android_restorecon("/sbin/mke2fs_static", 0); +// selinux_android_restorecon("/sbin/e2fsdroid_static", 0); +// +// selinux_android_restorecon("/sbin/mkfs.f2fs", 0); +// selinux_android_restorecon("/sbin/sload.f2fs", 0); + + // 容器环境,需要全部restorecon一遍,不然安全上下文件还是容器环境下的;过程比较耗时,约1分钟左右;TBD:此处有必要进一步优化。 + selinux_android_restorecon("/", SELINUX_ANDROID_RESTORECON_RECURSE); + selinux_android_restorecon("/dev", SELINUX_ANDROID_RESTORECON_RECURSE); +} + +// This function sets up SELinux logging to be written to kmsg, to match init's logging. +void SelinuxSetupKernelLogging() { + selinux_callback cb; + cb.func_log = selinux_klog_callback; + selinux_set_callback(SELINUX_CB_LOG, cb); +} + +// This function checks whether the sepolicy supports vendor init. +bool SelinuxHasVendorInit() { + if (!is_selinux_enabled()) { + return false; + } + if (!IsSplitPolicyDevice()) { + // If this device does not split sepolicy files, vendor_init will be available in the latest + // monolithic sepolicy file. + return true; + } + + std::string version; + if (!GetVendorMappingVersion(&version)) { + // Return true as the default if we failed to load the vendor sepolicy version. + return true; + } + + int major_version; + std::string major_version_str(version, 0, version.find('.')); + if (!ParseInt(major_version_str, &major_version)) { + PLOG(ERROR) << "Failed to parse the vendor sepolicy major version " << major_version_str; + // Return true as the default if we failed to parse the major version. + return true; + } + + return major_version >= 28; +} + +// selinux_android_file_context_handle() takes on the order of 10+ms to run, so we want to cache +// its value. selinux_android_restorecon() also needs an sehandle for file context look up. It +// will create and store its own copy, but selinux_android_set_sehandle() can be used to provide +// one, thus eliminating an extra call to selinux_android_file_context_handle(). +void SelabelInitialize() { + sehandle = selinux_android_file_context_handle(); + selinux_android_set_sehandle(sehandle); +} + +// A C++ wrapper around selabel_lookup() using the cached sehandle. +// If sehandle is null, this returns success with an empty context. +bool SelabelLookupFileContext(const std::string& key, int type, std::string* result) { + result->clear(); + + if (!sehandle) return true; + + char* context; + if (selabel_lookup(sehandle, &context, key.c_str(), type) != 0) { + return false; + } + *result = context; + free(context); + return true; +} + +// A C++ wrapper around selabel_lookup_best_match() using the cached sehandle. +// If sehandle is null, this returns success with an empty context. +bool SelabelLookupFileContextBestMatch(const std::string& key, + const std::vector& aliases, int type, + std::string* result) { + result->clear(); + + if (!sehandle) return true; + + std::vector c_aliases; + for (const auto& alias : aliases) { + c_aliases.emplace_back(alias.c_str()); + } + c_aliases.emplace_back(nullptr); + + char* context; + if (selabel_lookup_best_match(sehandle, &context, key.c_str(), &c_aliases[0], type) != 0) { + return false; + } + *result = context; + free(context); + return true; +} + +} // namespace init +} // namespace android diff --git a/aosp/system/core/init/selinux.h b/aosp/system/core/init/selinux.h new file mode 100644 index 000000000..497fca1fe --- /dev/null +++ b/aosp/system/core/init/selinux.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _INIT_SELINUX_H +#define _INIT_SELINUX_H + +#include +#include + +namespace android { +namespace init { + +void SelinuxInitialize(); +void SelinuxInitializeWithoutLoadPolicy(); +void SelinuxRestoreContext(); + +void SelinuxSetupKernelLogging(); +bool SelinuxHasVendorInit(); + +void SelabelInitialize(); +bool SelabelLookupFileContext(const std::string& key, int type, std::string* result); +bool SelabelLookupFileContextBestMatch(const std::string& key, + const std::vector& aliases, int type, + std::string* result); + +} // namespace init +} // namespace android + +#endif diff --git a/aosp/system/core/init/service.cpp b/aosp/system/core/init/service.cpp new file mode 100644 index 000000000..1378a9482 --- /dev/null +++ b/aosp/system/core/init/service.cpp @@ -0,0 +1,1244 @@ +/* + * Copyright (C) 2015 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "service.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rlimit_parser.h" +#include "util.h" + +#if defined(__ANDROID__) +#include + +#include + +#include "init.h" +#include "property_service.h" +#else +#include "host_init_stubs.h" +#endif + +using android::base::boot_clock; +using android::base::GetProperty; +using android::base::Join; +using android::base::ParseInt; +using android::base::StartsWith; +using android::base::StringPrintf; +using android::base::unique_fd; +using android::base::WriteStringToFile; + +namespace android { +namespace init { + +static Result ComputeContextFromExecutable(const std::string& service_path) { + + std::string computed_context; + char* raw_con = nullptr; + char* raw_filecon = nullptr; + + if (getcon(&raw_con) == -1) { + return Error() << "Could not get security context"; + } + std::unique_ptr mycon(raw_con); + + if (getfilecon(service_path.c_str(), &raw_filecon) == -1) { + return Error() << "Could not get file context"; + } + std::unique_ptr filecon(raw_filecon); + + char* new_con = nullptr; + int rc = security_compute_create(mycon.get(), filecon.get(), + string_to_security_class("process"), &new_con); + if (rc == 0) { + computed_context = new_con; + free(new_con); + } + if (rc == 0 && computed_context == mycon.get()) { + return Error() << "File " << service_path << "(labeled \"" << filecon.get() + << "\") has incorrect label or no domain transition from " << mycon.get() + << " to another SELinux domain defined. Have you configured your " + "service correctly? https://source.android.com/security/selinux/" + "device-policy#label_new_services_and_address_denials"; + } + if (rc < 0) { + return Error() << "Could not get process context"; + } + return computed_context; +} + +Result Service::SetUpMountNamespace() const { + constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID; + + // Recursively remount / as slave like zygote does so unmounting and mounting /proc + // doesn't interfere with the parent namespace's /proc mount. This will also + // prevent any other mounts/unmounts initiated by the service from interfering + // with the parent namespace but will still allow mount events from the parent + // namespace to propagate to the child. + if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) { + return ErrnoError() << "Could not remount(/) recursively as slave"; + } + + // umount() then mount() /proc and/or /sys + // Note that it is not sufficient to mount with MS_REMOUNT. + if (namespace_flags_ & CLONE_NEWPID) { + if (umount("/proc") == -1) { + return ErrnoError() << "Could not umount(/proc)"; + } + if (mount("", "/proc", "proc", kSafeFlags, "") == -1) { + return ErrnoError() << "Could not mount(/proc)"; + } + } + bool remount_sys = std::any_of(namespaces_to_enter_.begin(), namespaces_to_enter_.end(), + [](const auto& entry) { return entry.first == CLONE_NEWNET; }); + if (remount_sys) { + if (umount2("/sys", MNT_DETACH) == -1) { + return ErrnoError() << "Could not umount(/sys)"; + } + if (mount("", "/sys", "sys", kSafeFlags, "") == -1) { + return ErrnoError() << "Could not mount(/sys)"; + } + } + return Success(); +} + +Result Service::SetUpPidNamespace() const { + if (prctl(PR_SET_NAME, name_.c_str()) == -1) { + return ErrnoError() << "Could not set name"; + } + + pid_t child_pid = fork(); + if (child_pid == -1) { + return ErrnoError() << "Could not fork init inside the PID namespace"; + } + + if (child_pid > 0) { + // So that we exit with the right status. + static int init_exitstatus = 0; + signal(SIGTERM, [](int) { _exit(init_exitstatus); }); + + pid_t waited_pid; + int status; + while ((waited_pid = wait(&status)) > 0) { + // This loop will end when there are no processes left inside the + // PID namespace or when the init process inside the PID namespace + // gets a signal. + if (waited_pid == child_pid) { + init_exitstatus = status; + } + } + if (!WIFEXITED(init_exitstatus)) { + _exit(EXIT_FAILURE); + } + _exit(WEXITSTATUS(init_exitstatus)); + } + return Success(); +} + +Result Service::EnterNamespaces() const { + for (const auto& [nstype, path] : namespaces_to_enter_) { + + auto fd = unique_fd{open(path.c_str(), O_RDONLY | O_CLOEXEC)}; + if (!fd) { + return ErrnoError() << "Could not open namespace at " << path; + } + if (setns(fd, nstype) == -1) { + return ErrnoError() << "Could not setns() namespace at " << path; + } + } + return Success(); +} + +static bool ExpandArgsAndExecv(const std::vector& args) { + std::vector expanded_args; + std::vector c_strings; + + expanded_args.resize(args.size()); + c_strings.push_back(const_cast(args[0].data())); + for (std::size_t i = 1; i < args.size(); ++i) { + if (!expand_props(args[i], &expanded_args[i])) { + LOG(FATAL) << args[0] << ": cannot expand '" << args[i] << "'"; + } + c_strings.push_back(expanded_args[i].data()); + } + c_strings.push_back(nullptr); + return execv(c_strings[0], c_strings.data()) == 0; +} + +unsigned long Service::next_start_order_ = 1; +bool Service::is_exec_service_running_ = false; + +Service::Service(const std::string& name, Subcontext* subcontext_for_restart_commands, + const std::vector& args) + : Service(name, 0, 0, 0, {}, 0, 0, "", subcontext_for_restart_commands, args) {} + +Service::Service(const std::string& name, unsigned flags, uid_t uid, gid_t gid, + const std::vector& supp_gids, const CapSet& capabilities, + unsigned namespace_flags, const std::string& seclabel, + Subcontext* subcontext_for_restart_commands, const std::vector& args) + : name_(name), + classnames_({"default"}), + flags_(flags), + pid_(0), + crash_count_(0), + uid_(uid), + gid_(gid), + supp_gids_(supp_gids), + capabilities_(capabilities), + namespace_flags_(namespace_flags), + seclabel_(seclabel), + onrestart_(false, subcontext_for_restart_commands, "", 0, + "onrestart", {}), + keychord_id_(0), + ioprio_class_(IoSchedClass_NONE), + ioprio_pri_(0), + priority_(0), + oom_score_adjust_(-1000), + swappiness_(-1), + soft_limit_in_bytes_(-1), + limit_in_bytes_(-1), + start_order_(0), + args_(args) {} + +void Service::NotifyStateChange(const std::string& new_state) const { + if ((flags_ & SVC_TEMPORARY) != 0) { + // Services created by 'exec' are temporary and don't have properties tracking their state. + return; + } + + std::string prop_name = "init.svc." + name_; + property_set(prop_name, new_state); + + if (new_state == "running") { + uint64_t start_ns = time_started_.time_since_epoch().count(); + std::string boottime_property = "ro.boottime." + name_; + if (GetProperty(boottime_property, "").empty()) { + property_set(boottime_property, std::to_string(start_ns)); + } + } +} + +void Service::KillProcessGroup(int signal) { + // If we've already seen a successful result from killProcessGroup*(), then we have removed + // the cgroup already and calling these functions a second time will simply result in an error. + // This is true regardless of which signal was sent. + // These functions handle their own logging, so no additional logging is needed. + if (!process_cgroup_empty_) { + LOG(INFO) << "Sending signal " << signal << " to service '" << name_ << "' (pid " << pid_ + << ") process group..."; + int r; + if (signal == SIGTERM) { + r = killProcessGroupOnce(uid_, pid_, signal); + } else { + r = killProcessGroup(uid_, pid_, signal); + } + + if (r == 0) process_cgroup_empty_ = true; + } +} + +void Service::SetProcessAttributes() { + for (const auto& rlimit : rlimits_) { + if (setrlimit(rlimit.first, &rlimit.second) == -1) { + LOG(FATAL) << StringPrintf("setrlimit(%d, {rlim_cur=%ld, rlim_max=%ld}) failed", + rlimit.first, rlimit.second.rlim_cur, rlimit.second.rlim_max); + } + } + // Keep capabilites on uid change. + if (capabilities_.any() && uid_) { + // If Android is running in a container, some securebits might already + // be locked, so don't change those. + unsigned long securebits = prctl(PR_GET_SECUREBITS); + if (securebits == -1UL) { + PLOG(FATAL) << "prctl(PR_GET_SECUREBITS) failed for " << name_; + } + securebits |= SECBIT_KEEP_CAPS | SECBIT_KEEP_CAPS_LOCKED; + if (prctl(PR_SET_SECUREBITS, securebits) != 0) { + PLOG(FATAL) << "prctl(PR_SET_SECUREBITS) failed for " << name_; + } + } + + // TODO: work out why this fails for `console` then upgrade to FATAL. + if (setpgid(0, getpid()) == -1) PLOG(ERROR) << "setpgid failed for " << name_; + + if (gid_) { + if (setgid(gid_) != 0) { + PLOG(FATAL) << "setgid failed for " << name_; + } + } + if (setgroups(supp_gids_.size(), &supp_gids_[0]) != 0) { + PLOG(FATAL) << "setgroups failed for " << name_; + } + if (uid_) { + if (setuid(uid_) != 0) { + PLOG(FATAL) << "setuid failed for " << name_; + } + } + + if (is_selinux_enabled() && !seclabel_.empty()) { + if (setexeccon(seclabel_.c_str()) < 0) { + PLOG(FATAL) << "cannot setexeccon('" << seclabel_ << "') for " << name_; + } + } + + if (priority_ != 0) { + if (setpriority(PRIO_PROCESS, 0, priority_) != 0) { + PLOG(FATAL) << "setpriority failed for " << name_; + } + } + if (capabilities_.any()) { + if (!SetCapsForExec(capabilities_)) { + LOG(FATAL) << "cannot set capabilities for " << name_; + } + } else if (uid_) { + // Inheritable caps can be non-zero when running in a container. + if (!DropInheritableCaps()) { + LOG(FATAL) << "cannot drop inheritable caps for " << name_; + } + } +} + +void Service::Reap(const siginfo_t& siginfo) { + if (!(flags_ & SVC_ONESHOT) || (flags_ & SVC_RESTART)) { + KillProcessGroup(SIGKILL); + } + + // Remove any descriptor resources we may have created. + std::for_each(descriptors_.begin(), descriptors_.end(), + std::bind(&DescriptorInfo::Clean, std::placeholders::_1)); + + for (const auto& f : reap_callbacks_) { + f(siginfo); + } + + if (flags_ & SVC_EXEC) UnSetExec(); + + if (flags_ & SVC_TEMPORARY) return; + + pid_ = 0; + flags_ &= (~SVC_RUNNING); + start_order_ = 0; + + // Oneshot processes go into the disabled state on exit, + // except when manually restarted. + if ((flags_ & SVC_ONESHOT) && !(flags_ & SVC_RESTART)) { + flags_ |= SVC_DISABLED; + } + + // Disabled and reset processes do not get restarted automatically. + if (flags_ & (SVC_DISABLED | SVC_RESET)) { + NotifyStateChange("stopped"); + return; + } + + // If we crash > 4 times in 4 minutes, reboot into recovery. + boot_clock::time_point now = boot_clock::now(); + if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) { + if (now < time_crashed_ + 4min) { + if (++crash_count_ > 4) { + LOG(FATAL) << "critical process '" << name_ << "' exited 4 times in 4 minutes"; + } + } else { + time_crashed_ = now; + crash_count_ = 1; + } + } + + flags_ &= (~SVC_RESTART); + flags_ |= SVC_RESTARTING; + + // Execute all onrestart commands for this service. + onrestart_.ExecuteAllCommands(); + + NotifyStateChange("restarting"); + return; +} + +void Service::DumpState() const { + LOG(INFO) << "service " << name_; + LOG(INFO) << " class '" << Join(classnames_, " ") << "'"; + LOG(INFO) << " exec " << Join(args_, " "); + std::for_each(descriptors_.begin(), descriptors_.end(), + [] (const auto& info) { LOG(INFO) << *info; }); +} + +Result Service::ParseCapabilities(const std::vector& args) { + capabilities_ = 0; + + if (!CapAmbientSupported()) { + return Error() + << "capabilities requested but the kernel does not support ambient capabilities"; + } + + unsigned int last_valid_cap = GetLastValidCap(); + if (last_valid_cap >= capabilities_.size()) { + LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP"; + } + + for (size_t i = 1; i < args.size(); i++) { + const std::string& arg = args[i]; + int res = LookupCap(arg); + if (res < 0) { + return Error() << StringPrintf("invalid capability '%s'", arg.c_str()); + } + unsigned int cap = static_cast(res); // |res| is >= 0. + if (cap > last_valid_cap) { + return Error() << StringPrintf("capability '%s' not supported by the kernel", + arg.c_str()); + } + capabilities_[cap] = true; + } + return Success(); +} + +Result Service::ParseClass(const std::vector& args) { + classnames_ = std::set(args.begin() + 1, args.end()); + return Success(); +} + +Result Service::ParseConsole(const std::vector& args) { + flags_ |= SVC_CONSOLE; + console_ = args.size() > 1 ? "/dev/" + args[1] : ""; + return Success(); +} + +Result Service::ParseCritical(const std::vector& args) { + flags_ |= SVC_CRITICAL; + return Success(); +} + +Result Service::ParseDisabled(const std::vector& args) { + flags_ |= SVC_DISABLED; + flags_ |= SVC_RC_DISABLED; + return Success(); +} + +Result Service::ParseEnterNamespace(const std::vector& args) { + if (args[1] != "net") { + return Error() << "Init only supports entering network namespaces"; + } + if (!namespaces_to_enter_.empty()) { + return Error() << "Only one network namespace may be entered"; + } + // Network namespaces require that /sys is remounted, otherwise the old adapters will still be + // present. Therefore, they also require mount namespaces. + namespace_flags_ |= CLONE_NEWNS; + namespaces_to_enter_.emplace_back(CLONE_NEWNET, args[2]); + return Success(); +} + +Result Service::ParseGroup(const std::vector& args) { + auto gid = DecodeUid(args[1]); + if (!gid) { + return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error(); + } + gid_ = *gid; + + for (std::size_t n = 2; n < args.size(); n++) { + gid = DecodeUid(args[n]); + if (!gid) { + return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error(); + } + supp_gids_.emplace_back(*gid); + } + return Success(); +} + +Result Service::ParsePriority(const std::vector& args) { + priority_ = 0; + if (!ParseInt(args[1], &priority_, + static_cast(ANDROID_PRIORITY_HIGHEST), // highest is negative + static_cast(ANDROID_PRIORITY_LOWEST))) { + return Error() << StringPrintf("process priority value must be range %d - %d", + ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST); + } + return Success(); +} + +Result Service::ParseInterface(const std::vector& args) { + const std::string& interface_name = args[1]; + const std::string& instance_name = args[2]; + + const FQName fq_name = FQName(interface_name); + if (!fq_name.isValid()) { + return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'"; + } + + if (!fq_name.isFullyQualified()) { + return Error() << "Interface name not fully-qualified '" << interface_name << "'"; + } + + if (fq_name.isValidValueName()) { + return Error() << "Interface name must not be a value name '" << interface_name << "'"; + } + + const std::string fullname = interface_name + "/" + instance_name; + + for (const auto& svc : ServiceList::GetInstance()) { + if (svc->interfaces().count(fullname) > 0) { + return Error() << "Interface '" << fullname << "' redefined in " << name() + << " but is already defined by " << svc->name(); + } + } + + interfaces_.insert(fullname); + + return Success(); +} + +Result Service::ParseIoprio(const std::vector& args) { + if (!ParseInt(args[2], &ioprio_pri_, 0, 7)) { + return Error() << "priority value must be range 0 - 7"; + } + + if (args[1] == "rt") { + ioprio_class_ = IoSchedClass_RT; + } else if (args[1] == "be") { + ioprio_class_ = IoSchedClass_BE; + } else if (args[1] == "idle") { + ioprio_class_ = IoSchedClass_IDLE; + } else { + return Error() << "ioprio option usage: ioprio <0-7>"; + } + + return Success(); +} + +Result Service::ParseKeycodes(const std::vector& args) { + for (std::size_t i = 1; i < args.size(); i++) { + int code; + if (ParseInt(args[i], &code)) { + keycodes_.emplace_back(code); + } else { + LOG(WARNING) << "ignoring invalid keycode: " << args[i]; + } + } + return Success(); +} + +Result Service::ParseOneshot(const std::vector& args) { + flags_ |= SVC_ONESHOT; + return Success(); +} + +Result Service::ParseOnrestart(const std::vector& args) { + std::vector str_args(args.begin() + 1, args.end()); + int line = onrestart_.NumCommands() + 1; + if (auto result = onrestart_.AddCommand(str_args, line); !result) { + return Error() << "cannot add Onrestart command: " << result.error(); + } + return Success(); +} + +Result Service::ParseNamespace(const std::vector& args) { + for (size_t i = 1; i < args.size(); i++) { + if (args[i] == "pid") { + namespace_flags_ |= CLONE_NEWPID; + // PID namespaces require mount namespaces. + namespace_flags_ |= CLONE_NEWNS; + } else if (args[i] == "mnt") { + namespace_flags_ |= CLONE_NEWNS; + } else { + return Error() << "namespace must be 'pid' or 'mnt'"; + } + } + return Success(); +} + +Result Service::ParseOomScoreAdjust(const std::vector& args) { + if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) { + return Error() << "oom_score_adjust value must be in range -1000 - +1000"; + } + return Success(); +} + +Result Service::ParseOverride(const std::vector& args) { + override_ = true; + return Success(); +} + +Result Service::ParseMemcgSwappiness(const std::vector& args) { + if (!ParseInt(args[1], &swappiness_, 0)) { + return Error() << "swappiness value must be equal or greater than 0"; + } + return Success(); +} + +Result Service::ParseMemcgLimitInBytes(const std::vector& args) { + if (!ParseInt(args[1], &limit_in_bytes_, 0)) { + return Error() << "limit_in_bytes value must be equal or greater than 0"; + } + return Success(); +} + +Result Service::ParseMemcgSoftLimitInBytes(const std::vector& args) { + if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) { + return Error() << "soft_limit_in_bytes value must be equal or greater than 0"; + } + return Success(); +} + +Result Service::ParseProcessRlimit(const std::vector& args) { + auto rlimit = ParseRlimit(args); + if (!rlimit) return rlimit.error(); + + rlimits_.emplace_back(*rlimit); + return Success(); +} + +Result Service::ParseSeclabel(const std::vector& args) { + seclabel_ = args[1]; + return Success(); +} + +Result Service::ParseSetenv(const std::vector& args) { + environment_vars_.emplace_back(args[1], args[2]); + return Success(); +} + +Result Service::ParseShutdown(const std::vector& args) { + if (args[1] == "critical") { + flags_ |= SVC_SHUTDOWN_CRITICAL; + return Success(); + } + return Error() << "Invalid shutdown option"; +} + +template +Result Service::AddDescriptor(const std::vector& args) { + int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1; + Result uid = 0; + Result gid = 0; + std::string context = args.size() > 6 ? args[6] : ""; + + if (args.size() > 4) { + uid = DecodeUid(args[4]); + if (!uid) { + return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error(); + } + } + + if (args.size() > 5) { + gid = DecodeUid(args[5]); + if (!gid) { + return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error(); + } + } + + auto descriptor = std::make_unique(args[1], args[2], *uid, *gid, perm, context); + + auto old = + std::find_if(descriptors_.begin(), descriptors_.end(), + [&descriptor] (const auto& other) { return descriptor.get() == other.get(); }); + + if (old != descriptors_.end()) { + return Error() << "duplicate descriptor " << args[1] << " " << args[2]; + } + + descriptors_.emplace_back(std::move(descriptor)); + return Success(); +} + +// name type perm [ uid gid context ] +Result Service::ParseSocket(const std::vector& args) { + if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") && + !StartsWith(args[2], "seqpacket")) { + return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'"; + } + return AddDescriptor(args); +} + +// name type perm [ uid gid context ] +Result Service::ParseFile(const std::vector& args) { + if (args[2] != "r" && args[2] != "w" && args[2] != "rw") { + return Error() << "file type must be 'r', 'w' or 'rw'"; + } + if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) { + return Error() << "file name must not be relative"; + } + return AddDescriptor(args); +} + +Result Service::ParseUser(const std::vector& args) { + auto uid = DecodeUid(args[1]); + if (!uid) { + return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error(); + } + uid_ = *uid; + return Success(); +} + +Result Service::ParseWritepid(const std::vector& args) { + writepid_files_.assign(args.begin() + 1, args.end()); + return Success(); +} + +class Service::OptionParserMap : public KeywordMap { + public: + OptionParserMap() {} + + private: + const Map& map() const override; +}; + +const Service::OptionParserMap::Map& Service::OptionParserMap::map() const { + constexpr std::size_t kMax = std::numeric_limits::max(); + // clang-format off + static const Map option_parsers = { + {"capabilities", + {1, kMax, &Service::ParseCapabilities}}, + {"class", {1, kMax, &Service::ParseClass}}, + {"console", {0, 1, &Service::ParseConsole}}, + {"critical", {0, 0, &Service::ParseCritical}}, + {"disabled", {0, 0, &Service::ParseDisabled}}, + {"enter_namespace", + {2, 2, &Service::ParseEnterNamespace}}, + {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}}, + {"interface", {2, 2, &Service::ParseInterface}}, + {"ioprio", {2, 2, &Service::ParseIoprio}}, + {"priority", {1, 1, &Service::ParsePriority}}, + {"keycodes", {1, kMax, &Service::ParseKeycodes}}, + {"oneshot", {0, 0, &Service::ParseOneshot}}, + {"onrestart", {1, kMax, &Service::ParseOnrestart}}, + {"override", {0, 0, &Service::ParseOverride}}, + {"oom_score_adjust", + {1, 1, &Service::ParseOomScoreAdjust}}, + {"memcg.swappiness", + {1, 1, &Service::ParseMemcgSwappiness}}, + {"memcg.soft_limit_in_bytes", + {1, 1, &Service::ParseMemcgSoftLimitInBytes}}, + {"memcg.limit_in_bytes", + {1, 1, &Service::ParseMemcgLimitInBytes}}, + {"namespace", {1, 2, &Service::ParseNamespace}}, + {"rlimit", {3, 3, &Service::ParseProcessRlimit}}, + {"seclabel", {1, 1, &Service::ParseSeclabel}}, + {"setenv", {2, 2, &Service::ParseSetenv}}, + {"shutdown", {1, 1, &Service::ParseShutdown}}, + {"socket", {3, 6, &Service::ParseSocket}}, + {"file", {2, 2, &Service::ParseFile}}, + {"user", {1, 1, &Service::ParseUser}}, + {"writepid", {1, kMax, &Service::ParseWritepid}}, + }; + // clang-format on + return option_parsers; +} + +Result Service::ParseLine(const std::vector& args) { + static const OptionParserMap parser_map; + auto parser = parser_map.FindFunction(args); + + if (!parser) return parser.error(); + + return std::invoke(*parser, this, args); +} + +Result Service::ExecStart() { + flags_ |= SVC_ONESHOT; + + if (auto result = Start(); !result) { + return result; + } + + flags_ |= SVC_EXEC; + is_exec_service_running_ = true; + + LOG(INFO) << "SVC_EXEC pid " << pid_ << " (uid " << uid_ << " gid " << gid_ << "+" + << supp_gids_.size() << " context " << (!seclabel_.empty() ? seclabel_ : "default") + << ") started; waiting..."; + + return Success(); +} + +Result Service::Start() { + bool disabled = (flags_ & (SVC_DISABLED | SVC_RESET)); + // Starting a service removes it from the disabled or reset state and + // immediately takes it out of the restarting state if it was in there. + flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START)); + + // Running processes require no additional work --- if they're in the + // process of exiting, we've ensured that they will immediately restart + // on exit, unless they are ONESHOT. For ONESHOT service, if it's in + // stopping status, we just set SVC_RESTART flag so it will get restarted + // in Reap(). + if (flags_ & SVC_RUNNING) { + if ((flags_ & SVC_ONESHOT) && disabled) { + flags_ |= SVC_RESTART; + } + // It is not an error to try to start a service that is already running. + return Success(); + } + + bool needs_console = (flags_ & SVC_CONSOLE); + if (needs_console) { + if (console_.empty()) { + console_ = default_console; + } + + // Make sure that open call succeeds to ensure a console driver is + // properly registered for the device node + int console_fd = open(console_.c_str(), O_RDWR | O_CLOEXEC); + if (console_fd < 0) { + flags_ |= SVC_DISABLED; + return ErrnoError() << "Couldn't open console '" << console_ << "'"; + } + close(console_fd); + } + + struct stat sb; + if (stat(args_[0].c_str(), &sb) == -1) { + flags_ |= SVC_DISABLED; + return ErrnoError() << "Cannot find '" << args_[0] << "'"; + } + + std::string scon; + if (is_selinux_enabled()) { + if (!seclabel_.empty()) { + scon = seclabel_; + } else { + auto result = ComputeContextFromExecutable(args_[0]); + if (!result) { + LOG(ERROR) << "starting service " << name_ << " failed : " << result.error(); + // return result.error(); + } else { + scon = *result; + } + } + } + LOG(INFO) << "starting service '" << name_ << "' with scontext: " << scon; + pid_t pid = -1; + if (namespace_flags_) { + pid = clone(nullptr, nullptr, namespace_flags_ | SIGCHLD, nullptr); + } else { + pid = fork(); + } + + if (pid == 0) { + umask(077); +#if 0 + LOG(FATAL) << "EnterNamespaces"; + if (auto result = EnterNamespaces(); !result) { + LOG(FATAL) << "Service '" << name_ << "' could not enter namespaces: " << result.error(); + } + LOG(FATAL) << "namespace_flags_ = " << namespace_flags_; + if (namespace_flags_ & CLONE_NEWNS) { + if (auto result = SetUpMountNamespace(); !result) { + LOG(FATAL) << "Service '" << name_ + << "' could not set up mount namespace: " << result.error(); + } + } + + LOG(FATAL) << "namespace_flags_ = " << namespace_flags_; + if (namespace_flags_ & CLONE_NEWPID) { + // This will fork again to run an init process inside the PID + // namespace. + if (auto result = SetUpPidNamespace(); !result) { + LOG(FATAL) << "Service '" << name_ + << "' could not set up PID namespace: " << result.error(); + } + } +#endif + for (const auto& [key, value] : environment_vars_) { + LOG(FATAL) << "key = " << key << " value = " << value; + setenv(key.c_str(), value.c_str(), 1); + } + std::for_each(descriptors_.begin(), descriptors_.end(), + std::bind(&DescriptorInfo::CreateAndPublish, std::placeholders::_1, scon)); + + // See if there were "writepid" instructions to write to files under /dev/cpuset/. + auto cpuset_predicate = [](const std::string& path) { + return StartsWith(path, "/dev/cpuset/"); + }; + auto iter = std::find_if(writepid_files_.begin(), writepid_files_.end(), cpuset_predicate); + if (iter == writepid_files_.end()) { + // There were no "writepid" instructions for cpusets, check if the system default + // cpuset is specified to be used for the process. + std::string default_cpuset = GetProperty("ro.cpuset.default", ""); + if (!default_cpuset.empty()) { + // Make sure the cpuset name starts and ends with '/'. + // A single '/' means the 'root' cpuset. + if (default_cpuset.front() != '/') { + default_cpuset.insert(0, 1, '/'); + } + if (default_cpuset.back() != '/') { + default_cpuset.push_back('/'); + } + writepid_files_.push_back( + StringPrintf("/dev/cpuset%stasks", default_cpuset.c_str())); + } + } + std::string pid_str = std::to_string(getpid()); + for (const auto& file : writepid_files_) { + if (!WriteStringToFile(pid_str, file)) { + PLOG(ERROR) << "couldn't write " << pid_str << " to " << file; + } + } + + if (ioprio_class_ != IoSchedClass_NONE) { + if (android_set_ioprio(getpid(), ioprio_class_, ioprio_pri_)) { + PLOG(ERROR) << "failed to set pid " << getpid() + << " ioprio=" << ioprio_class_ << "," << ioprio_pri_; + } + } + + if (needs_console) { + setsid(); + OpenConsole(); + } else { + ZapStdio(); + } + + // As requested, set our gid, supplemental gids, uid, context, and + // priority. Aborts on failure. + SetProcessAttributes(); + + if (!ExpandArgsAndExecv(args_)) { + PLOG(ERROR) << "cannot execve('" << args_[0] << "')"; + } + + _exit(127); + } + + if (pid < 0) { + pid_ = 0; + return ErrnoError() << "Failed to fork"; + } + + if (oom_score_adjust_ != -1000) { + std::string oom_str = std::to_string(oom_score_adjust_); + std::string oom_file = StringPrintf("/proc/%d/oom_score_adj", pid); + if (!WriteStringToFile(oom_str, oom_file)) { + PLOG(ERROR) << "couldn't write oom_score_adj: " << strerror(errno); + } + } + + time_started_ = boot_clock::now(); + pid_ = pid; + flags_ |= SVC_RUNNING; + start_order_ = next_start_order_++; + process_cgroup_empty_ = false; + + errno = -createProcessGroup(uid_, pid_); + if (errno != 0) { + PLOG(ERROR) << "createProcessGroup(" << uid_ << ", " << pid_ << ") failed for service '" + << name_ << "'"; + } else { + if (swappiness_ != -1) { + if (!setProcessGroupSwappiness(uid_, pid_, swappiness_)) { + PLOG(ERROR) << "setProcessGroupSwappiness failed"; + } + } + + if (soft_limit_in_bytes_ != -1) { + if (!setProcessGroupSoftLimit(uid_, pid_, soft_limit_in_bytes_)) { + PLOG(ERROR) << "setProcessGroupSoftLimit failed"; + } + } + + if (limit_in_bytes_ != -1) { + if (!setProcessGroupLimit(uid_, pid_, limit_in_bytes_)) { + PLOG(ERROR) << "setProcessGroupLimit failed"; + } + } + } + + NotifyStateChange("running"); + return Success(); +} + +Result Service::StartIfNotDisabled() { + if (!(flags_ & SVC_DISABLED)) { + return Start(); + } else { + flags_ |= SVC_DISABLED_START; + } + return Success(); +} + +Result Service::Enable() { + flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED); + if (flags_ & SVC_DISABLED_START) { + return Start(); + } + return Success(); +} + +void Service::Reset() { + StopOrReset(SVC_RESET); +} + +void Service::Stop() { + StopOrReset(SVC_DISABLED); +} + +void Service::Terminate() { + flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START); + flags_ |= SVC_DISABLED; + if (pid_) { + KillProcessGroup(SIGTERM); + NotifyStateChange("stopping"); + } +} + +void Service::Restart() { + if (flags_ & SVC_RUNNING) { + /* Stop, wait, then start the service. */ + StopOrReset(SVC_RESTART); + } else if (!(flags_ & SVC_RESTARTING)) { + /* Just start the service since it's not running. */ + if (auto result = Start(); !result) { + LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error(); + } + } /* else: Service is restarting anyways. */ +} + +// The how field should be either SVC_DISABLED, SVC_RESET, or SVC_RESTART. +void Service::StopOrReset(int how) { + // The service is still SVC_RUNNING until its process exits, but if it has + // already exited it shoudn't attempt a restart yet. + flags_ &= ~(SVC_RESTARTING | SVC_DISABLED_START); + + if ((how != SVC_DISABLED) && (how != SVC_RESET) && (how != SVC_RESTART)) { + // An illegal flag: default to SVC_DISABLED. + how = SVC_DISABLED; + } + + // If the service has not yet started, prevent it from auto-starting with its class. + if (how == SVC_RESET) { + flags_ |= (flags_ & SVC_RC_DISABLED) ? SVC_DISABLED : SVC_RESET; + } else { + flags_ |= how; + } + // Make sure it's in right status when a restart immediately follow a + // stop/reset or vice versa. + if (how == SVC_RESTART) { + flags_ &= (~(SVC_DISABLED | SVC_RESET)); + } else { + flags_ &= (~SVC_RESTART); + } + + if (pid_) { + KillProcessGroup(SIGKILL); + NotifyStateChange("stopping"); + } else { + NotifyStateChange("stopped"); + } +} + +void Service::ZapStdio() const { + int fd; + fd = open("/dev/null", O_RDWR); + dup2(fd, 0); + dup2(fd, 1); + dup2(fd, 2); + close(fd); +} + +void Service::OpenConsole() const { + int fd = open(console_.c_str(), O_RDWR); + if (fd == -1) fd = open("/dev/null", O_RDWR); + ioctl(fd, TIOCSCTTY, 0); + dup2(fd, 0); + dup2(fd, 1); + dup2(fd, 2); + close(fd); +} + +ServiceList::ServiceList() {} + +ServiceList& ServiceList::GetInstance() { + static ServiceList instance; + return instance; +} + +void ServiceList::AddService(std::unique_ptr service) { + services_.emplace_back(std::move(service)); +} + +std::unique_ptr Service::MakeTemporaryOneshotService(const std::vector& args) { + // Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS... + // SECLABEL can be a - to denote default + std::size_t command_arg = 1; + for (std::size_t i = 1; i < args.size(); ++i) { + if (args[i] == "--") { + command_arg = i + 1; + break; + } + } + if (command_arg > 4 + NR_SVC_SUPP_GIDS) { + LOG(ERROR) << "exec called with too many supplementary group ids"; + return nullptr; + } + + if (command_arg >= args.size()) { + LOG(ERROR) << "exec called without command"; + return nullptr; + } + std::vector str_args(args.begin() + command_arg, args.end()); + + static size_t exec_count = 0; + exec_count++; + std::string name = "exec " + std::to_string(exec_count) + " (" + Join(str_args, " ") + ")"; + + unsigned flags = SVC_ONESHOT | SVC_TEMPORARY; + CapSet no_capabilities; + unsigned namespace_flags = 0; + + std::string seclabel = ""; + if (command_arg > 2 && args[1] != "-") { + seclabel = args[1]; + } + Result uid = 0; + if (command_arg > 3) { + uid = DecodeUid(args[2]); + if (!uid) { + LOG(ERROR) << "Unable to decode UID for '" << args[2] << "': " << uid.error(); + return nullptr; + } + } + Result gid = 0; + std::vector supp_gids; + if (command_arg > 4) { + gid = DecodeUid(args[3]); + if (!gid) { + LOG(ERROR) << "Unable to decode GID for '" << args[3] << "': " << gid.error(); + return nullptr; + } + std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */; + for (size_t i = 0; i < nr_supp_gids; ++i) { + auto supp_gid = DecodeUid(args[4 + i]); + if (!supp_gid) { + LOG(ERROR) << "Unable to decode GID for '" << args[4 + i] + << "': " << supp_gid.error(); + return nullptr; + } + supp_gids.push_back(*supp_gid); + } + } + + return std::make_unique(name, flags, *uid, *gid, supp_gids, no_capabilities, + namespace_flags, seclabel, nullptr, str_args); +} + +// Shutdown services in the opposite order that they were started. +const std::vector ServiceList::services_in_shutdown_order() const { + std::vector shutdown_services; + for (const auto& service : services_) { + if (service->start_order() > 0) shutdown_services.emplace_back(service.get()); + } + std::sort(shutdown_services.begin(), shutdown_services.end(), + [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); }); + return shutdown_services; +} + +void ServiceList::RemoveService(const Service& svc) { + auto svc_it = std::find_if(services_.begin(), services_.end(), + [&svc] (const std::unique_ptr& s) { + return svc.name() == s->name(); + }); + if (svc_it == services_.end()) { + return; + } + + services_.erase(svc_it); +} + +void ServiceList::DumpState() const { + for (const auto& s : services_) { + s->DumpState(); + } +} + +Result ServiceParser::ParseSection(std::vector&& args, + const std::string& filename, int line) { + if (args.size() < 3) { + return Error() << "services must have a name and a program"; + } + + const std::string& name = args[1]; + if (!IsValidName(name)) { + return Error() << "invalid service name '" << name << "'"; + } + + Subcontext* restart_action_subcontext = nullptr; + if (subcontexts_) { + for (auto& subcontext : *subcontexts_) { + if (StartsWith(filename, subcontext.path_prefix())) { + restart_action_subcontext = &subcontext; + break; + } + } + } + + std::vector str_args(args.begin() + 2, args.end()); + service_ = std::make_unique(name, restart_action_subcontext, str_args); + return Success(); +} + +Result ServiceParser::ParseLineSection(std::vector&& args, int line) { + return service_ ? service_->ParseLine(std::move(args)) : Success(); +} + +Result ServiceParser::EndSection() { + if (service_) { + Service* old_service = service_list_->FindService(service_->name()); + if (old_service) { + if (!service_->is_override()) { + return Error() << "ignored duplicate definition of service '" << service_->name() + << "'"; + } + + service_list_->RemoveService(*old_service); + old_service = nullptr; + } + + service_list_->AddService(std::move(service_)); + } + + return Success(); +} + +bool ServiceParser::IsValidName(const std::string& name) const { + // Property names can be any length, but may only contain certain characters. + // Property values can contain any characters, but may only be a certain length. + // (The latter restriction is needed because `start` and `stop` work by writing + // the service name to the "ctl.start" and "ctl.stop" properties.) + return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX; +} + +} // namespace init +} // namespace android diff --git a/aosp/system/core/init/subcontext.cpp b/aosp/system/core/init/subcontext.cpp new file mode 100644 index 000000000..c8b2f5eae --- /dev/null +++ b/aosp/system/core/init/subcontext.cpp @@ -0,0 +1,381 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "subcontext.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "action.h" +#include "util.h" + +#if defined(__ANDROID__) +#include + +#include "property_service.h" +#include "selinux.h" +#else +#include "host_init_stubs.h" +#endif + +using android::base::GetExecutablePath; +using android::base::GetIntProperty; +using android::base::Join; +using android::base::Socketpair; +using android::base::Split; +using android::base::StartsWith; +using android::base::unique_fd; + +namespace android { +namespace init { + +const std::string kInitContext = "u:r:init:s0"; +const std::string kVendorContext = "u:r:vendor_init:s0"; + +const char* const paths_and_secontexts[2][2] = { + {"/vendor", kVendorContext.c_str()}, + {"/odm", kVendorContext.c_str()}, +}; + +namespace { + +constexpr size_t kBufferSize = 4096; + +Result ReadMessage(int socket) { + char buffer[kBufferSize] = {}; + auto result = TEMP_FAILURE_RETRY(recv(socket, buffer, sizeof(buffer), 0)); + if (result <= 0) { + return ErrnoError(); + } + return std::string(buffer, result); +} + +template +Result SendMessage(int socket, const T& message) { + std::string message_string; + if (!message.SerializeToString(&message_string)) { + return Error() << "Unable to serialize message"; + } + + if (message_string.size() > kBufferSize) { + return Error() << "Serialized message too long to send"; + } + + if (auto result = + TEMP_FAILURE_RETRY(send(socket, message_string.c_str(), message_string.size(), 0)); + result != static_cast(message_string.size())) { + return ErrnoError() << "send() failed to send message contents"; + } + return Success(); +} + +std::vector> properties_to_set; + +uint32_t SubcontextPropertySet(const std::string& name, const std::string& value) { + properties_to_set.emplace_back(name, value); + return 0; +} + +class SubcontextProcess { + public: + SubcontextProcess(const KeywordFunctionMap* function_map, std::string context, int init_fd) + : function_map_(function_map), context_(std::move(context)), init_fd_(init_fd){}; + void MainLoop(); + + private: + void RunCommand(const SubcontextCommand::ExecuteCommand& execute_command, + SubcontextReply* reply) const; + void ExpandArgs(const SubcontextCommand::ExpandArgsCommand& expand_args_command, + SubcontextReply* reply) const; + + const KeywordFunctionMap* function_map_; + const std::string context_; + const int init_fd_; +}; + +void SubcontextProcess::RunCommand(const SubcontextCommand::ExecuteCommand& execute_command, + SubcontextReply* reply) const { + // Need to use ArraySplice instead of this code. + auto args = std::vector(); + for (const auto& string : execute_command.args()) { + args.emplace_back(string); + } + + auto map_result = function_map_->FindFunction(args); + Result result; + if (!map_result) { + result = Error() << "Cannot find command: " << map_result.error(); + } else { + result = RunBuiltinFunction(map_result->second, args, context_); + } + + for (const auto& [name, value] : properties_to_set) { + auto property = reply->add_properties_to_set(); + property->set_name(name); + property->set_value(value); + } + + properties_to_set.clear(); + + if (result) { + reply->set_success(true); + } else { + auto* failure = reply->mutable_failure(); + failure->set_error_string(result.error_string()); + failure->set_error_errno(result.error_errno()); + } +} + +void SubcontextProcess::ExpandArgs(const SubcontextCommand::ExpandArgsCommand& expand_args_command, + SubcontextReply* reply) const { + for (const auto& arg : expand_args_command.args()) { + auto expanded_prop = std::string{}; + if (!expand_props(arg, &expanded_prop)) { + auto* failure = reply->mutable_failure(); + failure->set_error_string("Failed to expand '" + arg + "'"); + failure->set_error_errno(0); + return; + } else { + auto* expand_args_reply = reply->mutable_expand_args_reply(); + expand_args_reply->add_expanded_args(expanded_prop); + } + } +} + +void SubcontextProcess::MainLoop() { + pollfd ufd[1]; + ufd[0].events = POLLIN; + ufd[0].fd = init_fd_; + + while (true) { + ufd[0].revents = 0; + int nr = TEMP_FAILURE_RETRY(poll(ufd, arraysize(ufd), -1)); + if (nr == 0) continue; + if (nr < 0) { + PLOG(FATAL) << "poll() of subcontext socket failed, continuing"; + } + + auto init_message = ReadMessage(init_fd_); + if (!init_message) { + LOG(FATAL) << "Could not read message from init: " << init_message.error(); + } + + auto subcontext_command = SubcontextCommand(); + if (!subcontext_command.ParseFromString(*init_message)) { + LOG(FATAL) << "Unable to parse message from init"; + } + + auto reply = SubcontextReply(); + switch (subcontext_command.command_case()) { + case SubcontextCommand::kExecuteCommand: { + RunCommand(subcontext_command.execute_command(), &reply); + break; + } + case SubcontextCommand::kExpandArgsCommand: { + ExpandArgs(subcontext_command.expand_args_command(), &reply); + break; + } + default: + LOG(FATAL) << "Unknown message type from init: " + << subcontext_command.command_case(); + } + + if (auto result = SendMessage(init_fd_, reply); !result) { + LOG(FATAL) << "Failed to send message to init: " << result.error(); + } + } +} + +} // namespace + +int SubcontextMain(int argc, char** argv, const KeywordFunctionMap* function_map) { + if (argc < 4) LOG(FATAL) << "Fewer than 4 args specified to subcontext (" << argc << ")"; + + auto context = std::string(argv[2]); + auto init_fd = std::atoi(argv[3]); + + if (is_selinux_enabled()) { + SelabelInitialize(); + } + property_set = SubcontextPropertySet; + + auto subcontext_process = SubcontextProcess(function_map, context, init_fd); + subcontext_process.MainLoop(); + return 0; +} + +void Subcontext::Fork() { + unique_fd subcontext_socket; + if (!Socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, &socket_, &subcontext_socket)) { + LOG(FATAL) << "Could not create socket pair to communicate to subcontext"; + return; + } + + auto result = fork(); + + if (result == -1) { + LOG(FATAL) << "Could not fork subcontext"; + } else if (result == 0) { + socket_.reset(); + + // We explicitly do not use O_CLOEXEC here, such that we can reference this FD by number + // in the subcontext process after we exec. + int child_fd = dup(subcontext_socket); + if (child_fd < 0) { + PLOG(FATAL) << "Could not dup child_fd"; + } + + LOG(INFO) << "setexeccon for process " << getpid() << " " << context_ << ""; + if (setexeccon(context_.c_str()) < 0) { + PLOG(FATAL) << "Could not set execcon for '" << context_ << "'"; + } + + auto init_path = GetExecutablePath(); + auto child_fd_string = std::to_string(child_fd); + const char* args[] = {init_path.c_str(), "subcontext", context_.c_str(), + child_fd_string.c_str(), nullptr}; + execv(init_path.data(), const_cast(args)); + + PLOG(FATAL) << "Could not execv subcontext init"; + } else { + subcontext_socket.reset(); + pid_ = result; + LOG(INFO) << "Forked subcontext for '" << context_ << "' with pid " << pid_; + } +} + +void Subcontext::Restart() { + LOG(ERROR) << "Restarting subcontext '" << context_ << "'"; + if (pid_) { + kill(pid_, SIGKILL); + } + pid_ = 0; + socket_.reset(); + Fork(); +} + +Result Subcontext::TransmitMessage(const SubcontextCommand& subcontext_command) { + if (auto result = SendMessage(socket_, subcontext_command); !result) { + Restart(); + return ErrnoError() << "Failed to send message to subcontext"; + } + + auto subcontext_message = ReadMessage(socket_); + if (!subcontext_message) { + Restart(); + return Error() << "Failed to receive result from subcontext: " << subcontext_message.error(); + } + + auto subcontext_reply = SubcontextReply{}; + if (!subcontext_reply.ParseFromString(*subcontext_message)) { + Restart(); + return Error() << "Unable to parse message from subcontext"; + } + return subcontext_reply; +} + +Result Subcontext::Execute(const std::vector& args) { + auto subcontext_command = SubcontextCommand(); + std::copy( + args.begin(), args.end(), + RepeatedPtrFieldBackInserter(subcontext_command.mutable_execute_command()->mutable_args())); + + auto subcontext_reply = TransmitMessage(subcontext_command); + if (!subcontext_reply) { + return subcontext_reply.error(); + } + + for (const auto& property : subcontext_reply->properties_to_set()) { + ucred cr = {.pid = pid_, .uid = 0, .gid = 0}; + std::string error; + if (HandlePropertySet(property.name(), property.value(), context_, cr, &error) != 0) { + LOG(ERROR) << "Subcontext init could not set '" << property.name() << "' to '" + << property.value() << "': " << error; + } + } + + if (subcontext_reply->reply_case() == SubcontextReply::kFailure) { + auto& failure = subcontext_reply->failure(); + return ResultError(failure.error_string(), failure.error_errno()); + } + + if (subcontext_reply->reply_case() != SubcontextReply::kSuccess) { + return Error() << "Unexpected message type from subcontext: " + << subcontext_reply->reply_case(); + } + + return Success(); +} + +Result> Subcontext::ExpandArgs(const std::vector& args) { + auto subcontext_command = SubcontextCommand{}; + std::copy(args.begin(), args.end(), + RepeatedPtrFieldBackInserter( + subcontext_command.mutable_expand_args_command()->mutable_args())); + + auto subcontext_reply = TransmitMessage(subcontext_command); + if (!subcontext_reply) { + return subcontext_reply.error(); + } + + if (subcontext_reply->reply_case() == SubcontextReply::kFailure) { + auto& failure = subcontext_reply->failure(); + return ResultError(failure.error_string(), failure.error_errno()); + } + + if (subcontext_reply->reply_case() != SubcontextReply::kExpandArgsReply) { + return Error() << "Unexpected message type from subcontext: " + << subcontext_reply->reply_case(); + } + + auto& reply = subcontext_reply->expand_args_reply(); + auto expanded_args = std::vector{}; + for (const auto& string : reply.expanded_args()) { + expanded_args.emplace_back(string); + } + return expanded_args; +} + +static std::vector subcontexts; + +std::vector* InitializeSubcontexts() { + if (SelinuxHasVendorInit()) { + for (const auto& [path_prefix, secontext] : paths_and_secontexts) { + subcontexts.emplace_back(path_prefix, secontext); + } + } + return &subcontexts; +} + +bool SubcontextChildReap(pid_t pid) { + for (auto& subcontext : subcontexts) { + if (subcontext.pid() == pid) { + subcontext.Restart(); + return true; + } + } + return false; +} + +} // namespace init +} // namespace android diff --git a/aosp/system/core/init/ueventd.cpp b/aosp/system/core/init/ueventd.cpp new file mode 100644 index 000000000..27ef621b7 --- /dev/null +++ b/aosp/system/core/init/ueventd.cpp @@ -0,0 +1,300 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ueventd.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "devices.h" +#include "firmware_handler.h" +#include "log.h" +#include "selinux.h" +#include "uevent_listener.h" +#include "ueventd_parser.h" +#include "util.h" + +// At a high level, ueventd listens for uevent messages generated by the kernel through a netlink +// socket. When ueventd receives such a message it handles it by taking appropriate actions, +// which can typically be creating a device node in /dev, setting file permissions, setting selinux +// labels, etc. +// Ueventd also handles loading of firmware that the kernel requests, and creates symlinks for block +// and character devices. + +// When ueventd starts, it regenerates uevents for all currently registered devices by traversing +// /sys and writing 'add' to each 'uevent' file that it finds. This causes the kernel to generate +// and resend uevent messages for all of the currently registered devices. This is done, because +// ueventd would not have been running when these devices were registered and therefore was unable +// to receive their uevent messages and handle them appropriately. This process is known as +// 'cold boot'. + +// 'init' currently waits synchronously on the cold boot process of ueventd before it continues +// its boot process. For this reason, cold boot should be as quick as possible. One way to achieve +// a speed up here is to parallelize the handling of ueventd messages, which consume the bulk of the +// time during cold boot. + +// Handling of uevent messages has two unique properties: +// 1) It can be done in isolation; it doesn't need to read or write any status once it is started. +// 2) It uses setegid() and setfscreatecon() so either care (aka locking) must be taken to ensure +// that no file system operations are done while the uevent process has an abnormal egid or +// fscreatecon or this handling must happen in a separate process. +// Given the above two properties, it is best to fork() subprocesses to handle the uevents. This +// reduces the overhead and complexity that would be required in a solution with threads and locks. +// In testing, a racy multithreaded solution has the same performance as the fork() solution, so +// there is no reason to deal with the complexity of the former. + +// One other important caveat during the boot process is the handling of SELinux restorecon. +// Since many devices have child devices, calling selinux_android_restorecon() recursively for each +// device when its uevent is handled, results in multiple restorecon operations being done on a +// given file. It is more efficient to simply do restorecon recursively on /sys during cold boot, +// than to do restorecon on each device as its uevent is handled. This only applies to cold boot; +// once that has completed, restorecon is done for each device as its uevent is handled. + +// With all of the above considered, the cold boot process has the below steps: +// 1) ueventd regenerates uevents by doing the /sys traversal and listens to the netlink socket for +// the generated uevents. It writes these uevents into a queue represented by a vector. +// +// 2) ueventd forks 'n' separate uevent handler subprocesses and has each of them to handle the +// uevents in the queue based on a starting offset (their process number) and a stride (the total +// number of processes). Note that no IPC happens at this point and only const functions from +// DeviceHandler should be called from this context. +// +// 3) In parallel to the subprocesses handling the uevents, the main thread of ueventd calls +// selinux_android_restorecon() recursively on /sys/class, /sys/block, and /sys/devices. +// +// 4) Once the restorecon operation finishes, the main thread calls waitpid() to wait for all +// subprocess handlers to complete and exit. Once this happens, it marks coldboot as having +// completed. +// +// At this point, ueventd is single threaded, poll()'s and then handles any future uevents. + +// Lastly, it should be noted that uevents that occur during the coldboot process are handled +// without issue after the coldboot process completes. This is because the uevent listener is +// paused while the uevent handler and restorecon actions take place. Once coldboot completes, +// the uevent listener resumes in polling mode and will handle the uevents that occurred during +// coldboot. + +namespace android { +namespace init { + +class ColdBoot { + public: + ColdBoot(UeventListener& uevent_listener, DeviceHandler& device_handler) + : uevent_listener_(uevent_listener), + device_handler_(device_handler), + num_handler_subprocesses_(std::thread::hardware_concurrency() ?: 4) {} + + void Run(); + + private: + void UeventHandlerMain(unsigned int process_num, unsigned int total_processes); + void RegenerateUevents(); + void ForkSubProcesses(); + void DoRestoreCon(); + void WaitForSubProcesses(); + + UeventListener& uevent_listener_; + DeviceHandler& device_handler_; + + unsigned int num_handler_subprocesses_; + std::vector uevent_queue_; + + std::set subprocess_pids_; +}; + +void ColdBoot::UeventHandlerMain(unsigned int process_num, unsigned int total_processes) { + for (unsigned int i = process_num; i < uevent_queue_.size(); i += total_processes) { + auto& uevent = uevent_queue_[i]; + device_handler_.HandleDeviceEvent(uevent); + } + _exit(EXIT_SUCCESS); +} + +void ColdBoot::RegenerateUevents() { + uevent_listener_.RegenerateUevents([this](const Uevent& uevent) { + HandleFirmwareEvent(uevent); + + uevent_queue_.emplace_back(std::move(uevent)); + return ListenerAction::kContinue; + }); +} + +void ColdBoot::ForkSubProcesses() { + for (unsigned int i = 0; i < num_handler_subprocesses_; ++i) { + auto pid = fork(); + if (pid < 0) { + PLOG(FATAL) << "fork() failed!"; + } + + if (pid == 0) { + UeventHandlerMain(i, num_handler_subprocesses_); + } + + subprocess_pids_.emplace(pid); + } +} + +void ColdBoot::DoRestoreCon() { + selinux_android_restorecon("/sys", SELINUX_ANDROID_RESTORECON_RECURSE); + device_handler_.set_skip_restorecon(false); +} + +void ColdBoot::WaitForSubProcesses() { + // Treat subprocesses that crash or get stuck the same as if ueventd itself has crashed or gets + // stuck. + // + // When a subprocess crashes, we fatally abort from ueventd. init will restart ueventd when + // init reaps it, and the cold boot process will start again. If this continues to fail, then + // since ueventd is marked as a critical service, init will reboot to recovery. + // + // When a subprocess gets stuck, keep ueventd spinning waiting for it. init has a timeout for + // cold boot and will reboot to the bootloader if ueventd does not complete in time. + while (!subprocess_pids_.empty()) { + int status; + pid_t pid = TEMP_FAILURE_RETRY(waitpid(-1, &status, 0)); + if (pid == -1) { + PLOG(ERROR) << "waitpid() failed"; + continue; + } + + auto it = std::find(subprocess_pids_.begin(), subprocess_pids_.end(), pid); + if (it == subprocess_pids_.end()) continue; + + if (WIFEXITED(status)) { + if (WEXITSTATUS(status) == EXIT_SUCCESS) { + subprocess_pids_.erase(it); + } else { + LOG(FATAL) << "subprocess exited with status " << WEXITSTATUS(status); + } + } else if (WIFSIGNALED(status)) { + LOG(FATAL) << "subprocess killed by signal " << WTERMSIG(status); + } + } +} + +void ColdBoot::Run() { + android::base::Timer cold_boot_timer; + + RegenerateUevents(); + + ForkSubProcesses(); + + DoRestoreCon(); + + WaitForSubProcesses(); + + close(open(COLDBOOT_DONE, O_WRONLY | O_CREAT | O_CLOEXEC, 0000)); + LOG(INFO) << "Coldboot took " << cold_boot_timer.duration().count() / 1000.0f << " seconds"; +} + +DeviceHandler CreateDeviceHandler() { + Parser parser; + + std::vector subsystems; + parser.AddSectionParser("subsystem", std::make_unique(&subsystems)); + + using namespace std::placeholders; + std::vector sysfs_permissions; + std::vector dev_permissions; + parser.AddSingleLineParser("/sys/", + std::bind(ParsePermissionsLine, _1, &sysfs_permissions, nullptr)); + parser.AddSingleLineParser("/dev/", + std::bind(ParsePermissionsLine, _1, nullptr, &dev_permissions)); + + parser.ParseConfig("/ueventd.rc"); + parser.ParseConfig("/vendor/ueventd.rc"); + parser.ParseConfig("/odm/ueventd.rc"); + + /* + * keep the current product name base configuration so + * we remain backwards compatible and allow it to override + * everything + * TODO: cleanup platform ueventd.rc to remove vendor specific + * device node entries (b/34968103) + */ + std::string hardware = android::base::GetProperty("ro.hardware", ""); + parser.ParseConfig("/ueventd." + hardware + ".rc"); + + auto boot_devices = fs_mgr_get_boot_devices(); + return DeviceHandler(std::move(dev_permissions), std::move(sysfs_permissions), + std::move(subsystems), std::move(boot_devices), true); +} + +int ueventd_main(int argc, char** argv) { + /* + * init sets the umask to 077 for forked processes. We need to + * create files with exact permissions, without modification by + * the umask. + */ + umask(000); + + InitKernelLogging(argv); + + LOG(INFO) << "ueventd started!"; + + if (is_selinux_enabled()) { + // 设置ueventd进程标签,因为默认是继承init的标签u:r:init:s0,所以需要修改 + if (setcon("u:r:ueventd:s0") < 0) { + LOG(INFO) << "set context for ueventd failed"; + } else { + LOG(INFO) << "set context for ueventd success."; + } + + SelinuxSetupKernelLogging(); + SelabelInitialize(); + } + + DeviceHandler device_handler = CreateDeviceHandler(); + UeventListener uevent_listener; + + if (access(COLDBOOT_DONE, F_OK) != 0) { + ColdBoot cold_boot(uevent_listener, device_handler); + cold_boot.Run(); + } + + // We use waitpid() in ColdBoot, so we can't ignore SIGCHLD until now. + signal(SIGCHLD, SIG_IGN); + // Reap and pending children that exited between the last call to waitpid() and setting SIG_IGN + // for SIGCHLD above. + while (waitpid(-1, nullptr, WNOHANG) > 0) { + } + + uevent_listener.Poll([&device_handler](const Uevent& uevent) { + HandleFirmwareEvent(uevent); + device_handler.HandleDeviceEvent(uevent); + return ListenerAction::kContinue; + }); + + return 0; +} + +} // namespace init +} // namespace android diff --git a/aosp/system/core/init/util.cpp b/aosp/system/core/init/util.cpp new file mode 100644 index 000000000..e5905f2c6 --- /dev/null +++ b/aosp/system/core/init/util.cpp @@ -0,0 +1,446 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "reboot.h" + +#if defined(__ANDROID__) +#include + +#include "selinux.h" +#else +#include "host_init_stubs.h" +#endif + +#ifdef _INIT_INIT_H +#error "Do not include init.h in files used by ueventd or watchdogd; it will expose init's globals" +#endif + +using android::base::boot_clock; +using namespace std::literals::string_literals; + +namespace android { +namespace init { + +const std::string kDefaultAndroidDtDir("/proc/device-tree/firmware/android/"); + +// DecodeUid() - decodes and returns the given string, which can be either the +// numeric or name representation, into the integer uid or gid. +Result DecodeUid(const std::string& name) { + if (isalpha(name[0])) { + passwd* pwd = getpwnam(name.c_str()); + if (!pwd) return ErrnoError() << "getpwnam failed"; + + return pwd->pw_uid; + } + + errno = 0; + uid_t result = static_cast(strtoul(name.c_str(), 0, 0)); + if (errno) return ErrnoError() << "strtoul failed"; + + return result; +} + +/* + * CreateSocket - creates a Unix domain socket in ANDROID_SOCKET_DIR + * ("/dev/socket") as dictated in init.rc. This socket is inherited by the + * daemon. We communicate the file descriptor's value via the environment + * variable ANDROID_SOCKET_ENV_PREFIX ("ANDROID_SOCKET_foo"). + */ +int CreateSocket(const char* name, int type, bool passcred, mode_t perm, uid_t uid, gid_t gid, + const char* socketcon) { +#if 0 + if (socketcon) { + if (setsockcreatecon(socketcon) == -1) { + PLOG(ERROR) << "setsockcreatecon(\"" << socketcon << "\") failed"; + return -1; + } + } +#endif + android::base::unique_fd fd(socket(PF_UNIX, type, 0)); + if (fd < 0) { + PLOG(ERROR) << "Failed to open socket '" << name << "'"; + return -1; + } + + // socket创建完毕,将sockcreate security context设置为默认值 + if (is_selinux_enabled() && socketcon) setsockcreatecon(NULL); + + struct sockaddr_un addr; + memset(&addr, 0 , sizeof(addr)); + addr.sun_family = AF_UNIX; + snprintf(addr.sun_path, sizeof(addr.sun_path), ANDROID_SOCKET_DIR"/%s", + name); + + if ((unlink(addr.sun_path) != 0) && (errno != ENOENT)) { + PLOG(ERROR) << "Failed to unlink old socket '" << name << "'"; + return -1; + } +#if 0 + std::string secontext; + if (SelabelLookupFileContext(addr.sun_path, S_IFSOCK, &secontext) && !secontext.empty()) { + setfscreatecon(secontext.c_str()); + } +#endif + if (passcred) { + int on = 1; + if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &on, sizeof(on))) { + PLOG(ERROR) << "Failed to set SO_PASSCRED '" << name << "'"; + return -1; + } + } + + int ret = bind(fd, (struct sockaddr *) &addr, sizeof (addr)); + int savederrno = errno; +#if 0 + if (!secontext.empty()) { + setfscreatecon(nullptr); + } +#endif + if (ret) { + errno = savederrno; + PLOG(ERROR) << "Failed to bind socket '" << name << "'"; + goto out_unlink; + } + + if (lchown(addr.sun_path, uid, gid)) { + PLOG(ERROR) << "Failed to lchown socket '" << addr.sun_path << "'"; + goto out_unlink; + } + if (fchmodat(AT_FDCWD, addr.sun_path, perm, AT_SYMLINK_NOFOLLOW)) { + PLOG(ERROR) << "Failed to fchmodat socket '" << addr.sun_path << "'"; + goto out_unlink; + } + + LOG(INFO) << "Created socket '" << addr.sun_path << "'" + << ", mode " << std::oct << perm << std::dec + << ", user " << uid + << ", group " << gid; + + return fd.release(); + +out_unlink: + unlink(addr.sun_path); + return -1; +} + +Result ReadFile(const std::string& path) { + android::base::unique_fd fd( + TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC))); + if (fd == -1) { + return ErrnoError() << "open() failed"; + } + + // For security reasons, disallow world-writable + // or group-writable files. + struct stat sb; + if (fstat(fd, &sb) == -1) { + return ErrnoError() << "fstat failed()"; + } + if ((sb.st_mode & (S_IWGRP | S_IWOTH)) != 0) { + return Error() << "Skipping insecure file"; + } + + std::string content; + if (!android::base::ReadFdToString(fd, &content)) { + return ErrnoError() << "Unable to read file contents"; + } + return content; +} + +static int OpenFile(const std::string& path, int flags, mode_t mode) { + if (!is_selinux_enabled()) { + return open(path.c_str(), flags, mode); + } + std::string secontext; + if (SelabelLookupFileContext(path, mode, &secontext) && !secontext.empty()) { + setfscreatecon(secontext.c_str()); + } + int rc = open(path.c_str(), flags, mode); + if (!secontext.empty()) { + int save_errno = errno; + setfscreatecon(nullptr); + errno = save_errno; + } + return rc; +} + +Result WriteFile(const std::string& path, const std::string& content) { + android::base::unique_fd fd(TEMP_FAILURE_RETRY( + OpenFile(path, O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600))); + if (fd == -1) { + return ErrnoError() << "open() failed"; + } + if (!android::base::WriteStringToFd(content, fd)) { + return ErrnoError() << "Unable to write file contents"; + } + return Success(); +} + +bool mkdir_recursive(const std::string& path, mode_t mode) { + std::string::size_type slash = 0; + while ((slash = path.find('/', slash + 1)) != std::string::npos) { + auto directory = path.substr(0, slash); + struct stat info; + if (stat(directory.c_str(), &info) != 0) { + auto ret = make_dir(directory, mode); + if (!ret && errno != EEXIST) return false; + } + } + auto ret = make_dir(path, mode); + if (!ret && errno != EEXIST) return false; + return true; +} + +int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) { + android::base::Timer t; + while (t.duration() < timeout) { + struct stat sb; + if (stat(filename, &sb) != -1) { + LOG(INFO) << "wait for '" << filename << "' took " << t; + return 0; + } + std::this_thread::sleep_for(10ms); + } + LOG(WARNING) << "wait for '" << filename << "' timed out and took " << t; + return -1; +} + +void import_kernel_cmdline(bool in_qemu, + const std::function& fn) { + std::string cmdline; + android::base::ReadFileToString("/proc/cmdline", &cmdline); + + for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) { + std::vector pieces = android::base::Split(entry, "="); + if (pieces.size() == 2) { + fn(pieces[0], pieces[1], in_qemu); + } + } +} + +bool make_dir(const std::string& path, mode_t mode) { + if (!is_selinux_enabled()) { + return (mkdir(path.c_str(), mode) == 0); + } + std::string secontext; + if (SelabelLookupFileContext(path, mode, &secontext) && !secontext.empty()) { + setfscreatecon(secontext.c_str()); + } + int rc = mkdir(path.c_str(), mode); + if (!secontext.empty()) { + int save_errno = errno; + setfscreatecon(nullptr); + errno = save_errno; + } + return rc == 0; +} + +/* + * Writes hex_len hex characters (1/2 byte) to hex from bytes. + */ +std::string bytes_to_hex(const uint8_t* bytes, size_t bytes_len) { + std::string hex("0x"); + for (size_t i = 0; i < bytes_len; i++) + android::base::StringAppendF(&hex, "%02x", bytes[i]); + return hex; +} + +/* + * Returns true is pathname is a directory + */ +bool is_dir(const char* pathname) { + struct stat info; + if (stat(pathname, &info) == -1) { + return false; + } + return S_ISDIR(info.st_mode); +} + +bool expand_props(const std::string& src, std::string* dst) { + const char* src_ptr = src.c_str(); + + if (!dst) { + return false; + } + + /* - variables can either be $x.y or ${x.y}, in case they are only part + * of the string. + * - will accept $$ as a literal $. + * - no nested property expansion, i.e. ${foo.${bar}} is not supported, + * bad things will happen + * - ${x.y:-default} will return default value if property empty. + */ + while (*src_ptr) { + const char* c; + + c = strchr(src_ptr, '$'); + if (!c) { + dst->append(src_ptr); + return true; + } + + dst->append(src_ptr, c); + c++; + + if (*c == '$') { + dst->push_back(*(c++)); + src_ptr = c; + continue; + } else if (*c == '\0') { + return true; + } + + std::string prop_name; + std::string def_val; + if (*c == '{') { + c++; + const char* end = strchr(c, '}'); + if (!end) { + // failed to find closing brace, abort. + LOG(ERROR) << "unexpected end of string in '" << src << "', looking for }"; + return false; + } + prop_name = std::string(c, end); + c = end + 1; + size_t def = prop_name.find(":-"); + if (def < prop_name.size()) { + def_val = prop_name.substr(def + 2); + prop_name = prop_name.substr(0, def); + } + } else { + prop_name = c; + LOG(ERROR) << "using deprecated syntax for specifying property '" << c << "', use ${name} instead"; + c += prop_name.size(); + } + + if (prop_name.empty()) { + LOG(ERROR) << "invalid zero-length property name in '" << src << "'"; + return false; + } + + std::string prop_val = android::base::GetProperty(prop_name, ""); + if (prop_val.empty()) { + if (def_val.empty()) { + LOG(ERROR) << "property '" << prop_name << "' doesn't exist while expanding '" << src << "'"; + return false; + } + prop_val = def_val; + } + + dst->append(prop_val); + src_ptr = c; + } + + return true; +} + +static std::string init_android_dt_dir() { + // Use the standard procfs-based path by default + std::string android_dt_dir = kDefaultAndroidDtDir; + // The platform may specify a custom Android DT path in kernel cmdline + import_kernel_cmdline(false, + [&](const std::string& key, const std::string& value, bool in_qemu) { + if (key == "androidboot.android_dt_dir") { + android_dt_dir = value; + } + }); + LOG(INFO) << "Using Android DT directory " << android_dt_dir; + return android_dt_dir; +} + +// FIXME: The same logic is duplicated in system/core/fs_mgr/ +const std::string& get_android_dt_dir() { + // Set once and saves time for subsequent calls to this function + static const std::string kAndroidDtDir = init_android_dt_dir(); + return kAndroidDtDir; +} + +// Reads the content of device tree file under the platform's Android DT directory. +// Returns true if the read is success, false otherwise. +bool read_android_dt_file(const std::string& sub_path, std::string* dt_content) { + const std::string file_name = get_android_dt_dir() + sub_path; + if (android::base::ReadFileToString(file_name, dt_content)) { + if (!dt_content->empty()) { + dt_content->pop_back(); // Trims the trailing '\0' out. + return true; + } + } + return false; +} + +bool is_android_dt_value_expected(const std::string& sub_path, const std::string& expected_content) { + std::string dt_content; + if (read_android_dt_file(sub_path, &dt_content)) { + if (dt_content == expected_content) { + return true; + } + } + return false; +} + +bool IsLegalPropertyName(const std::string& name) { + size_t namelen = name.size(); + + if (namelen < 1) return false; + if (name[0] == '.') return false; + if (name[namelen - 1] == '.') return false; + + /* Only allow alphanumeric, plus '.', '-', '@', ':', or '_' */ + /* Don't allow ".." to appear in a property name */ + for (size_t i = 0; i < namelen; i++) { + if (name[i] == '.') { + // i=0 is guaranteed to never have a dot. See above. + if (name[i - 1] == '.') return false; + continue; + } + if (name[i] == '_' || name[i] == '-' || name[i] == '@' || name[i] == ':') continue; + if (name[i] >= 'a' && name[i] <= 'z') continue; + if (name[i] >= 'A' && name[i] <= 'Z') continue; + if (name[i] >= '0' && name[i] <= '9') continue; + return false; + } + + return true; +} + +} // namespace init +} // namespace android -- Gitee From e253e91c23b42e7e62d79c3a650905528bc41157 Mon Sep 17 00:00:00 2001 From: yayaws_zk <584363327@qq.com> Date: Sat, 6 Sep 2025 13:08:26 +0800 Subject: [PATCH 3/3] open source init --- aosp/external/toybox/Android.mk | 4 ++-- aosp/system/core/init/Android.mk | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/aosp/external/toybox/Android.mk b/aosp/external/toybox/Android.mk index 71e036e2d..3e00e4c00 100644 --- a/aosp/external/toybox/Android.mk +++ b/aosp/external/toybox/Android.mk @@ -402,7 +402,7 @@ ALL_TOOLS := \ ############################################ include $(CLEAR_VARS) -LOCAL_MODULE := toybox_orig +LOCAL_MODULE := toybox LOCAL_SRC_FILES := $(common_SRC_FILES) LOCAL_CFLAGS := $(common_CFLAGS) LOCAL_SHARED_LIBRARIES := $(toybox_libraries) @@ -417,7 +417,7 @@ include $(BUILD_EXECUTABLE) ############################################ include $(CLEAR_VARS) -LOCAL_MODULE := toybox_vendor_orig +LOCAL_MODULE := toybox_vendor LOCAL_VENDOR_MODULE := true LOCAL_SRC_FILES := $(common_SRC_FILES) LOCAL_CFLAGS := $(common_CFLAGS) diff --git a/aosp/system/core/init/Android.mk b/aosp/system/core/init/Android.mk index 32f503420..4bb4004dc 100644 --- a/aosp/system/core/init/Android.mk +++ b/aosp/system/core/init/Android.mk @@ -45,7 +45,7 @@ include $(CLEAR_VARS) LOCAL_CPPFLAGS := $(init_cflags) LOCAL_SRC_FILES := main.cpp -LOCAL_MODULE:= init_orig +LOCAL_MODULE:= init LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT) LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_UNSTRIPPED) -- Gitee