ronantakizawa/codereview-bench huggingface dataset:
Repository: files-community/Files
File: src/Files.App/Utils/Signatures/DigitalSignaturesUtil.cs (C#)

Code before:
				return false;

			var result = PInvoke.CertComparePublicKeyInfo(
				ENCODING,
				&pCurrContext->pCertInfo->SubjectPublicKeyInfo,
				&pOrigContext->pCertInfo->SubjectPublicKeyInfo
			);

			return !result;
		}

		private unsafe static bool GetSignerCertificateInfo(string fileName, List<SignNodeInfo> signChain, CancellationToken ct)
		{
			var succeded = false;
			var authSignData = new SignDataHandle() { dwObjSize = 0, hCertStoreHandle = HCERTSTORE.Null, pSignerInfo = null };
			var signDataChain = new List<SignDataHandle>();
			signChain.Clear();

			var cert_store_prov_system = (PCSTR)(byte*)10;
			ReadOnlySpan<char> root = "Root";
			var hSystemStore = PInvoke.CertOpenStore(
				cert_store_prov_system,
				ENCODING,
				HCRYPTPROV_LEGACY.Null,
				(CERT_OPEN_STORE_FLAGS)CERT_SYSTEM_STORE_CURRENT_USER,
				Unsafe.AsPointer(ref MemoryMarshal.GetReference(root))
			); 
			if (hSystemStore == IntPtr.Zero)
				return false;

			void* hAuthCryptMsg = null;
			var result = TryGetSignerInfo(
				fileName,
				out hAuthCryptMsg,
				out authSignData.hCertStoreHandle,
				out authSignData.pSignerInfo,
				out authSignData.dwObjSize
			);

			if (hAuthCryptMsg is not null)
			{
				PInvoke.CryptMsgClose(hAuthCryptMsg);
				hAuthCryptMsg = null;
			}

			if (!result)
			{
				if (authSignData.hCertStoreHandle != IntPtr.Zero)
					PInvoke.CertCloseStore(authSignData.hCertStoreHandle, 0);

				PInvoke.CertCloseStore(hSystemStore, 0);

Review comment (suggestion):
I think this would be better.

```cs
fixed (char* pRoot = "root")
{
    var hSystemStore = PInvoke.CertOpenStore(
        ...,
        (void*)pRoot);
}
```

Code after:
				return false;

			var result = PInvoke.CertComparePublicKeyInfo(
				ENCODING,
				&pCurrContext->pCertInfo->SubjectPublicKeyInfo,
				&pOrigContext->pCertInfo->SubjectPublicKeyInfo
			);

			return !result;
		}

		private unsafe static bool GetSignerCertificateInfo(string fileName, List<SignNodeInfo> signChain, CancellationToken ct)
		{
			var succeded = false;
			var authSignData = new SignDataHandle() { dwObjSize = 0, hCertStoreHandle = HCERTSTORE.Null, pSignerInfo = null };
			var signDataChain = new List<SignDataHandle>();
			signChain.Clear();

			var cert_store_prov_system = (PCSTR)(byte*)10;
			HCERTSTORE hSystemStore;
			fixed (char* pRoot = "Root")
			{
				hSystemStore = PInvoke.CertOpenStore(
					cert_store_prov_system,
					ENCODING,
					HCRYPTPROV_LEGACY.Null,
					(CERT_OPEN_STORE_FLAGS)CERT_SYSTEM_STORE_CURRENT_USER,
					(void*)pRoot
				); 
			}
			if (hSystemStore == IntPtr.Zero)
				return false;

			void* hAuthCryptMsg = null;
			var result = TryGetSignerInfo(
				fileName,
				out hAuthCryptMsg,
				out authSignData.hCertStoreHandle,
				out authSignData.pSignerInfo,
				out authSignData.dwObjSize
				);

			if (hAuthCryptMsg is not null)
			{
				PInvoke.CryptMsgClose(hAuthCryptMsg);
				hAuthCryptMsg = null;
			}

			if (!result)
			{
				if (authSignData.hCertStoreHandle != IntPtr.Zero)
Repository: firecracker-microvm/firecracker
File: tests/integration_tests/functional/test_rng.py (Python)

Code before:
# Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""Tests for the virtio-rng device"""

import pytest

from framework.properties import global_props
from framework.utils import check_entropy

if (
    global_props.cpu_model == "ARM_NEOVERSE_V1"
    and global_props.host_linux_version == "4.14"
):
    pytestmark = pytest.mark.skip(reason="[cm]7g requires no SVE 5.10 kernel")


@pytest.fixture(params=[None])
def uvm_with_rng(uvm_nano, request):
    """Fixture of a microvm with virtio-rng configured"""
    rate_limiter = request.param
    uvm_nano.add_net_iface()
    uvm_nano.api.entropy.put(rate_limiter=rate_limiter)
    uvm_nano.start()
    # Just stuff it in the microvm so we can look at it later
    uvm_nano.rng_rate_limiter = rate_limiter
    return uvm_nano


def test_rng_not_present(uvm_nano):
    """
    Test a guest microVM *without* an entropy device and ensure that
    we cannot get data from /dev/hwrng
    """

    vm = uvm_nano
    vm.add_net_iface()
    vm.start()

    # If the guest kernel has been built with the virtio-rng module

Review comment (suggestion):
I think it would better cover all cases and be more explicit to note:
```suggestion
    pytestmark = pytest.mark.skip(reason="Graviton 3 requires no SVE 5.10 kernel")
```

Code after:
# Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""Tests for the virtio-rng device"""

import pytest

from framework.properties import global_props
from framework.utils import check_entropy

if (
    global_props.cpu_model == "ARM_NEOVERSE_V1"
    and global_props.host_linux_version == "4.14"
):
    # Graviton3 instances in 4.14 require a non-SVE kernel to boot
    pytestmark = pytest.mark.skip(reason="[cm]7g requires non-SVE 5.10 kernel")


@pytest.fixture(params=[None])
def uvm_with_rng(uvm_nano, request):
    """Fixture of a microvm with virtio-rng configured"""
    rate_limiter = request.param
    uvm_nano.add_net_iface()
    uvm_nano.api.entropy.put(rate_limiter=rate_limiter)
    uvm_nano.start()
    # Just stuff it in the microvm so we can look at it later
    uvm_nano.rng_rate_limiter = rate_limiter
    return uvm_nano


def test_rng_not_present(uvm_nano):
    """
    Test a guest microVM *without* an entropy device and ensure that
    we cannot get data from /dev/hwrng
    """

    vm = uvm_nano
    vm.add_net_iface()
    vm.start()
Repository: firecracker-microvm/firecracker
File: tools/test.sh (Shell)

Code before:
say "cgroups v2: enable nesting"
CGROUP=/sys/fs/cgroup
if [ -f $CGROUP/cgroup.controllers -a -e $CGROUP/cgroup.type ]; then
    # move the processes from the root group to the /init group,
    # otherwise writing subtree_control fails with EBUSY.
    # An error during moving non-existent process (i.e., "cat") is ignored.
    mkdir -p $CGROUP/init
    xargs -rn1 < $CGROUP/cgroup.procs > $CGROUP/init/cgroup.procs || :
    # enable controllers
    sed -e 's/ / +/g' -e 's/^/+/' < $CGROUP/cgroup.controllers \
        > $CGROUP/cgroup.subtree_control
fi

say "Copy CI artifacts to /srv, so hardlinks work"
cp -ruvf build/img /srv

cd tests
export PYTEST_ADDOPTS="${PYTEST_ADDOPTS:-} --pdbcls=IPython.terminal.debugger:TerminalPdb"
pytest "$@"
ret=$?

# if the tests failed and we are running in CI, print some disk usage stats
# to help troubleshooting
if [ $ret != 0 ] && [ "$BUILDKITE" == "true" ]; then
    df -ih
    df -h
    du -h / 2>/dev/null |sort -h |tail -32
fi

exit $ret


Review comment (suggestion):
nit: maybe something like this is simpler?

```suggestion
ret=0
pytest "$@" || ret = $?
```

Code after:
say "cgroups v2: enable nesting"
CGROUP=/sys/fs/cgroup
if [ -f $CGROUP/cgroup.controllers -a -e $CGROUP/cgroup.type ]; then
    # move the processes from the root group to the /init group,
    # otherwise writing subtree_control fails with EBUSY.
    # An error during moving non-existent process (i.e., "cat") is ignored.
    mkdir -p $CGROUP/init
    xargs -rn1 < $CGROUP/cgroup.procs > $CGROUP/init/cgroup.procs || :
    # enable controllers
    sed -e 's/ / +/g' -e 's/^/+/' < $CGROUP/cgroup.controllers \
        > $CGROUP/cgroup.subtree_control
fi

say "Copy CI artifacts to /srv, so hardlinks work"
cp -ruvf build/img /srv

cd tests
export PYTEST_ADDOPTS="${PYTEST_ADDOPTS:-} --pdbcls=IPython.terminal.debugger:TerminalPdb"

{
    # disable errexit momentarily so we can capture the exit status
    set +e
    pytest "$@"
    ret=$?
    set -e
}

# if the tests failed and we are running in CI, print some disk usage stats
# to help troubleshooting
if [ $ret != 0 ] && [ "$BUILDKITE" == "true" ]; then
    df -ih
    df -h
    du -h / 2>/dev/null |sort -h |tail -32
fi

exit $ret
Repository: firecracker-microvm/firecracker
File: src/vmm/src/vmm_config/hotplug.rs (Rust)

Code before:
// Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use std::io;

use serde::{Deserialize, Serialize};

use crate::vstate::vcpu::VcpuError;
use crate::StartVcpusError;

/// Errors associated with hot-plugging vCPUs
#[derive(Debug, thiserror::Error, displaydoc::Display)]
pub enum HotplugVcpuError {
    /// The number of vCPUs added must be greater than 0.
    VcpuCountTooLow,
    /// The number of vCPUs added must be less than 32.
    VcpuCountTooHigh,
    /// Event fd error: {0}
    EventFd(io::Error),
    /// Error creating the vcpu: {0}
    VcpuCreate(VcpuError),
    /// Failed to start vCPUs
    VcpuStart(StartVcpusError),
}

/// Config for hotplugging vCPUS
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct HotplugVcpuConfig {
    /// Number of vcpus to start.
    pub vcpu_count: u8,
}


Review comment (suggestion):
If we will have 1 endpoint for all hot plugging I would prefer to have 1 enum that represents all options. Smth like this:
```rust
enum HotplugRequest {
  Vcpu(HotplugVcpu),
  // Memory(HotplugMemory),
}
```
This better represents available options. Additionally way we don't need to do any additional checks like you do in the `request/hotplug.rs`.

Code after:
}

/// Errors associated with hot-plugging vCPUs
#[derive(Debug, thiserror::Error, displaydoc::Display)]
pub enum HotplugVcpuError {
    /// The number of vCPUs added must be greater than 0.
    VcpuCountTooLow,
    /// The number of vCPUs added must be less than 32.
    VcpuCountTooHigh,
    /// Event fd error: {0}
    EventFd(io::Error),
    /// Error creating the vcpu: {0}
    VcpuCreate(VcpuError),
    /// Failed to start vCPUs
    VcpuStart(StartVcpusError),
    /// No seccomp filter for thread category: {0}
    MissingSeccompFilters(String),
}

/// Config for hotplugging vCPUS
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct HotplugVcpuConfig {
    /// Number of vcpus to start.
    pub add: u8,
}
Repository: firecracker-microvm/firecracker
File: src/vmm/src/vmm_config/hotplug.rs (Rust)

Code before:
pub enum HotplugRequestError {
    /// Vcpu hotplugging error: {0}
    Vcpu(#[from] HotplugVcpuError),
}

/// Errors associated with hot-plugging vCPUs
#[derive(Debug, thiserror::Error, displaydoc::Display)]
pub enum HotplugVcpuError {
    /// The number of vCPUs added must be greater than 0.
    VcpuCountTooLow,
    /// The number of vCPUs added must be less than 32.
    VcpuCountTooHigh,
    /// Event fd error: {0}
    EventFd(io::Error),
    /// Error creating the vcpu: {0}
    VcpuCreate(VcpuError),
    /// Failed to start vCPUs
    VcpuStart(StartVcpusError),
}

/// Config for hotplugging vCPUS
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct HotplugVcpuConfig {
    /// Number of vcpus to start.
    pub vcpu_count: u8,
}


Review comment (suggestion):
This comment needs a bit of clarification. Does `vcpu_count` represent the amount of vCPUs the VM will end up with after (successfully) handling this request? If yes, then we might not "start" any vCPUs. We might actually shut down some.

Code after:
    /// Vcpu hotplugging error: {0}
    Vcpu(#[from] HotplugVcpuError),
}

/// Errors associated with hot-plugging vCPUs
#[derive(Debug, thiserror::Error, displaydoc::Display)]
pub enum HotplugVcpuError {
    /// The number of vCPUs added must be greater than 0.
    VcpuCountTooLow,
    /// The number of vCPUs added must be less than 32.
    VcpuCountTooHigh,
    /// Event fd error: {0}
    EventFd(io::Error),
    /// Error creating the vcpu: {0}
    VcpuCreate(VcpuError),
    /// Failed to start vCPUs
    VcpuStart(StartVcpusError),
    /// No seccomp filter for thread category: {0}
    MissingSeccompFilters(String),
}

/// Config for hotplugging vCPUS
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct HotplugVcpuConfig {
    /// Number of vcpus to start.
    pub add: u8,
}
Repository: firecracker-microvm/firecracker
File: resources/rebuild.sh (Shell)

Code before:
function main {
    if [[ $# = 0 ]]; then
        local MODE="all"
    elif [[ "$1" == "all" ]]; then
        local MODE="all"
        shift
    elif [[ "$1" == "rootfs" ]]; then
        local MODE="rootfs"
        shift
    elif [[ "$1" == "kernels" ]]; then
        local MODE="kernels"
        shift
    elif [[ "$1" == "help" ]]; then
        print_help
        exit 0
    else
        die "Unknown arg: $1. Please use \`$0 help\` for help."
    fi

    set -x
        
    install_dependencies

    if [[ "$MODE" =~ (all|rootfs) ]]; then
        say "Building rootfs"
        prepare_and_build_rootfs
    fi

    if [[ "$MODE" =~ (all|kernels) ]]; then
        say "Building CI kernels"
        build_al_kernels "$@"
    fi

    tree -h $OUTPUT_DIR
}

main "$@"


Review comment (suggestion):
```
case $1 in 
    all|rootfs|kernels)
        local MODE=$1
        shift
    help)
        print_help
        exit 0
        ;;
    *)
        die Unknown
esac
```

Code after:
    
        version: Optionally choose a kernel version to build. Supported
                 versions are: 5.10, 5.10-no-acpi or 6.1.
    
    help
        Displays the help message and exits.
EOF
}

function main {
    if [[ $# = 0 ]]; then
        local MODE="all"
    else
        case $1 in
            all|rootfs|kernels)
                local MODE=$1
                shift
                ;;
            help)
                print_help
                exit 0
                ;;
            *)
                die "Unknown command: '$1'. Please use \`$0 help\` for help."
        esac
    fi

    set -x
        
    install_dependencies

    # Create the directory in which we will store the kernels and rootfs
    mkdir -pv $OUTPUT_DIR

    if [[ "$MODE" =~ (all|rootfs) ]]; then
        say "Building rootfs"
        prepare_and_build_rootfs
    fi

    if [[ "$MODE" =~ (all|kernels) ]]; then
        say "Building CI kernels"
        build_al_kernels "$@"
    fi

    tree -h $OUTPUT_DIR
}

main "$@"
Repository: firecracker-microvm/firecracker
File: src/vmm/src/arch/mod.rs (Rust)

Code before:
    /// Device Type: Serial.
    #[cfg(target_arch = "aarch64")]
    Serial,
    /// Device Type: RTC.
    #[cfg(target_arch = "aarch64")]
    Rtc,
    /// Device Type: BootTimer.
    BootTimer,
}

/// Type for passing information about the initrd in the guest memory.
#[derive(Debug)]
pub struct InitrdConfig {
    /// Load address of initrd in guest memory
    pub address: crate::vstate::memory::GuestAddress,
    /// Size of initrd in guest memory
    pub size: usize,
}

/// Default page size for the guest OS.
pub const GUEST_PAGE_SIZE: usize = 4096;

/// Default page size for the host OS.
pub static mut HOST_PAGE_SIZE: usize = 4096;

/// Updates the HOST_PAGE_SIZE global variable to the output of
/// sysconf(_SC_PAGESIZE). If call is unsuccessfull the default
/// value of 4096 remains.
pub fn update_host_page_size() {
    // # Safety:
    // There is nothing unsafe here.
    let r = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
    if r < 0 {
        warn!("Could not get host page size with sysconf, assuming default 4K host pages");
    } else {
        // # Safety:
        // The value is checked.
        unsafe { HOST_PAGE_SIZE = usize::try_from(r).unwrap() };
    }
}

impl fmt::Display for DeviceType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}


Review comment (suggestion):
Instead of modifying a global, could we make it a function that returns the pagesize? Or use `lazy_static!`.

Code after:
    Virtio(u32),
    /// Device Type: Serial.
    #[cfg(target_arch = "aarch64")]
    Serial,
    /// Device Type: RTC.
    #[cfg(target_arch = "aarch64")]
    Rtc,
    /// Device Type: BootTimer.
    BootTimer,
}

