<commit_before>/*
 * The MIT License
 *
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., <NAME>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package hudson.util;

import static com.sun.jna.Pointer.NULL;
import static hudson.util.jna.GNUCLibrary.LIBC;
import static java.util.logging.Level.FINER;
import static java.util.logging.Level.FINEST;

import com.sun.jna.LastErrorException;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.NativeLongByReference;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Util;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.util.ProcessKillingVeto.VetoCause;
import hudson.util.ProcessTree.OSProcess;
import hudson.util.ProcessTreeRemoting.IOSProcess;
import hudson.util.ProcessTreeRemoting.IProcessTree;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.SortedMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.agents.AgentComputerUtil;
import jenkins.security.SlaveToMasterCallable;
import jenkins.util.SystemProperties;
import jenkins.util.java.JavaUtils;
import org.apache.commons.io.FileUtils;
import org.jenkinsci.remoting.SerializableOnlyOverRemoting;
import org.jvnet.winp.WinProcess;
import org.jvnet.winp.WinpException;

/**
 * Represents a snapshot of the process tree of the current system.
 *
 * <p>
 * A {@link ProcessTree} is really conceptually a map from process ID to a {@link OSProcess} object.
 * When Hudson runs on platforms that support process introspection, this allows you to introspect
 * and do some useful things on processes. On other platforms, the implementation falls back to
 * "do nothing" behavior.
 *
 * <p>
 * {@link ProcessTree} is remotable.
 *
 * @author <NAME>
 * @since 1.315
 */
