/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch licenses this file to you 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.
 */

package org.elasticsearch.bootstrap;

import org.apache.lucene.index.MergePolicy;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;

import java.io.IOError;
import java.util.Objects;
import java.util.function.Supplier;

class ElasticsearchUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    private final Supplier<String> loggingPrefixSupplier;

    ElasticsearchUncaughtExceptionHandler(final Supplier<String> loggingPrefixSupplier) {
        this.loggingPrefixSupplier = Objects.requireNonNull(loggingPrefixSupplier);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if (isFatalUncaught(e)) {
            try {
                onFatalUncaught(t.getName(), e);
            } finally {
                // we use specific error codes in case the above notification failed, at least we
                // will have some indication of the error bringing us down
                if (e instanceof InternalError) {
                    halt(128);
                } else if (e instanceof OutOfMemoryError) {
                    halt(127);
                } else if (e instanceof StackOverflowError) {
                    halt(126);
                } else if (e instanceof UnknownError) {
                    halt(125);
                } else if (e instanceof IOError) {
                    halt(124);
                } else {
                    halt(1);
                }
            }
        } else {
            onNonFatalUncaught(t.getName(), e);
        }
    }

    // visible for testing
    static boolean isFatalUncaught(Throwable e) {
        return isFatalCause(e) || (e instanceof MergePolicy.MergeException && isFatalCause(e.getCause()));
    }

    private static boolean isFatalCause(Throwable cause) {
        return cause instanceof Error;
    }

    // visible for testing
    void onFatalUncaught(final String threadName, final Throwable t) {
        final ESLogger logger = Loggers.getLogger(ElasticsearchUncaughtExceptionHandler.class, loggingPrefixSupplier.get());
        logger.error("fatal error in thread [{}], exiting", t, threadName);
    }

    // visible for testing
    void onNonFatalUncaught(final String threadName, final Throwable t) {
        final ESLogger logger = Loggers.getLogger(ElasticsearchUncaughtExceptionHandler.class, loggingPrefixSupplier.get());
        logger.warn("uncaught exception in thread [{}]", t, threadName);
    }

    // visible for testing
    @SuppressForbidden(reason = "halt")
    void halt(int status) {
        // we halt to prevent shutdown hooks from running
        Runtime.getRuntime().halt(status);
    }

}

@@ -1040,16 +1040,94 @@
 OError;%0A
+import java.security.AccessController;%0Aimport java.security.PrivilegedAction;%0A
 import j
@@ -3427,72 +3427,211 @@
     
-@SuppressForbidden(reason = %22halt%22)%0A    void halt(int status) %7B%0A
+void halt(int status) %7B%0A        AccessController.doPrivileged(new PrivilegedAction%3CVoid%3E() %7B%0A            @SuppressForbidden(reason = %22halt%22)%0A            @Override%0A            public Void run() %7B%0A        
     
@@ -3692,16 +3692,24 @@
         
+       
+ 
 Runtime.
@@ -3735,16 +3735,71 @@
 tatus);%0A
+                return null;%0A            %7D%0A        %7D);%0A
     %7D%0A%0A%7D

Mark halting the virtual machine as privileged