/* -*- c-file-style: "GNU" -*- */
/*
 * Copyright (C) CNRS, INRIA, Université Bordeaux 1, Télécom SudParis
 * See COPYING in top-level directory.
 */

/* This file contains an alternative libexample.so
 * The functions defined in libexample (example_function1 and
 * example_function2) are redefined so that when the application
 * call one of these functions, the hereby version of it is actually
 * invoked.
 */

#include <eztrace-core/eztrace_config.h>
#include <eztrace-lib/eztrace.h>
#include <eztrace-lib/eztrace_module.h>

#define CURRENT_MODULE example
DECLARE_CURRENT_MODULE;
int __example_initialized = 0;


/* pointers to the actual functions (located in the original
 * libexample.so)
 */
double (*libexample_function1)(double*, int) = NULL;
double (*libexample_static_function)(double*, int) = NULL;
int (*libexample_function2)(int*, int) = NULL;

/* redefine example_function1.
 * This version of the function only record some events and calls
 * the original example_function1 function
 */
double example_function1(double *array, int array_size) {
  /* records an event with two parameters
   */
  FUNCTION_ENTRY_WITH_ARGS(array, array_size);

  /* call the actual function (located in the original libexample.so) */
  double ret = libexample_function1(array, array_size);

  /* records another event without any parameter
   */
  FUNCTION_EXIT;
  return ret;
}

double example_static_function(double*array, int array_size) {
  FUNCTION_ENTRY_WITH_ARGS(array, array_size);

  /* call the actual function (located in the original libexample.so) */
  double ret = libexample_static_function(array, array_size);

  /* record another event with three parameters
   */
  FUNCTION_EXIT_WITH_ARGS(array, array_size, ret);
  return ret;
}

/* redefine example_function2.
 * This version of the function only record some events and calls
 * the original example_function2 function
 */
int example_function2(int *array, int array_size) {
  FUNCTION_ENTRY_WITH_ARGS(array, array_size);
  int ret = libexample_function2(array, array_size);
  FUNCTION_EXIT;
  return ret;
}

PPTRACE_START_INTERCEPT_FUNCTIONS(example)
  INTERCEPT3("example_function1", libexample_function1)
  INTERCEPT3("example_static_function", libexample_static_function)
  INTERCEPT3("example_function2", libexample_function2)
PPTRACE_END_INTERCEPT_FUNCTIONS(example);


static void init_example() {
  INSTRUMENT_FUNCTIONS(example);

  if (eztrace_autostart_enabled())
    eztrace_start();

  __example_initialized = 1;
}

static void finalize_example() {
  __example_initialized = 0;
  eztrace_stop();
}

void __example_init(void) __attribute__ ((constructor));
/* Initialize the current library */
void __example_init(void) {
  EZT_REGISTER_MODULE(example, "Example module", init_example, finalize_example);
}