public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree, SerializableOnlyOverRemoting {
    /**
     * To be filled in the constructor of the derived type.
     */
    protected final Map<Integer/*pid*/, OSProcess> processes = new HashMap<>();

    /**
     * Lazily obtained {@link ProcessKiller}s to be applied on this process tree.
     */
    private transient volatile List<ProcessKiller> killers;

    /**
     * Flag to skip the veto check since there aren't any.
     */
    private boolean skipVetoes;

    // instantiation only allowed for subtypes in this class
    private ProcessTree() {
       skipVetoes = false;
    }

    private ProcessTree(boolean vetoesExist) {
        skipVetoes = !vetoesExist;
    }

    /**
     * Gets the process given a specific ID, or null if no such process exists.
     */
    @CheckForNull
    public final OSProcess get(int pid) {
        return processes.get(pid);
    }

    /**
     * Lists all the processes in the system.
     */
    @Override
    @NonNull
    public final Iterator<OSProcess> iterator() {
        return processes.values().iterator();
    }

    /**
     * Try to convert {@link Process} into this process object
     * or null if it fails (for example, maybe the snapshot is taken after
     * this process has already finished.)
     */
    @CheckForNull
    public abstract OSProcess get(@NonNull Process proc);

    /**
     * Kills all the processes that have matching environment variables.
     *
     * <p>
     * In this method, the method is given a
     * "model environment variables", which is a list of environment variables
     * and their values that are characteristic to the launched process.
     * The implementation is expected to find processes
     * in the system that inherit these environment variables, and kill
     * them all. This is suitable for locating daemon processes
     * that cannot be tracked by the regular ancestor/descendant relationship.
     */
    @Override
    public abstract void killAll(@NonNull Map<String, String> modelEnvVars) throws InterruptedException;

    /**
     * The time to wait between sending Ctrl+C and killing the process. (JENKINS-17116)
     *
     * The default is 5 seconds. Careful! There are other timers in the system that may
     * interfere with this value here, e.g. in org.jenkinsci.plugins.workflow.cps.CpsThread.stop
     */
    private final long softKillWaitSeconds = Integer.getInteger("SoftKillWaitSeconds", 5);

    /**
     * Convenience method that does {@link #killAll(Map)} and {@link OSProcess#killRecursively()}.
     * This is necessary to reliably kill the process and its descendants, as some OS
     * may not implement {@link #killAll(Map)}.
     *
     * Either of the parameter can be null.
     */
    public void killAll(@CheckForNull Process proc, @CheckForNull Map<String, String> modelEnvVars) throws InterruptedException {
        LOGGER.fine("killAll: process=" + proc + " and envs=" + modelEnvVars);

        if (proc != null) {
            OSProcess p = get(proc);
            if (p != null) p.killRecursively();
        }

        if (modelEnvVars != null)
            killAll(modelEnvVars);
    }

    /**
     * Obtains the list of killers.
     */
    @NonNull
    /*package*/ final List<ProcessKiller> getKillers() throws InterruptedException {
        if (killers == null)
            try {
                VirtualChannel channelToController = AgentComputerUtil.getChannelToController();
                if (channelToController != null) {
                    killers = channelToController.call(new ListAll());
                } else {
                    // used in an environment that doesn't support talk-back to the master.
                    // let's do with what we have.
                    killers = Collections.emptyList();
                }
            } catch (IOException | Error e) {
                LOGGER.log(Level.WARNING, "Failed to obtain killers", e);
                killers = Collections.emptyList();
            }
        return killers;
    }

    private static class ListAll extends SlaveToMasterCallable<List<ProcessKiller>, IOException> {
        @Override
        public List<ProcessKiller> call() throws IOException {
            return new ArrayList<>(ProcessKiller.all());
        }
    }

    /**
     * Represents a process.
     */
    public abstract class OSProcess implements IOSProcess, Serializable {
        final int pid;

        // instantiation only allowed for subtypes in this class
        private OSProcess(int pid) {
            this.pid = pid;
        }

        @Override
        public final int getPid() {
            return pid;
        }
        /**
         * Gets the parent process. This method may return null, because
         * there's no guarantee that we are getting a consistent snapshot
         * of the whole system state.
         */

        @Override
        @CheckForNull
        public abstract OSProcess getParent();

        /*package*/ final ProcessTree getTree() {
            return ProcessTree.this;
        }

        /**
         * Immediate child processes.
         */
        @NonNull
        public final List<OSProcess> getChildren() {
            List<OSProcess> r = new ArrayList<>();
            for (OSProcess p : ProcessTree.this)
                if (p.getParent() == this)
                    r.add(p);
            return r;
        }

        /**
         * Kills this process.
         */
        @Override
        public abstract void kill() throws InterruptedException;

        void killByKiller() throws InterruptedException {
            for (ProcessKiller killer : getKillers())
                try {
                    if (killer.kill(this)) {
                        break;
                    }
                } catch (IOException | Error e) {
                    LOGGER.log(Level.WARNING, "Failed to kill pid=" + getPid(), e);
                }
        }

        /**
         * Kills this process and all the descendants.
         * <p>
         * Note that the notion of "descendants" is somewhat vague,
         * in the presence of such things like daemons. On platforms
         * where the recursive operation is not supported, this just kills
         * the current process.
         */
        @Override
        public abstract void killRecursively() throws InterruptedException;

        /**
         * @return The first non-null {@link VetoCause} provided by a process killing veto extension for this OSProcess.
         * null if no one objects killing the process.
         */
        protected @CheckForNull VetoCause getVeto() {
            String causeMessage = null;

            // Quick check, does anything exist to check against
            if (!skipVetoes) {
                try {
                    VirtualChannel channelToController = AgentComputerUtil.getChannelToController();
                    if (channelToController != null) {
                        CheckVetoes vetoCheck = new CheckVetoes(this);
                        causeMessage = channelToController.call(vetoCheck);
                    }
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "I/O Exception while checking for vetoes", e);
                } catch (InterruptedException e) {
                    LOGGER.log(Level.WARNING, "Interrupted Exception while checking for vetoes", e);
                }
            }

            if (causeMessage != null) {
                return new VetoCause(causeMessage);
            }
            return null;
        }

        /**
         * Gets the command-line arguments of this process.
         *
         * <p>
         * On Windows, where the OS models command-line arguments as a single string, this method
         * computes the approximated tokenization.
         */
        @Override
        @NonNull
        public abstract List<String> getArguments();

        /**
         * Obtains the environment variables of this process.
         *
         * @return
         *      empty map if failed (for example because the process is already dead,
         *      or the permission was denied.)
         */
        @Override
        @NonNull
        public abstract EnvVars getEnvironmentVariables();

        /**
         * Given the environment variable of a process and the "model environment variable" that Hudson
         * used for launching the build, returns true if there's a match (which means the process should
         * be considered a descendant of a build.)
         */
        public final boolean hasMatchingEnvVars(Map<String, String> modelEnvVar) {
            if (modelEnvVar.isEmpty())
                // sanity check so that we don't start rampage.
                return false;

            SortedMap<String, String> envs = getEnvironmentVariables();
            for (Map.Entry<String, String> e : modelEnvVar.entrySet()) {
                String v = envs.get(e.getKey());
                if (v == null || !v.equals(e.getValue()))
                    return false;   // no match
            }

            return true;
        }

        /**
         * Executes a chunk of code at the same machine where this process resides.
         */
        @Override
        public <T> T act(ProcessCallable<T> callable) throws IOException, InterruptedException {
            return callable.invoke(this, FilePath.localChannel);
        }

        Object writeReplace() {
            return new SerializedProcess(pid);
        }

        private class CheckVetoes extends SlaveToMasterCallable<String, IOException> {
            private IOSProcess process;

            CheckVetoes(IOSProcess processToCheck) {
                process = processToCheck;
            }

            @Override
            public String call() throws IOException {
                for (ProcessKillingVeto vetoExtension : ProcessKillingVeto.all()) {
                    VetoCause cause = vetoExtension.vetoProcessKilling(process);
                    if (cause != null) {
                        if (LOGGER.isLoggable(FINEST))
                            LOGGER.info("Killing of pid " + getPid() + " vetoed by " + vetoExtension.getClass().getName() + ": " + cause.getMessage());
                        return cause.getMessage();
                    }
                }
                return null;
            }
        }
    }

    /**
     * Serialized form of {@link OSProcess} is the PID and {@link ProcessTree}
     */
    @SuppressFBWarnings(value = "SE_INNER_CLASS", justification = "Serializing the outer instance is intended")
    private final class SerializedProcess implements Serializable {
        private final int pid;
        private static final long serialVersionUID = 1L;

        private SerializedProcess(int pid) {
            this.pid = pid;
        }

        Object readResolve() {
            return get(pid);
        }
    }

    /**
     * Code that gets executed on the machine where the {@link OSProcess} is local.
     * Used to act on {@link OSProcess}.
     *
     * @see ProcessTree.OSProcess#act(ProcessTree.ProcessCallable)
     */
    public interface ProcessCallable<T> extends Serializable {
        /**
         * Performs the computational task on the node where the data is located.
         *
         * @param process
         *      {@link OSProcess} that represents the local process.
         * @param channel
         *      The "back pointer" of the {@link Channel} that represents the communication
         *      with the node from where the code was sent.
         */
        T invoke(OSProcess process, VirtualChannel channel) throws IOException;
    }


    /* package */ static volatile Boolean vetoersExist;

    /**
     * Gets the {@link ProcessTree} of the current system
     * that JVM runs in, or in the worst case return the default one
     * that's not capable of killing descendants at all.
     */
    public static ProcessTree get() {
        if (!enabled)
            return DEFAULT;

        // Check for the existence of vetoers if I don't know already
        if (vetoersExist == null) {
            try {
                VirtualChannel channelToController = AgentComputerUtil.getChannelToController();
                if (channelToController != null) {
                    vetoersExist = channelToController.call(new DoVetoersExist());
                }
            }
            catch (InterruptedException ie) {
                // If we receive an InterruptedException here, we probably can't do much anyway.
                // Perhaps we should just return at this point since we probably can't do anything else.
                // It might make sense to introduce retries, but it's probably not going to get better.
                LOGGER.log(Level.FINE, "Caught InterruptedException while checking if vetoers exist: ", ie);
                Thread.interrupted(); // Clear the interrupt flag and just accept that no known vetoers exist.
            }
            catch (Exception e) {
                LOGGER.log(Level.WARNING, "Error while determining if vetoers exist", e);
            }
        }

        // Null-check in case the previous call worked
        boolean vetoes = vetoersExist == null ? true : vetoersExist;

        try {
            if (File.pathSeparatorChar == ';')
                return new Windows(vetoes);

            String os = Util.fixNull(System.getProperty("os.name"));
            if (os.equals("Linux"))
                return new Linux(vetoes);
            if (os.equals("AIX"))
                return new AIX(vetoes);
            if (os.equals("SunOS"))
                return new Solaris(vetoes);
            if (os.equals("Mac OS X"))
                return new Darwin(vetoes);
            if (os.equals("FreeBSD"))
                return new FreeBSD(vetoes);
        } catch (LinkageError e) {
            LOGGER.log(Level.WARNING, "Failed to load winp. Reverting to the default", e);
            enabled = false;
        }

        return DEFAULT;
    }

    private static class DoVetoersExist extends SlaveToMasterCallable<Boolean, IOException> {
        @Override
        public Boolean call() throws IOException {
            return ProcessKillingVeto.all().size() > 0;
        }
    }