/// Type for passing information about the initrd in the guest memory.
#[derive(Debug)]
pub struct InitrdConfig {
    /// Load address of initrd in guest memory
    pub address: crate::vstate::memory::GuestAddress,
    /// Size of initrd in guest memory
    pub size: usize,
}

/// Default page size for the guest OS.
pub const GUEST_PAGE_SIZE: usize = 4096;

/// Get the size of the host page size.
pub fn host_page_size() -> usize {
    /// Default page size for the host OS.
    static PAGE_SIZE: LazyLock<usize> = LazyLock::new(|| {
        // # Safety: Value always valid
        let r = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
        usize::try_from(r).unwrap_or_else(|_| {
            warn!("Could not get host page size with sysconf, assuming default 4K host pages");
            4096
        })
    });

    *PAGE_SIZE
}

impl fmt::Display for DeviceType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}
Repository: firecracker-microvm/firecracker
File: resources/hiding_ci/build_and_install_kernel.sh (Shell)

Code before:
#!/bin/bash
# Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

# We need sudo privilleges to install the kernel
if [ "$(id -u)" -ne 0 ]; then
  echo "This script must be run as root or with sudo privileges"
  exit 1
fi

# Currently this script only works on Ubuntu instances
if ! grep -qi 'ubuntu' /etc/os-release; then
  echo "This script currently only works on Ubuntu."
  exit 1
