# Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
# Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
#    conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list
#    of conditions and the following disclaimer in the documentation and/or other materials
#    provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors may be used
#    to endorse or promote products derived from this software without specific prior written
#    permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import("//build/lite/config/component/lite_component.gni")

LITEOS_MENUCONFIG_H = rebase_path("$root_out_dir/config.h")

declare_args() {
  tee_enable = false
  liteos_name = "OHOS_Image"
  liteos_skip_make = false
  liteos_is_mini = false
}

tee = ""
if (tee_enable) {
  tee = "_tee"
}

declare_args() {
  liteos_config_file = "${ohos_build_type}${tee}.config"
}

liteos_config_file =
    rebase_path(liteos_config_file, "", "$product_path/kernel_configs")
print("liteos_config_file:", liteos_config_file)

exec_script("//build/lite/run_shell_cmd.py",
            [ "env" + " CONFIG_=LOSCFG_" + " KCONFIG_CONFIG_HEADER='y=true'" +
                  " KCONFIG_CONFIG=$liteos_config_file" +
                  " DEVICE_PATH=$device_path" + " srctree=" + rebase_path(".") +
                  " genconfig" + " --header-path $LITEOS_MENUCONFIG_H" +
                  " --file-list kconfig_files.txt" +
                  " --env-list kconfig_env.txt" + " --config-out config.gni" ],
            "",
            [ liteos_config_file ])

import("liteos.gni")

assert(ARCH != "", "ARCH not set!")
assert(ARCH == arch, "ARCH not match! details: $ARCH != $arch")
assert(tee_enable == defined(LOSCFG_TEE_ENABLE), "TEE switch not match!")
assert(ohos_build_compiler == "clang" == defined(LOSCFG_COMPILER_CLANG_LLVM),
       "compiler not match!")

generate_notice_file("kernel_notice_file") {
  module_name = "kernel"
  module_source_dir_list = [
    "$LITEOSTHIRDPARTY/FreeBSD",
    "$LITEOSTHIRDPARTY/musl",
    "$LITEOSTHIRDPARTY/zlib",
    "$LITEOSTHIRDPARTY/FatFs",
    "$LITEOSTHIRDPARTY/lwip",
    "$LITEOSTHIRDPARTY/NuttX",
    "$LITEOSTHIRDPARTY/mtd-utils",
  ]
}

liteos_arch_cflags = []
if (defined(LOSCFG_ARCH_ARM)) {
  mcpu = LOSCFG_ARCH_CPU
  if (defined(LOSCFG_ARCH_ARM_AARCH64) && defined(LOSCFG_ARCH_FPU_DISABLE)) {
    mcpu += "+nofp"
  }
  liteos_arch_cflags += [ "-mcpu=$mcpu" ]
  if (defined(LOSCFG_ARCH_ARM_AARCH32)) {
    liteos_arch_cflags += [
      "-mfloat-abi=softfp",
      "-mfpu=$LOSCFG_ARCH_FPU",
    ]
  }
}

cc = "$ohos_current_cc_command " + string_join(" ", liteos_arch_cflags)
if (ohos_build_compiler == "clang") {
  cc += " --target=$target_triple"
}

config("arch_config") {
  cflags = liteos_arch_cflags
  asmflags = cflags
  ldflags = cflags
  if (defined(LOSCFG_ARCH_ARM_AARCH32)) {
    if (!defined(LOSCFG_COMPILER_CLANG_LLVM)) {
      cflags += [ "-mthumb-interwork" ]
    }
  }
  if (defined(LOSCFG_THUMB)) {
    cflags += [ "-mthumb" ]
    if (defined(LOSCFG_COMPILER_CLANG_LLVM)) {
      cflags += [ "-mimplicit-it=thumb" ]
    } else {
      cflags += [ "-Wa,-mimplicit-it=thumb" ]
    }
  }
}

config("stdinc_config") {
  std_include = exec_script("//build/lite/run_shell_cmd.py",
                            [ "$cc -print-file-name=include" ],
                            "trim string")
  cflags = [
    "-isystem",
    std_include,
  ]
  if (!defined(LOSCFG_LIBC_NEWLIB)) {
    cflags += [ "-nostdinc" ]
  }
  asmflags = cflags
}