//
//
// implementation follows
//-------------------------------------------
//

    /**
     * Empty process list as a default value if the platform doesn't support it.
     */
    /*package*/ static final ProcessTree DEFAULT = new Local() {
        @Override
        public OSProcess get(@NonNull final Process proc) {
            return new OSProcess(-1) {
                @Override
                @CheckForNull
                public OSProcess getParent() {
                    return null;
                }

                @Override
                public void killRecursively() {
                    // fall back to a single process killer
                    proc.destroy();
                }

                @Override
                public void kill() throws InterruptedException {
                    if (getVeto() != null)
                        return;
                    proc.destroy();
                    killByKiller();
                }

                @Override
                @NonNull
                public List<String> getArguments() {
                    return Collections.emptyList();
                }

                @Override
                @NonNull
                public EnvVars getEnvironmentVariables() {
                    return new EnvVars();
                }
            };
        }

        @Override
        public void killAll(@NonNull Map<String, String> modelEnvVars) {
            // no-op
        }
    };

    private class WindowsOSProcess extends OSProcess {

        private final WinProcess p;
        private EnvVars env;
        private List<String> args;

        WindowsOSProcess(WinProcess p) {
            super(p.getPid());
            this.p = p;
        }

        @CheckForNull
        @Override
        public OSProcess getParent() {
            // Windows process doesn't have parent/child relationship
            return null;
        }

        @Override
        public void killRecursively() throws InterruptedException {
            if (getVeto() != null)
                return;

            LOGGER.log(FINER, "Killing recursively {0}", getPid());
            // Firstly try to kill the root process gracefully, then do a forcekill if it does not help (algorithm is described in JENKINS-17116)
            killSoftly();
            p.killRecursively();
            killByKiller();
        }

        @Override
        public void kill() throws InterruptedException {
            if (getVeto() != null) {
                return;
            }

            LOGGER.log(FINER, "Killing {0}", getPid());
            // Firstly try to kill it gracefully, then do a forcekill if it does not help (algorithm is described in JENKINS-17116)
            killSoftly();
            p.kill();
            killByKiller();
        }

        private void killSoftly() throws InterruptedException {
            // send Ctrl+C to the process
            try {
                if (!p.sendCtrlC()) {
                    return;
                }
            }
            catch (WinpException e) {
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.log(Level.FINE, "Failed to send CTRL+C to pid=" + getPid(), e);
                }
                return;
            }

            // after that wait for it to cease to exist
            long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(softKillWaitSeconds);
            int sleepTime = 10; // initially we sleep briefly, then sleep up to 1sec
            do {
                if (!p.isRunning()) {
                    break;
                }

                Thread.sleep(sleepTime);
                sleepTime = Math.min(sleepTime * 2, 1000);
            } while (System.nanoTime() < deadline);
        }

        @NonNull
        @Override
        public synchronized List<String> getArguments() {
            if (args == null) {
                args = Arrays.asList(QuotedStringTokenizer.tokenize(p.getCommandLine()));
            }
            return args;
        }

        @NonNull
        @Override
        public synchronized EnvVars getEnvironmentVariables() {
            try {
               return getEnvironmentVariables2();
            } catch (WindowsOSProcessException e) {
                if (LOGGER.isLoggable(FINEST)) {
                    LOGGER.log(FINEST, "Failed to get the environment variables of process with pid=" + p.getPid(), e);
                }
            }
            return env;
        }

        private synchronized EnvVars getEnvironmentVariables2() throws WindowsOSProcessException {
            if (env != null) {
              return env;
            }
            env = new EnvVars();

            try {
               env.putAll(p.getEnvironmentVariables());
            } catch (WinpException e) {
               throw new WindowsOSProcessException("Failed to get the environment variables", e);
            }
            return env;
        }

        private boolean hasMatchingEnvVars2(Map<String, String> modelEnvVar) throws WindowsOSProcessException {
            if (modelEnvVar.isEmpty())
                // sanity check so that we don't start rampage.
                return false;

            SortedMap<String, String> envs = getEnvironmentVariables2();
            for (Map.Entry<String, String> e : modelEnvVar.entrySet()) {
                String v = envs.get(e.getKey());
                if (v == null || !v.equals(e.getValue()))
                    return false;   // no match
            }

            return true;
        }
    }

    //TODO: Cleanup once Winp provides proper API
    /**
     * Wrapper for runtime {@link WinpException}.
     */
    private static class WindowsOSProcessException extends Exception {
        WindowsOSProcessException(WinpException ex) {
            super(ex);
        }

        WindowsOSProcessException(String message, WinpException ex) {
            super(message, ex);
        }
    }

    private static final class Windows extends Local {
        Windows(boolean vetoesExist) {
            super(vetoesExist);

            for (final WinProcess p : WinProcess.all()) {
                int pid = p.getPid();
                if (pid == 0 || pid == 4) continue; // skip the System Idle and System processes
                super.processes.put(pid, new WindowsOSProcess(p));
            }
        }

        @CheckForNull
        @Override
        public OSProcess get(@NonNull Process proc) {
            return get(new WinProcess(proc).getPid());
        }

        @Override
        public void killAll(@NonNull Map<String, String> modelEnvVars) throws InterruptedException {
            for (OSProcess p : this) {
                if (p.getPid() < 10)
                    continue;   // ignore system processes like "idle process"

                LOGGER.log(FINEST, "Considering to kill {0}", p.getPid());

                boolean matched;
                try {
                    matched = hasMatchingEnvVars(p, modelEnvVars);
                } catch (WindowsOSProcessException e) {
                    // likely a missing privilege
                    // TODO: not a minor issue - causes process termination error in JENKINS-30782
                    if (LOGGER.isLoggable(FINEST)) {
                        LOGGER.log(FINEST, "Failed to check environment variable match for process with pid=" + p.getPid(), e);
                    }
                    continue;
                }

                if (matched) {
                    p.killRecursively();
                } else {
                    LOGGER.log(Level.FINEST, "Environment variable didn't match for process with pid={0}", p.getPid());
                }
            }
        }

        static {
            WinProcess.enableDebugPrivilege();
        }

        private static boolean hasMatchingEnvVars(@NonNull OSProcess p, @NonNull Map<String, String> modelEnvVars)
                throws WindowsOSProcessException {
            if (p instanceof WindowsOSProcess) {
                return ((WindowsOSProcess) p).hasMatchingEnvVars2(modelEnvVars);
            } else {
                // Should never happen, but there is a risk of getting such class during deserialization
                try {
                    return p.hasMatchingEnvVars(modelEnvVars);
                } catch (WinpException e) {
                    // likely a missing privilege
                    throw new WindowsOSProcessException(e);
                }
            }
        }
    }

    abstract static class Unix extends Local {
        Unix(boolean vetoersExist) {
            super(vetoersExist);
        }

        @CheckForNull
        @Override
        public OSProcess get(@NonNull Process proc) {
            return get(UnixReflection.pid(proc));
        }

        @Override
        public void killAll(@NonNull Map<String, String> modelEnvVars) throws InterruptedException {
            for (OSProcess p : this)
                if (p.hasMatchingEnvVars(modelEnvVars))
                    p.killRecursively();
        }
    }
    /**
     * {@link ProcessTree} based on /proc.
     */

    abstract static class ProcfsUnix extends Unix {
        ProcfsUnix(boolean vetoersExist) {
            super(vetoersExist);

            File[] processes = new File("/proc").listFiles(File::isDirectory);
            if (processes == null) {
                LOGGER.info("No /proc");
                return;
            }

            for (File p : processes) {
                int pid;
                try {
                    pid = Integer.parseInt(p.getName());
                } catch (NumberFormatException e) {
                    // other sub-directories
                    continue;
                }
                try {
                    this.processes.put(pid, createProcess(pid));
                } catch (IOException e) {
                    // perhaps the process status has changed since we obtained a directory listing
                }
            }
        }

        protected abstract OSProcess createProcess(int pid) throws IOException;
    }

    /**
     * A process.
     */
    public abstract class UnixProcess extends OSProcess {
        protected UnixProcess(int pid) {
            super(pid);
        }

        protected final File getFile(String relativePath) {
            return new File(new File("/proc/" + getPid()), relativePath);
        }

        /**
         * Tries to kill this process.
         */
        @Override
        public void kill() throws InterruptedException {
            // after sending SIGTERM, wait for the process to cease to exist
            long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(softKillWaitSeconds);
            kill(deadline);
        }

        private void kill(long deadline) throws InterruptedException {
            if (getVeto() != null)
                return;
            try {
                int pid = getPid();
                LOGGER.fine("Killing pid=" + pid);
                UnixReflection.destroy(pid);
                // after sending SIGTERM, wait for the process to cease to exist
                int sleepTime = 10; // initially we sleep briefly, then sleep up to 1sec
                File status = getFile("status");
                do {
                    if (!status.exists()) {
                        break; // status is gone, process therefore as well
                    }

                    Thread.sleep(sleepTime);
                    sleepTime = Math.min(sleepTime * 2, 1000);
                } while (System.nanoTime() < deadline);
            } catch (IllegalAccessException e) {
                // this is impossible
                IllegalAccessError x = new IllegalAccessError();
                x.initCause(e);
                throw x;
            } catch (InvocationTargetException e) {
                // tunnel serious errors
                if (e.getTargetException() instanceof Error)
                    throw (Error) e.getTargetException();
                // otherwise log and let go. I need to see when this happens
                LOGGER.log(Level.INFO, "Failed to terminate pid=" + getPid(), e);
            }
            killByKiller();
        }

        @Override
        public void killRecursively() throws InterruptedException {
            // after sending SIGTERM, wait for the processes to cease to exist until the deadline
            long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(softKillWaitSeconds);
            killRecursively(deadline);
        }

        private void killRecursively(long deadline) throws InterruptedException {
            // We kill individual processes of a tree, so handling vetoes inside #kill() is enough for UnixProcess es
            LOGGER.fine("Recursively killing pid=" + getPid());
            for (OSProcess p : getChildren()) {
                if (p instanceof UnixProcess) {
                    ((UnixProcess) p).killRecursively(deadline);
                } else {
                    p.killRecursively(); // should not happen, fallback to non-deadline version
                }
            }
            kill(deadline);
        }

        /**
         * Obtains the argument list of this process.
         *
         * @return
         *      empty list if failed (for example because the process is already dead,
         *      or the permission was denied.)
         */
        @Override
        @NonNull
        public abstract List<String> getArguments();
    }

    //TODO: can be replaced by multi-release JAR
    /**
     * Reflection used in the Unix support.
     */
    private static final class UnixReflection {
        /**
         * Field to access the PID of the process.
         * Required for Java 8 and older JVMs.
         */
        private static final Field JAVA8_PID_FIELD;

        /**
         * Field to access the PID of the process.
         * Required for Java 9 and above until this is replaced by multi-release JAR.
         */
        private static final Method JAVA9_PID_METHOD;

        /**
         * Method to destroy a process, given pid.
         *
         * Looking at the JavaSE source code, this is using SIGTERM (15)
         */
        private static final Method JAVA8_DESTROY_PROCESS;
        private static final Method JAVA_9_PROCESSHANDLE_OF;
        private static final Method JAVA_9_PROCESSHANDLE_DESTROY;

        static {
            try {
                if (JavaUtils.isRunningWithPostJava8()) {
                    Class<?> clazz = Process.class;
                    JAVA9_PID_METHOD = clazz.getMethod("pid");
                    JAVA8_PID_FIELD = null;
                    Class<?> processHandleClazz = Class.forName("java.lang.ProcessHandle");
                    JAVA_9_PROCESSHANDLE_OF = processHandleClazz.getMethod("of", long.class);
                    JAVA_9_PROCESSHANDLE_DESTROY = processHandleClazz.getMethod("destroy");
                    JAVA8_DESTROY_PROCESS = null;
                } else {
                    Class<?> clazz = Class.forName("java.lang.UNIXProcess");
                    JAVA8_PID_FIELD = clazz.getDeclaredField("pid");
                    JAVA8_PID_FIELD.setAccessible(true);
                    JAVA9_PID_METHOD = null;

                    JAVA8_DESTROY_PROCESS = clazz.getDeclaredMethod("destroyProcess", int.class, boolean.class);
                    JAVA8_DESTROY_PROCESS.setAccessible(true);
                    JAVA_9_PROCESSHANDLE_OF = null;
                    JAVA_9_PROCESSHANDLE_DESTROY = null;
                }
            } catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) {
                throw new LinkageError("Cannot initialize reflection for Unix Processes", e);
            }
        }

        public static void destroy(int pid) throws IllegalAccessException,
                InvocationTargetException {
            if (JAVA8_DESTROY_PROCESS != null) {
                JAVA8_DESTROY_PROCESS.invoke(null, pid, false);
            } else {
                final Optional handle = (Optional) JAVA_9_PROCESSHANDLE_OF.invoke(null, pid);
                if (handle.isPresent()) {
                    JAVA_9_PROCESSHANDLE_DESTROY.invoke(handle.get());
                }
            }
        }

        //TODO: We ideally need to update ProcessTree APIs to Support Long (JENKINS-53799).
        public static int pid(@NonNull Process proc) {
            try {
                if (JAVA8_PID_FIELD != null) {
                    return JAVA8_PID_FIELD.getInt(proc);
                } else {
                    long pid = (long) JAVA9_PID_METHOD.invoke(proc);
                    if (pid > Integer.MAX_VALUE) {
                        throw new IllegalAccessError("Java 9+ support error (JENKINS-53799). PID is out of Jenkins API bounds: " + pid);
                    }
                    return (int) pid;
                }
            } catch (IllegalAccessException | InvocationTargetException e) { // impossible
                IllegalAccessError x = new IllegalAccessError();
                x.initCause(e);
                throw x;
            }
        }
    }


    static class Linux extends ProcfsUnix {
        Linux(boolean vetoersExist) {
            super(vetoersExist);
        }

        @Override
        protected LinuxProcess createProcess(int pid) throws IOException {
            return new LinuxProcess(pid);
        }

        class LinuxProcess extends UnixProcess {
            private int ppid = -1;
            private EnvVars envVars;<commit_msg>Eliminate reflection from `ProcessTree` (#6762)<commit_after>/*
 * The MIT License
 *
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., <NAME>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package hudson.util;

import static com.sun.jna.Pointer.NULL;
import static hudson.util.jna.GNUCLibrary.LIBC;
import static java.util.logging.Level.FINER;
import static java.util.logging.Level.FINEST;

import com.google.common.primitives.Ints;
import com.sun.jna.LastErrorException;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.NativeLongByReference;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.EnvVars;
import hudson.FilePath;
import hudson.Util;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.util.ProcessKillingVeto.VetoCause;
import hudson.util.ProcessTree.OSProcess;
import hudson.util.ProcessTreeRemoting.IOSProcess;
import hudson.util.ProcessTreeRemoting.IProcessTree;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamException;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.agents.AgentComputerUtil;
import jenkins.security.SlaveToMasterCallable;
import jenkins.util.SystemProperties;
import org.apache.commons.io.FileUtils;
import org.jenkinsci.remoting.SerializableOnlyOverRemoting;
import org.jvnet.winp.WinProcess;
import org.jvnet.winp.WinpException;

/**
 * Represents a snapshot of the process tree of the current system.
 *
 * <p>
 * A {@link ProcessTree} is really conceptually a map from process ID to a {@link OSProcess} object.
 * When Hudson runs on platforms that support process introspection, this allows you to introspect
 * and do some useful things on processes. On other platforms, the implementation falls back to
 * "do nothing" behavior.
 *
 * <p>
 * {@link ProcessTree} is remotable.
 *
 * @author <NAME>
 * @since 1.315
 */
public abstract class ProcessTree implements Iterable<OSProcess>, IProcessTree, SerializableOnlyOverRemoting {
    /**
     * To be filled in the constructor of the derived type.
     */
    protected final Map<Integer/*pid*/, OSProcess> processes = new HashMap<>();

    /**
     * Lazily obtained {@link ProcessKiller}s to be applied on this process tree.
     */
    private transient volatile List<ProcessKiller> killers;

    /**
     * Flag to skip the veto check since there aren't any.
     */
    private boolean skipVetoes;

    // instantiation only allowed for subtypes in this class
    private ProcessTree() {
       skipVetoes = false;
    }

    private ProcessTree(boolean vetoesExist) {
        skipVetoes = !vetoesExist;
    }

    /**
     * Gets the process given a specific ID, or null if no such process exists.
     */
    @CheckForNull
    public final OSProcess get(int pid) {
        return processes.get(pid);
    }

    /**
     * Lists all the processes in the system.
     */
    @Override
    @NonNull
    public final Iterator<OSProcess> iterator() {
        return processes.values().iterator();
    }

    /**
     * Try to convert {@link Process} into this process object
     * or null if it fails (for example, maybe the snapshot is taken after
     * this process has already finished.)
     */
    @CheckForNull
    public abstract OSProcess get(@NonNull Process proc);

    /**
     * Kills all the processes that have matching environment variables.
     *
     * <p>
     * In this method, the method is given a
     * "model environment variables", which is a list of environment variables
     * and their values that are characteristic to the launched process.
     * The implementation is expected to find processes
     * in the system that inherit these environment variables, and kill
     * them all. This is suitable for locating daemon processes
     * that cannot be tracked by the regular ancestor/descendant relationship.
     */
    @Override
    public abstract void killAll(@NonNull Map<String, String> modelEnvVars) throws InterruptedException;

    /**
     * The time to wait between sending Ctrl+C and killing the process. (JENKINS-17116)
     *
     * The default is 5 seconds. Careful! There are other timers in the system that may
     * interfere with this value here, e.g. in org.jenkinsci.plugins.workflow.cps.CpsThread.stop
     */
    private final long softKillWaitSeconds = Integer.getInteger("SoftKillWaitSeconds", 5);

    /**
     * Convenience method that does {@link #killAll(Map)} and {@link OSProcess#killRecursively()}.
     * This is necessary to reliably kill the process and its descendants, as some OS
     * may not implement {@link #killAll(Map)}.
     *
     * Either of the parameter can be null.
     */
    public void killAll(@CheckForNull Process proc, @CheckForNull Map<String, String> modelEnvVars) throws InterruptedException {
        LOGGER.fine("killAll: process=" + proc + " and envs=" + modelEnvVars);

        if (proc != null) {
            OSProcess p = get(proc);
            if (p != null) p.killRecursively();
        }

        if (modelEnvVars != null)
            killAll(modelEnvVars);
    }

    /**
     * Obtains the list of killers.
     */
    @NonNull
    /*package*/ final List<ProcessKiller> getKillers() throws InterruptedException {
        if (killers == null)
            try {
                VirtualChannel channelToController = AgentComputerUtil.getChannelToController();
                if (channelToController != null) {
                    killers = channelToController.call(new ListAll());
                } else {
                    // used in an environment that doesn't support talk-back to the master.
                    // let's do with what we have.
                    killers = Collections.emptyList();
                }
            } catch (IOException | Error e) {
                LOGGER.log(Level.WARNING, "Failed to obtain killers", e);
                killers = Collections.emptyList();
            }
        return killers;
    }

    private static class ListAll extends SlaveToMasterCallable<List<ProcessKiller>, IOException> {
        @Override
        public List<ProcessKiller> call() throws IOException {
            return new ArrayList<>(ProcessKiller.all());
        }
    }

    /**
     * Represents a process.
     */
    public abstract class OSProcess implements IOSProcess, Serializable {
        final int pid;

        // instantiation only allowed for subtypes in this class
        private OSProcess(int pid) {
            this.pid = pid;
        }

        @Override
        public final int getPid() {
            return pid;
        }
        /**
         * Gets the parent process. This method may return null, because
         * there's no guarantee that we are getting a consistent snapshot
         * of the whole system state.
         */

        @Override
        @CheckForNull
        public abstract OSProcess getParent();

        /*package*/ final ProcessTree getTree() {
            return ProcessTree.this;
        }

        /**
         * Immediate child processes.
         */
        @NonNull
        public final List<OSProcess> getChildren() {
            List<OSProcess> r = new ArrayList<>();
            for (OSProcess p : ProcessTree.this)
                if (p.getParent() == this)
                    r.add(p);
            return r;
        }

        /**
         * Kills this process.
         */
        @Override
        public abstract void kill() throws InterruptedException;

        void killByKiller() throws InterruptedException {
            for (ProcessKiller killer : getKillers())
                try {
                    if (killer.kill(this)) {
                        break;
                    }
                } catch (IOException | Error e) {
                    LOGGER.log(Level.WARNING, "Failed to kill pid=" + getPid(), e);
                }
        }

        /**
         * Kills this process and all the descendants.
         * <p>
         * Note that the notion of "descendants" is somewhat vague,
         * in the presence of such things like daemons. On platforms
         * where the recursive operation is not supported, this just kills
         * the current process.
         */
        @Override
        public abstract void killRecursively() throws InterruptedException;

        /**
         * @return The first non-null {@link VetoCause} provided by a process killing veto extension for this OSProcess.
         * null if no one objects killing the process.
         */
        protected @CheckForNull VetoCause getVeto() {
            String causeMessage = null;

            // Quick check, does anything exist to check against
            if (!skipVetoes) {
                try {
                    VirtualChannel channelToController = AgentComputerUtil.getChannelToController();
                    if (channelToController != null) {
                        CheckVetoes vetoCheck = new CheckVetoes(this);
                        causeMessage = channelToController.call(vetoCheck);
                    }
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "I/O Exception while checking for vetoes", e);
                } catch (InterruptedException e) {
                    LOGGER.log(Level.WARNING, "Interrupted Exception while checking for vetoes", e);
                }
            }

            if (causeMessage != null) {
                return new VetoCause(causeMessage);
            }
            return null;
        }

        /**
         * Gets the command-line arguments of this process.
         *
         * <p>
         * On Windows, where the OS models command-line arguments as a single string, this method
         * computes the approximated tokenization.
         */
        @Override
        @NonNull
        public abstract List<String> getArguments();

        /**
         * Obtains the environment variables of this process.
         *
         * @return
         *      empty map if failed (for example because the process is already dead,
         *      or the permission was denied.)
         */
        @Override
        @NonNull
        public abstract EnvVars getEnvironmentVariables();

        /**
         * Given the environment variable of a process and the "model environment variable" that Hudson
         * used for launching the build, returns true if there's a match (which means the process should
         * be considered a descendant of a build.)
         */
        public final boolean hasMatchingEnvVars(Map<String, String> modelEnvVar) {
            if (modelEnvVar.isEmpty())
                // sanity check so that we don't start rampage.
                return false;

            SortedMap<String, String> envs = getEnvironmentVariables();
            for (Map.Entry<String, String> e : modelEnvVar.entrySet()) {
                String v = envs.get(e.getKey());
                if (v == null || !v.equals(e.getValue()))
                    return false;   // no match
            }

            return true;
        }

        /**
         * Executes a chunk of code at the same machine where this process resides.
         */
        @Override
        public <T> T act(ProcessCallable<T> callable) throws IOException, InterruptedException {
            return callable.invoke(this, FilePath.localChannel);
        }

        Object writeReplace() {
            return new SerializedProcess(pid);
        }

        private class CheckVetoes extends SlaveToMasterCallable<String, IOException> {
            private IOSProcess process;

            CheckVetoes(IOSProcess processToCheck) {
                process = processToCheck;
            }

            @Override
            public String call() throws IOException {
                for (ProcessKillingVeto vetoExtension : ProcessKillingVeto.all()) {
                    VetoCause cause = vetoExtension.vetoProcessKilling(process);
                    if (cause != null) {
                        if (LOGGER.isLoggable(FINEST))
                            LOGGER.info("Killing of pid " + getPid() + " vetoed by " + vetoExtension.getClass().getName() + ": " + cause.getMessage());
                        return cause.getMessage();
                    }
                }
                return null;
            }
        }
    }

    /**
     * Serialized form of {@link OSProcess} is the PID and {@link ProcessTree}
     */
    @SuppressFBWarnings(value = "SE_INNER_CLASS", justification = "Serializing the outer instance is intended")
    private final class SerializedProcess implements Serializable {
        private final int pid;
        private static final long serialVersionUID = 1L;

        private SerializedProcess(int pid) {
            this.pid = pid;
        }

        Object readResolve() {
            return get(pid);
        }
    }

    /**
     * Code that gets executed on the machine where the {@link OSProcess} is local.
     * Used to act on {@link OSProcess}.
     *
     * @see ProcessTree.OSProcess#act(ProcessTree.ProcessCallable)
     */
    public interface ProcessCallable<T> extends Serializable {
        /**
         * Performs the computational task on the node where the data is located.
         *
         * @param process
         *      {@link OSProcess} that represents the local process.
         * @param channel
         *      The "back pointer" of the {@link Channel} that represents the communication
         *      with the node from where the code was sent.
         */
        T invoke(OSProcess process, VirtualChannel channel) throws IOException;
    }


    /* package */ static volatile Boolean vetoersExist;

    /**
     * Gets the {@link ProcessTree} of the current system
     * that JVM runs in, or in the worst case return the default one
     * that's not capable of killing descendants at all.
     */
    public static ProcessTree get() {
        if (!enabled)
            return DEFAULT;

        // Check for the existence of vetoers if I don't know already
        if (vetoersExist == null) {
            try {
                VirtualChannel channelToController = AgentComputerUtil.getChannelToController();
                if (channelToController != null) {
                    vetoersExist = channelToController.call(new DoVetoersExist());
                }
            }
            catch (InterruptedException ie) {
                // If we receive an InterruptedException here, we probably can't do much anyway.
                // Perhaps we should just return at this point since we probably can't do anything else.
                // It might make sense to introduce retries, but it's probably not going to get better.
                LOGGER.log(Level.FINE, "Caught InterruptedException while checking if vetoers exist: ", ie);
                Thread.interrupted(); // Clear the interrupt flag and just accept that no known vetoers exist.
            }
            catch (Exception e) {
                LOGGER.log(Level.WARNING, "Error while determining if vetoers exist", e);
            }
        }

        // Null-check in case the previous call worked
        boolean vetoes = vetoersExist == null ? true : vetoersExist;

        try {
            if (File.pathSeparatorChar == ';')
                return new Windows(vetoes);

            String os = Util.fixNull(System.getProperty("os.name"));
            if (os.equals("Linux"))
                return new Linux(vetoes);
            if (os.equals("AIX"))
                return new AIX(vetoes);
            if (os.equals("SunOS"))
                return new Solaris(vetoes);
            if (os.equals("Mac OS X"))
                return new Darwin(vetoes);
            if (os.equals("FreeBSD"))
                return new FreeBSD(vetoes);
        } catch (LinkageError e) {
            LOGGER.log(Level.WARNING, "Failed to load winp. Reverting to the default", e);
            enabled = false;
        }

        return DEFAULT;
    }

    private static class DoVetoersExist extends SlaveToMasterCallable<Boolean, IOException> {
        @Override
        public Boolean call() throws IOException {
            return ProcessKillingVeto.all().size() > 0;
        }
    }

//
//
// implementation follows
//-------------------------------------------
//

    /**
     * Empty process list as a default value if the platform doesn't support it.
     */
    /*package*/ static final ProcessTree DEFAULT = new Local() {
        @Override
        public OSProcess get(@NonNull final Process proc) {
            return new OSProcess(-1) {
                @Override
                @CheckForNull
                public OSProcess getParent() {
                    return null;
                }

                @Override
                public void killRecursively() {
                    // fall back to a single process killer
                    proc.destroy();
                }

                @Override
                public void kill() throws InterruptedException {
                    if (getVeto() != null)
                        return;
                    proc.destroy();
                    killByKiller();
                }

                @Override
                @NonNull
                public List<String> getArguments() {
                    return Collections.emptyList();
                }

                @Override
                @NonNull
                public EnvVars getEnvironmentVariables() {
                    return new EnvVars();
                }
            };
        }

        @Override
        public void killAll(@NonNull Map<String, String> modelEnvVars) {
            // no-op
        }
    };

    private class WindowsOSProcess extends OSProcess {

        private final WinProcess p;
        private EnvVars env;
        private List<String> args;

        WindowsOSProcess(WinProcess p) {
            super(p.getPid());
            this.p = p;
        }

        @CheckForNull
        @Override
        public OSProcess getParent() {
            // Windows process doesn't have parent/child relationship
            return null;
        }

        @Override
        public void killRecursively() throws InterruptedException {
            if (getVeto() != null)
                return;

            LOGGER.log(FINER, "Killing recursively {0}", getPid());
            // Firstly try to kill the root process gracefully, then do a forcekill if it does not help (algorithm is described in JENKINS-17116)
            killSoftly();
            p.killRecursively();
            killByKiller();
        }

        @Override
        public void kill() throws InterruptedException {
            if (getVeto() != null) {
                return;
            }

            LOGGER.log(FINER, "Killing {0}", getPid());
            // Firstly try to kill it gracefully, then do a forcekill if it does not help (algorithm is described in JENKINS-17116)
            killSoftly();
            p.kill();
            killByKiller();
        }

        private void killSoftly() throws InterruptedException {
            // send Ctrl+C to the process
            try {
                if (!p.sendCtrlC()) {
                    return;
                }
            }
            catch (WinpException e) {
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.log(Level.FINE, "Failed to send CTRL+C to pid=" + getPid(), e);
                }
                return;
            }

            // after that wait for it to cease to exist
            long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(softKillWaitSeconds);
            int sleepTime = 10; // initially we sleep briefly, then sleep up to 1sec
            do {
                if (!p.isRunning()) {
                    break;
                }

                Thread.sleep(sleepTime);
                sleepTime = Math.min(sleepTime * 2, 1000);
            } while (System.nanoTime() < deadline);
        }

        @NonNull
        @Override
        public synchronized List<String> getArguments() {
            if (args == null) {
                args = Arrays.asList(QuotedStringTokenizer.tokenize(p.getCommandLine()));
            }
            return args;
        }

        @NonNull
        @Override
        public synchronized EnvVars getEnvironmentVariables() {
            try {
               return getEnvironmentVariables2();
            } catch (WindowsOSProcessException e) {
                if (LOGGER.isLoggable(FINEST)) {
                    LOGGER.log(FINEST, "Failed to get the environment variables of process with pid=" + p.getPid(), e);
                }
            }
            return env;
        }

        private synchronized EnvVars getEnvironmentVariables2() throws WindowsOSProcessException {
            if (env != null) {
              return env;
            }
            env = new EnvVars();

            try {
               env.putAll(p.getEnvironmentVariables());
            } catch (WinpException e) {
               throw new WindowsOSProcessException("Failed to get the environment variables", e);
            }
            return env;
        }

        private boolean hasMatchingEnvVars2(Map<String, String> modelEnvVar) throws WindowsOSProcessException {
            if (modelEnvVar.isEmpty())
                // sanity check so that we don't start rampage.
                return false;

            SortedMap<String, String> envs = getEnvironmentVariables2();
            for (Map.Entry<String, String> e : modelEnvVar.entrySet()) {
                String v = envs.get(e.getKey());
                if (v == null || !v.equals(e.getValue()))
                    return false;   // no match
            }

            return true;
        }
    }

    //TODO: Cleanup once Winp provides proper API
    /**
     * Wrapper for runtime {@link WinpException}.
     */
    private static class WindowsOSProcessException extends Exception {
        WindowsOSProcessException(WinpException ex) {
            super(ex);
        }

        WindowsOSProcessException(String message, WinpException ex) {
            super(message, ex);
        }
    }

    private static final class Windows extends Local {
        Windows(boolean vetoesExist) {
            super(vetoesExist);

            for (final WinProcess p : WinProcess.all()) {
                int pid = p.getPid();
                if (pid == 0 || pid == 4) continue; // skip the System Idle and System processes
                super.processes.put(pid, new WindowsOSProcess(p));
            }
        }

        @CheckForNull
        @Override
        public OSProcess get(@NonNull Process proc) {
            return get(new WinProcess(proc).getPid());
        }

        @Override
        public void killAll(@NonNull Map<String, String> modelEnvVars) throws InterruptedException {
            for (OSProcess p : this) {
                if (p.getPid() < 10)
                    continue;   // ignore system processes like "idle process"

                LOGGER.log(FINEST, "Considering to kill {0}", p.getPid());

                boolean matched;
                try {
                    matched = hasMatchingEnvVars(p, modelEnvVars);
                } catch (WindowsOSProcessException e) {
                    // likely a missing privilege
                    // TODO: not a minor issue - causes process termination error in JENKINS-30782
                    if (LOGGER.isLoggable(FINEST)) {
                        LOGGER.log(FINEST, "Failed to check environment variable match for process with pid=" + p.getPid(), e);
                    }
                    continue;
                }

                if (matched) {
                    p.killRecursively();
                } else {
                    LOGGER.log(Level.FINEST, "Environment variable didn't match for process with pid={0}", p.getPid());
                }
            }
        }

        static {
            WinProcess.enableDebugPrivilege();
        }

        private static boolean hasMatchingEnvVars(@NonNull OSProcess p, @NonNull Map<String, String> modelEnvVars)
                throws WindowsOSProcessException {
            if (p instanceof WindowsOSProcess) {
                return ((WindowsOSProcess) p).hasMatchingEnvVars2(modelEnvVars);
            } else {
                // Should never happen, but there is a risk of getting such class during deserialization
                try {
                    return p.hasMatchingEnvVars(modelEnvVars);
                } catch (WinpException e) {
                    // likely a missing privilege
                    throw new WindowsOSProcessException(e);
                }
            }
        }
    }

    abstract static class Unix extends Local {
        Unix(boolean vetoersExist) {
            super(vetoersExist);
        }

        @CheckForNull
        @Override
        public OSProcess get(@NonNull Process proc) {
            return get(Ints.checkedCast(proc.pid()));
        }

        @Override
        public void killAll(@NonNull Map<String, String> modelEnvVars) throws InterruptedException {
            for (OSProcess p : this)
                if (p.hasMatchingEnvVars(modelEnvVars))
                    p.killRecursively();
        }
    }
    /**
     * {@link ProcessTree} based on /proc.
     */

    abstract static class ProcfsUnix extends Unix {
        ProcfsUnix(boolean vetoersExist) {
            super(vetoersExist);

            File[] processes = new File("/proc").listFiles(File::isDirectory);
            if (processes == null) {
                LOGGER.info("No /proc");
                return;
            }

            for (File p : processes) {
                int pid;
                try {
                    pid = Integer.parseInt(p.getName());
                } catch (NumberFormatException e) {
                    // other sub-directories
                    continue;
                }
                try {
                    this.processes.put(pid, createProcess(pid));
                } catch (IOException e) {
                    // perhaps the process status has changed since we obtained a directory listing
                }
            }
        }

        protected abstract OSProcess createProcess(int pid) throws IOException;
    }

    /**
     * A process.
     */
    public abstract class UnixProcess extends OSProcess {
        protected UnixProcess(int pid) {
            super(pid);
        }

        protected final File getFile(String relativePath) {
            return new File(new File("/proc/" + getPid()), relativePath);
        }

        /**
         * Tries to kill this process.
         */
        @Override
        public void kill() throws InterruptedException {
            // after sending SIGTERM, wait for the process to cease to exist
            long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(softKillWaitSeconds);
            kill(deadline);
        }

        private void kill(long deadline) throws InterruptedException {
            if (getVeto() != null)
                return;
            int pid = getPid();
            LOGGER.fine("Killing pid=" + pid);
            ProcessHandle.of(pid).ifPresent(ProcessHandle::destroy);
            // after sending SIGTERM, wait for the process to cease to exist
            int sleepTime = 10; // initially we sleep briefly, then sleep up to 1sec
            File status = getFile("status");
            do {
                if (!status.exists()) {
                    break; // status is gone, process therefore as well
                }

                Thread.sleep(sleepTime);
                sleepTime = Math.min(sleepTime * 2, 1000);
            } while (System.nanoTime() < deadline);
            killByKiller();
        }

        @Override
        public void killRecursively() throws InterruptedException {
            // after sending SIGTERM, wait for the processes to cease to exist until the deadline
            long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(softKillWaitSeconds);
            killRecursively(deadline);
        }

        private void killRecursively(long deadline) throws InterruptedException {
            // We kill individual processes of a tree, so handling vetoes inside #kill() is enough for UnixProcess es
            LOGGER.fine("Recursively killing pid=" + getPid());
            for (OSProcess p : getChildren()) {
                if (p instanceof UnixProcess) {
                    ((UnixProcess) p).killRecursively(deadline);
                } else {
                    p.killRecursively(); // should not happen, fallback to non-deadline version
                }
            }
            kill(deadline);
        }

        /**
         * Obtains the argument list of this process.
         *
         * @return
         *      empty list if failed (for example because the process is already dead,
         *      or the permission was denied.)
         */
        @Override
        @NonNull
        public abstract List<String> getArguments();
    }

    static class Linux extends ProcfsUnix {
        Linux(boolean vetoersExist) {
            super(vetoersExist);
        }

        @Override
        protected LinuxProcess createProcess(int pid) throws IOException {
            return new LinuxProcess(pid);
        }

        class LinuxProcess extends UnixProcess {
            private int ppid = -1;
            private EnvVars envVars;
{'fraction_non_alphanumeric': 0.08386102004461012, 'fraction_numerical': 0.002664630769000464, 'mean_word_length': 1.776706293124948, 'pattern_counts': {'":': 2, '<': 96, '<?xml version=': 0, '>': 93, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5518633', 'n_tokens_mistral': 17252, 'n_tokens_neox': 16370, 'n_words': 5295}