/**
 * 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 <hwbinder/Parcel.h>

using namespace android::hardware;

int main() {
    int32_t numFds = 1;
    int32_t numInts = 0;
    android::status_t err = android::NO_ERROR;

    native_handle_t *nativeHandleSend = native_handle_create(numFds, numInts);
    Parcel *parcel = new Parcel();
    err = parcel->writeNativeHandleNoDup(nativeHandleSend);
    if (err != android::NO_ERROR) {
        return EXIT_FAILURE;
    }
    parcel->setDataPosition(0);

    nativeHandleSend->numInts = 1024;

    const native_handle_t *nativeHandleReceive = nullptr;
    err = parcel->readNativeHandleNoDup(&nativeHandleReceive);
    if (err == android::NO_ERROR) {
        native_handle_t *tempHandle = const_cast<native_handle_t *>(nativeHandleReceive);
        for (numInts = nativeHandleReceive->numFds; numInts < nativeHandleReceive->numInts;
             ++numInts) {
            ++tempHandle->data[numInts];
        }
    }

    // The fix is to validate the nativeHandle size and return an error. Hence
    // if control reaches here, the patch is present. Return EXIT_SUCCESS
    delete parcel;
    native_handle_delete(nativeHandleSend);
    return EXIT_SUCCESS;
}
