/**
 * 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 "../includes/common.h"
#include <binder/IServiceManager.h>
#include <binder/Parcel.h>
#include <stdio.h>

using namespace android;

int main(void) {
  status_t err;
  sp<IServiceManager> sm = defaultServiceManager();
  String16 name(String16("gpu"));
  sp<IBinder> service = sm->checkService(name);
  String16 interface_name = service->getInterfaceDescriptor();

  Parcel data, reply;
  std::string UpdatableDriverPath("CVE-2020-0420");
  data.writeInterfaceToken(interface_name);
  data.writeUtf8AsUtf16(UpdatableDriverPath);
  err = service->transact(3 /*SET_UPDATABLE_DRIVER_PATH,*/, data, &reply, 0);
  if (err != OK) {
    return EXIT_FAILURE;
  }

  Parcel data1, reply1;
  data1.writeInterfaceToken(interface_name);
  err = service->transact(4 /*GET_UPDATABLE_DRIVER_PATH,*/, data1, &reply1, 0);
  if (err != OK) {
    return EXIT_FAILURE;
  }
  std::string driverPath;
  err = reply1.readUtf8FromUtf16(&driverPath);
  if (err != OK) {
    return EXIT_FAILURE;
  }

  /** If the driver path returned is same as that was set, then there is no
   * check in the API and the vulnerability is present.
   */
  if (0 == strcmp(driverPath.c_str(), UpdatableDriverPath.c_str())) {
    return EXIT_VULNERABLE;
  }

  return EXIT_SUCCESS;
}
