/* SPDX-FileCopyrightText: 2024 Google LLC */
/* SPDX-License-Identifier: Apache-2.0 */

//! @file ${filename}
//! This file is autogenerated by tools/applib_malloc.py


#include "kernel/pbl_malloc.h"
#include "kernel/pebble_tasks.h"
#include "mcu/privilege.h"
#include "process_management/process_manager.h"
#include "system/passert.h"


${includes}


typedef struct {
  size_t actual_size; //!< The size of the struct as it's currently implemented without padding
  size_t size_2x; //!< The size we struct allocation should be for legacy2 apps
  size_t size_3x; //!< The size we struct allocation should be for 3.x apps
} ApplibTypeInfo;

typedef enum {
  ${applib_enum_types}
} ApplibType;


static const ApplibTypeInfo s_applib_malloc_types[] = {
  ${applib_malloc_types}
};


static size_t prv_find_size(int index) {
  const ApplibTypeInfo *type = &s_applib_malloc_types[index];

  if (mcu_state_is_thread_privileged()) {
    return type->actual_size;
  }

  if (process_manager_compiled_with_legacy2_sdk()) {
    return type->size_2x;
  }

  return type->size_3x;
}

static void* prv_malloc(size_t size, uintptr_t client_pc) {
  if (!size) {
    return NULL;
  }

#if defined(MALLOC_INSTRUMENTATION)
  void *result = task_malloc_with_pc(size, client_pc);
#else
  void *result = task_malloc(size);
#endif

  if (!result && mcu_state_is_thread_privileged()) {
    // We want to trip an assert if our malloc failed and we're not running a 3rd party app.
    PBL_CROAK_OOM(size, client_pc, task_heap_get_for_current_task());
  }

  return result;
}

static void* prv_zalloc(size_t size, uintptr_t client_pc) {
  void *result = prv_malloc(size, client_pc);

  if (result) {
    memset(result, 0, size);
  }

  return result;
}

void* applib_malloc(size_t size) {
#if defined(MALLOC_INSTRUMENTATION)
  register uintptr_t lr __asm("lr");
  uintptr_t saved_lr = lr;
  return prv_malloc(size, saved_lr);
#else
  return prv_malloc(size, 0);
#endif
}

void* applib_zalloc(size_t size) {
#if defined(MALLOC_INSTRUMENTATION)
  register uintptr_t lr __asm("lr");
  uintptr_t saved_lr = lr;
  return prv_zalloc(size, saved_lr);
#else
  return prv_zalloc(size, 0);
#endif
}

void applib_free(void *ptr) {
#if defined(MALLOC_INSTRUMENTATION)
  register uintptr_t lr __asm("lr");
  uintptr_t saved_lr = lr;
  task_free_with_pc(ptr, saved_lr);
#else
  task_free(ptr);
#endif
}