config("ssp_config") {
  cflags = []
  if (defined(LOSCFG_CC_STACKPROTECTOR_ALL)) {
    cflags += [ "-fstack-protector-all" ]
  } else if (defined(LOSCFG_CC_STACKPROTECTOR_STRONG)) {
    cflags += [ "-fstack-protector-strong" ]
  } else if (defined(LOSCFG_CC_STACKPROTECTOR)) {
    cflags += [
      "-fstack-protector",
      "--param",
      "ssp-buffer-size=4",
    ]
  } else {
    cflags += [ "-fno-stack-protector" ]
  }
  asmflags = cflags
}

config("optimize_config") {
  cflags = []
  if (defined(LOSCFG_COMPILE_DEBUG)) {
    cflags += [
      "-g",
      "-gdwarf-2",
    ]
    optimization_cflag = "-O0"
  }
  if (defined(LOSCFG_COMPILE_OPTIMIZE)) {
    optimization_cflag = "-O2"
  }
  if (defined(LOSCFG_COMPILE_OPTIMIZE_SIZE)) {
    if (defined(LOSCFG_COMPILER_CLANG_LLVM)) {
      optimization_cflag = "-Oz"
    } else {
      optimization_cflag = "-Os"
    }
  }
  if (defined(LOSCFG_COMPILE_LTO)) {
    if (defined(LOSCFG_COMPILER_CLANG_LLVM)) {
      cflags += [ "-flto=thin" ]
    } else {
      #cflags += [ "-flto" ]
    }
  }
  cflags += [ optimization_cflag ]
  asmflags = cflags
}

config("kconfig_config") {
  cflags = [
    "-imacros",
    "$LITEOS_MENUCONFIG_H",
  ]
  asmflags = cflags
}

config("warn_config") {
  cflags = [
    "-Wall",
    "-Werror",
    "-Wpointer-arith",
    "-Wstrict-prototypes",
    "-Winvalid-pch",
  ]
  if (defined(LOSCFG_COMPILER_CLANG_LLVM)) {
    cflags += [ "-Wno-address-of-packed-member" ]
  }
  asmflags = cflags
}

config("dialect_config") {
  cflags_c = [ "-std=c99" ]
  cflags_cc = [ "-std=c++11" ]
}

config("misc_config") {
  defines = [ "__LITEOS__" ]
  defines += [ "__LITEOS_A__" ]
  if (!defined(LOSCFG_DEBUG_VERSION)) {
    defines += [ "NDEBUG" ]
  }

  cflags = [
    "-fno-pic",
    "-fno-builtin",
    "-fms-extensions",
    "-fno-strict-aliasing",
    "-fno-common",
    "-fsigned-char",
    "-ffunction-sections",
    "-fdata-sections",
    "-fno-exceptions",
    "-fno-omit-frame-pointer",
    "-fno-short-enums",
    "-mno-unaligned-access",
  ]

  if (!defined(LOSCFG_COMPILER_CLANG_LLVM)) {
    cflags += [ "-fno-aggressive-loop-optimizations" ]
  }

  asmflags = cflags
}

config("los_config") {
  configs = [
    ":arch_config",
    ":kconfig_config",
    ":stdinc_config",
    ":dialect_config",
    ":optimize_config",
    ":ssp_config",
    ":warn_config",
    ":misc_config",
  ]
}

cmd = "if [ -f $device_path/BUILD.gn ]; then echo true; else echo false; fi"
HAVE_DEVICE_SDK = exec_script("//build/lite/run_shell_cmd.py", [ cmd ], "value")

config("public") {
  configs = [
    "arch:public",
    "kernel:public",
    "compat:public",
    "bsd:public",
    "fs:public",
    "drivers:public",
    "security:public",
    "net:public",
    "shell:public",
    "lib:public",
  ]

  configs += [
    "$HDFTOPDIR:public",
    "//drivers/liteos:public",
  ]

  if (HAVE_DEVICE_SDK) {
    configs += [ "$device_path:public" ]
  }
}

