// SPDX-FileCopyrightText: 2024 Redict Contributors
// SPDX-FileCopyrightText: 2024 Salvatore Sanfilippo <antirez at gmail dot com>
//
// SPDX-License-Identifier: BSD-3-Clause
// SPDX-License-Identifier: LGPL-3.0-only

#include "redictmodule.h"

#include <strings.h>
#include <sys/mman.h>

#define UNUSED(V) ((void) V)

void assertCrash(RedictModuleInfoCtx *ctx, int for_crash_report) {
    UNUSED(ctx);
    UNUSED(for_crash_report);
    RedictModule_Assert(0);
}

void segfaultCrash(RedictModuleInfoCtx *ctx, int for_crash_report) {
    UNUSED(ctx);
    UNUSED(for_crash_report);
    /* Compiler gives warnings about writing to a random address
     * e.g "*((char*)-1) = 'x';". As a workaround, we map a read-only area
     * and try to write there to trigger segmentation fault. */
    char *p = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    *p = 'x';
}

int RedictModule_OnLoad(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    if (RedictModule_Init(ctx,"infocrash",1,REDICTMODULE_APIVER_1)
            == REDICTMODULE_ERR) return REDICTMODULE_ERR;
    RedictModule_Assert(argc == 1);
    if (!strcasecmp(RedictModule_StringPtrLen(argv[0], NULL), "segfault")) {
        if (RedictModule_RegisterInfoFunc(ctx, segfaultCrash) == REDICTMODULE_ERR) return REDICTMODULE_ERR;
    } else if(!strcasecmp(RedictModule_StringPtrLen(argv[0], NULL), "assert")) {
        if (RedictModule_RegisterInfoFunc(ctx, assertCrash) == REDICTMODULE_ERR) return REDICTMODULE_ERR;
    } else {
        return REDICTMODULE_ERR;
    }

    return REDICTMODULE_OK;
}