fi

confirm() {
  if [[ "$*" == *"--no-install"* ]]; then
    echo "Not installing new kernel."
    exit 1
  fi

  if [[ "$*" == *"--install"* ]]; then
    return 0
  fi

  while true; do
    read -p "Do you want to install the new kernel? (y/n) " yn
    case $yn in
    [Yy]*) return 0 ;;
    [Nn]*)
      echo "Exiting..."
      exit 1
      ;;
    *) echo "Please answer yes or no." ;;
    esac
  done
}

KERNEL_URL=$(cat kernel_url)
KERNEL_COMMIT_HASH=$(cat kernel_commit_hash)
KERNEL_VERSION=$(cat kernel_version)
KERNEL_PATCHES_DIR=$(pwd)/patches
KERNEL_CONFIG_OVERRIDES=$(pwd)/kernel_config_overrides


Review comment (bug):
this'll need to be an `exit 0`, otherwise if we try to run this from pytest as an integration test it'll fail :/

Code after:
#!/bin/bash
# Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

# fail if we encounter an error, uninitialized variable or a pipe breaks
set -eu -o pipefail

check_root() {
  # We need sudo privileges to install the kernel
  if [ "$(id -u)" -ne 0 ]; then
    echo "To install, this script must be run as root or with sudo privileges"
    exit 1
  fi
}