group("modules") {
  deps = [
    "arch",
    "bsd",
    "compat",
    "drivers",
    "fs",
    "kernel",
    "lib",
    "net",
    "security",
    "shell",
    "syscall",
    "testsuites/kernel:kernel_test",
  ]

  deps += [
    "//drivers/liteos",
    HDFTOPDIR,
  ]

  if (HAVE_DEVICE_SDK) {
    deps += [ device_path ]
  }
}

group("apps") {
  deps = [ "apps" ]
}

group("tests") {
  deps = [ "testsuites" ]
}

group("kernel") {
  deps = [ ":build_kernel_image" ]
}

group("liteos_a") {
  deps = [ ":kernel" ]
  if (!liteos_is_mini) {
    deps += [
      ":apps",
      ":tests",
      "//third_party/musl/scripts/build_lite:strip",
    ]
    if (liteos_skip_make == false) {
      deps += [ ":make" ]
    }
  }
}

executable("liteos") {
  configs = []  # clear default configs
  configs += [ ":arch_config" ]
  configs += [ ":public" ]

  ldflags = [
    "-static",
    "-nostdlib",
    "-Wl,--gc-sections",
    "-Wl,-Map=$liteos_name.map",
    "-Wl,--no-eh-frame-hdr",
  ]

  if (defined(LOSCFG_LIBC_NEWLIB)) {
    ldflags += [
      "-Wl,--wrap=_free_r",
      "-Wl,--wrap,_malloc_usable_size_r",
      "-Wl,--wrap,_malloc_r",
      "-Wl,--wrap,_memalign_r",
      "-Wl,--wrap,_realloc_r",
      "-Wl,--wrap,_fseeko_r",
    ]
    ldflags -= [ "-nostdlib" ]
  }
  libgcc = exec_script("//build/lite/run_shell_cmd.py",
                       [ "$cc -print-libgcc-file-name" ],
                       "trim string")
  libs = [ libgcc ]
  if (defined(LOSCFG_COMPILER_CLANG_LLVM)) {
    ldflags +=
        [ "-Wl,-T" + rebase_path("tools/build/liteos_llvm.ld", root_build_dir) ]
    inputs = [ "tools/build/liteos_llvm.ld" ]
  } else {
    ldflags +=
        [ "-Wl,-T" + rebase_path("tools/build/liteos.ld", root_build_dir) ]
    ldflags += [ "-nostartfiles" ]
    inputs = [ "tools/build/liteos.ld" ]
  }

  inputs += [ "$root_out_dir/board.ld" ]

  output_dir = target_out_dir

  deps = [
    ":modules",
    "platform:copy_board.ld",
  ]
}

copy("copy_liteos") {
  deps = [ ":liteos" ]
  sources = [ "$target_out_dir/unstripped/bin/liteos" ]
  outputs = [ "$root_out_dir/$liteos_name" ]
}

build_ext_component("build_kernel_image") {
  deps = [ ":copy_liteos" ]
  exec_path = rebase_path(root_out_dir)

  objcopy = "${compile_prefix}objcopy$toolchain_cmd_suffix"
  objdump = "${compile_prefix}objdump$toolchain_cmd_suffix"

  command = "$objcopy -O binary $liteos_name $liteos_name.bin"
  command +=
      " && sh -c '$objdump -t $liteos_name | sort >$liteos_name.sym.sorted'"
  command += " && sh -c '$objdump -d $liteos_name >$liteos_name.asm'"
}

build_ext_component("make") {
  exec_path = rebase_path(".", root_build_dir)
  outdir = rebase_path("$target_out_dir/${target_name}_out")
  sysroot_path = rebase_path(ohos_current_sysroot)
  arch_cflags = string_join(" ", target_arch_cflags)
  command = "./build.sh \"$board_name\" \"$ohos_build_compiler\" \"$root_build_dir\" \"$ohos_build_type\" \"$tee_enable\""
  command += " \"$device_company\" \"$product_path\" \"$outdir\" \"$ohos_version\" \"$sysroot_path\" \"$arch_cflags\""
  command += " \"$device_path\" \"$compile_prefix\" \"$liteos_config_file\""
  if (liteos_skip_make) {
    print("build_ext_component \"$target_name\" skipped:", command)
    command = "true"
  }
}
