/**
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "../includes/common.h"
#include <dlfcn.h>
#include <libxml/xmlmemory.h>
#include <stdlib.h>
#include <string.h>

bool s_strlen_initialized = false;
static unsigned long (*real_strlen)(const char *) = nullptr;

#define TEST_STRING "CVE-2018_9472_Simulate_OverFlow_By_Large_String_Length"
#define LARGE_SIZE ((size_t)-2)

void strlen_init(void) {
  real_strlen = (unsigned long (*)(const char *))dlsym(RTLD_NEXT, "strlen");
  if (real_strlen) {
    s_strlen_initialized = true;
  }
}

size_t strlen(const char *str) {
  if (!s_strlen_initialized) {
    strlen_init();
  }
  if (!strncmp(str, TEST_STRING, sizeof(TEST_STRING))) {
    return LARGE_SIZE;
  }
  return real_strlen(str);
}

int main() {
  if (xmlMemStrdupLoc(TEST_STRING, "none", 0)) {
    return EXIT_VULNERABLE;
  }
  return EXIT_SUCCESS;
}