check_ubuntu() {
  # Currently this script only works on Ubuntu instances
  if ! grep -qi 'ubuntu' /etc/os-release; then
    echo "This script currently only works on Ubuntu."
    exit 1
  fi
}

tidy_up() {
  # Some cleanup after we are done
  echo "Cleaning up.."
  popd
  rm -rf $TMP_BUILD_DIR
}

confirm() {
  if [[ "$*" == *"--no-install"* ]]; then
    echo "Not installing new kernel."

    if [[ "$*" == *"--tidy"* ]]; then
      tidy_up
    fi

    exit 0
  fi

  if [[ "$*" == *"--install"* ]]; then
    return 0
  fi
Repository: firecracker-microvm/firecracker
File: resources/hiding_ci/build_and_install_kernel.sh (Shell)

Code before:
}

KERNEL_URL=$(cat kernel_url)
KERNEL_COMMIT_HASH=$(cat kernel_commit_hash)
KERNEL_VERSION=$(cat kernel_version)
KERNEL_PATCHES_DIR=$(pwd)/patches
KERNEL_CONFIG_OVERRIDES=$(pwd)/kernel_config_overrides

TMP_BUILD_DIR=$(mktemp -d -t kernel-build-XXXX)

pushd .
cd $TMP_BUILD_DIR

