/*
 * SNOOPY COMMAND LOGGER
 *
 * Copyright (c) 2000 Marius Aamodt Eriksen <marius@linux.com>
 * Copyright (c) 2000 Mike Baker <mbm@linux.com>
 * Copyright (c) 2010-2015 Bostjan Skufca <bostjan@a2o.si>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */



/*
 * Includes order: from local to global
 */
#include "execve-wrapper-test-configfile-env.h"

#include "snoopy.h"

#include "init-deinit.h"

#include "action/log-syscall-exec.h"
#include "configuration.h"
#include "inputdatastorage.h"

#include <dlfcn.h>
#include <stddef.h>



/*
 * Helpers to find pointer to overloaded function
 */
#if defined(RTLD_NEXT)
#  define REAL_LIBC RTLD_NEXT
#else
#  define REAL_LIBC ((void *) -1L)
#endif

#define FN(ptr, type, name, args)   ptr = (type (*)args)dlsym (REAL_LIBC, name)



/*
 * Function wrapper - execv()
 */
__attribute__((visibility("default"))) int execv (const char *filename, char *const argv[]) {
    static int (*func)(const char *, char * const *);

    FN(func, int, "execv", (const char *, char * const *));

    char *envp[] = { NULL };
    snoopy_entrypoint_execve_wrapper_test_configfile_env_init(filename, argv, envp);
    snoopy_action_log_syscall_exec();
    snoopy_entrypoint_execve_wrapper_test_configfile_env_exit();

    return (*func) (filename, argv);
}



/*
 * Function wrapper - execve()
 */
__attribute__((visibility("default"))) int execve (const char *filename, char *const argv[], char *const envp[])
{
    static int (*func)(const char *, char * const *, char * const *);

    FN(func, int, "execve", (const char *, char * const *, char * const *));

    snoopy_entrypoint_execve_wrapper_test_configfile_env_init(filename, argv, envp);
    snoopy_action_log_syscall_exec();
    snoopy_entrypoint_execve_wrapper_test_configfile_env_exit();

    return (*func) (filename, argv, envp);
}



void snoopy_entrypoint_execve_wrapper_test_configfile_env_init (const char *filename, char *const argv[], char *const envp[])
{
    snoopy_configuration_preinit_setConfigFilePathFromEnv();

    snoopy_init();

    snoopy_inputdatastorage_store_filename(filename);
    snoopy_inputdatastorage_store_argv(argv);
    snoopy_inputdatastorage_store_envp(envp);
}



void snoopy_entrypoint_execve_wrapper_test_configfile_env_exit ()
{
    snoopy_cleanup();
}