echo "Cloning kernel repository into" $TMP_BUILD_DIR

# We checkout the repository that way to make it as
# small and fast as possible
git init
git remote add origin $KERNEL_URL
git fetch --depth 1 origin $KERNEL_COMMIT_HASH
git checkout FETCH_HEAD

# Apply our patches on top
for PATCH in $KERNEL_PATCHES_DIR/*.patch; do
  echo "Applying patch:" $(basename $PATCH)
  git apply $PATCH
done

echo "Making kernel config ready for build"
# We use olddefconfig to automatically pull in the
# config from the AMI and update to the newest
# defaults
make olddefconfig

# Disable the ubuntu keys
scripts/config --disable SYSTEM_TRUSTED_KEYS
scripts/config --disable SYSTEM_REVOCATION_KEYS

# Apply our config overrides on top of the config
scripts/kconfig/merge_config.sh .config $KERNEL_CONFIG_OVERRIDES

# Finally run olddefconfig again to make sure any
# new options are configured before build
make olddefconfig

echo "Building kernel this may take a while"
make -j $(nproc)
echo "Building kernel modules"
make modules -j $(nproc)
echo "Kernel build complete!"


Review comment (suggestion):
mh, I kinda assumed that we'd be storing the output of `git format-patch`, not `git diff`, so this should be `git am` instead of `git apply`

Code after:

    exit 0
  fi

  if [[ "$*" == *"--install"* ]]; then
    return 0
  fi

  while true; do
    read -p "Do you want to install the new kernel? (y/n) " yn
    case $yn in
    [Yy]*) return 0 ;;
    [Nn]*)
      echo "Exiting..."
      exit 1
      ;;
    *) echo "Please answer yes or no." ;;
    esac
  done
}

apply_patch_file() {
  git apply $1
}

apply_series_mbox() {
  git am $1 --empty=drop
}

apply_series_link() {
  patch_url=$(cat $1)
  echo "Fetching mbox from:" $patch_url
  curl --output lore.mbox.gz "$patch_url/t.mbox.gz"
  gunzip lore.mbox
  apply_series_mbox lore.mbox
  rm lore.mbox
}

apply_patch_or_series() {
  case "$1" in
  *.patch) apply_patch_file $1 ;;
  *.mbox) apply_series_mbox $1 ;;
  *.lore) apply_series_link $1 ;;
  *)
    echo "Uknown patch file: "$1
    exit 1
    ;;
  esac
}

check_override_presence() {
Repository: firecracker-microvm/firecracker
File: resources/hiding_ci/build_and_install_kernel.sh (Shell)

Code before:
git remote add origin $KERNEL_URL
git fetch --depth 1 origin $KERNEL_COMMIT_HASH
git checkout FETCH_HEAD

# Apply our patches on top
for PATCH in $KERNEL_PATCHES_DIR/*.patch; do
  echo "Applying patch:" $(basename $PATCH)
  git apply $PATCH
done

echo "Making kernel config ready for build"
# We use olddefconfig to automatically pull in the
# config from the AMI and update to the newest
# defaults
make olddefconfig

# Disable the ubuntu keys
scripts/config --disable SYSTEM_TRUSTED_KEYS
scripts/config --disable SYSTEM_REVOCATION_KEYS

# Apply our config overrides on top of the config
scripts/kconfig/merge_config.sh .config $KERNEL_CONFIG_OVERRIDES

# Finally run olddefconfig again to make sure any
# new options are configured before build
make olddefconfig

echo "Building kernel this may take a while"
make -j $(nproc)
echo "Building kernel modules"
make modules -j $(nproc)
echo "Kernel build complete!"

# Make sure a user really wants to install this kernel
confirm "$@"

echo "Installing kernel modules..."
make INSTALL_MOD_STRIP=1 modules_install
echo "Installing kernel..."
make INSTALL_MOD_STRIP=1 install
echo "Update initramfs"
update-initramfs -c -k $KERNEL_VERSION
echo "Updating GRUB..."
update-grub

echo "Kernel built and installed successfully!"

# Some cleanup after we are done
popd
rm -rf $TMP_BUILD_DIR


Review comment (bug):
Should we add some sort of assertion here to verify that .config contains everything we specify in kernel_config_overwrites? Just as a sanity check, to avoid ever running into any hard/weird to debug issues

Code after:
  done
}

apply_patch_file() {
  git apply $1
}

apply_series_mbox() {
  git am $1 --empty=drop
}

apply_series_link() {
  patch_url=$(cat $1)
  echo "Fetching mbox from:" $patch_url
  curl --output lore.mbox.gz "$patch_url/t.mbox.gz"
  gunzip lore.mbox
  apply_series_mbox lore.mbox
  rm lore.mbox
}

apply_patch_or_series() {
  case "$1" in
  *.patch) apply_patch_file $1 ;;
  *.mbox) apply_series_mbox $1 ;;
  *.lore) apply_series_link $1 ;;
  *)
    echo "Uknown patch file: "$1
    exit 1
    ;;
  esac
}

check_override_presence() {
  while IFS= read -r line; do
    if ! grep -Fq "$line" .config; then
      echo "Missing config: $line"
      exit 1
    fi
  done <"$KERNEL_CONFIG_OVERRIDES"

  echo "All overrides correctly applied.."
}

KERNEL_URL=$(cat kernel_url)
KERNEL_COMMIT_HASH=$(cat kernel_commit_hash)
KERNEL_PATCHES_DIR=$(pwd)/patches
KERNEL_CONFIG_OVERRIDES=$(pwd)/kernel_config_overrides

TMP_BUILD_DIR=$(mktemp -d -t kernel-build-XXXX)

pushd .