File: Process%2BRun.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (216 lines) | stat: -rw-r--r-- 8,086 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import Foundation
import LSPLogging
import SwiftExtensions

import struct TSCBasic.AbsolutePath
import class TSCBasic.Process
import enum TSCBasic.ProcessEnv
import struct TSCBasic.ProcessEnvironmentBlock
import struct TSCBasic.ProcessResult

#if os(Windows)
import WinSDK
#endif

extension Process {
  /// Wait for the process to exit. If the task gets cancelled, during this time, send a `SIGINT` to the process.
  /// Should the process not terminate on SIGINT after 2 seconds, it is killed using `SIGKILL`.
  @discardableResult
  public func waitUntilExitStoppingProcessOnTaskCancellation() async throws -> ProcessResult {
    let hasExited = AtomicBool(initialValue: false)
    return try await withTaskCancellationHandler {
      defer {
        hasExited.value = true
      }
      return try await waitUntilExit()
    } onCancel: {
      signal(SIGINT)
      Task {
        // Give the process 2 seconds to react to a SIGINT. If that doesn't work, kill the process.
        try await Task.sleep(for: .seconds(2))
        if !hasExited.value {
          #if os(Windows)
          // Windows does not define SIGKILL. Process.signal sends a `terminate` to the underlying Foundation process
          // for any signal that is not SIGINT. Use `SIGABRT` to terminate the process.
          signal(SIGABRT)
          #else
          signal(SIGKILL)
          #endif
        }
      }
    }
  }

  /// Launches a new process with the given parameters.
  ///
  /// - Important: If `workingDirectory` is not supported on this platform, this logs an error and falls back to launching the
  ///   process without the working directory set.
  private static func launch(
    arguments: [String],
    environmentBlock: ProcessEnvironmentBlock = ProcessEnv.block,
    workingDirectory: AbsolutePath?,
    outputRedirection: OutputRedirection = .collect(redirectStderr: false),
    startNewProcessGroup: Bool = true,
    loggingHandler: LoggingHandler? = .none
  ) throws -> Process {
    let process =
      if let workingDirectory {
        Process(
          arguments: arguments,
          environmentBlock: environmentBlock,
          workingDirectory: workingDirectory,
          outputRedirection: outputRedirection,
          startNewProcessGroup: startNewProcessGroup,
          loggingHandler: loggingHandler
        )
      } else {
        Process(
          arguments: arguments,
          environmentBlock: environmentBlock,
          outputRedirection: outputRedirection,
          startNewProcessGroup: startNewProcessGroup,
          loggingHandler: loggingHandler
        )
      }
    do {
      try process.launch()
    } catch Process.Error.workingDirectoryNotSupported where workingDirectory != nil {
      return try Process.launchWithWorkingDirectoryUsingSh(
        arguments: arguments,
        environmentBlock: environmentBlock,
        workingDirectory: workingDirectory!,
        outputRedirection: outputRedirection,
        startNewProcessGroup: startNewProcessGroup,
        loggingHandler: loggingHandler
      )
    }
    return process
  }

  private static func launchWithWorkingDirectoryUsingSh(
    arguments: [String],
    environmentBlock: ProcessEnvironmentBlock = ProcessEnv.block,
    workingDirectory: AbsolutePath,
    outputRedirection: OutputRedirection = .collect,
    startNewProcessGroup: Bool = true,
    loggingHandler: LoggingHandler? = .none
  ) throws -> Process {
    let shPath = "/usr/bin/sh"
    guard FileManager.default.fileExists(atPath: shPath) else {
      logger.error(
        """
        Working directory not supported on the platform and 'sh' could not be found. \
        Launching process without working directory \(workingDirectory.pathString)
        """
      )
      return try Process.launch(
        arguments: arguments,
        environmentBlock: environmentBlock,
        workingDirectory: nil,
        outputRedirection: outputRedirection,
        startNewProcessGroup: startNewProcessGroup,
        loggingHandler: loggingHandler
      )
    }
    return try Process.launch(
      arguments: [shPath, "-c", #"cd "$0"; exec "$@""#, workingDirectory.pathString] + arguments,
      environmentBlock: environmentBlock,
      workingDirectory: nil,
      outputRedirection: outputRedirection,
      startNewProcessGroup: startNewProcessGroup,
      loggingHandler: loggingHandler
    )
  }

  /// Runs a new process with the given parameters and waits for it to exit, sending SIGINT if this task is cancelled.
  ///
  /// The process's priority tracks the priority of the current task.
  @discardableResult
  public static func run(
    arguments: [String],
    environmentBlock: ProcessEnvironmentBlock = ProcessEnv.block,
    workingDirectory: AbsolutePath?,
    outputRedirection: OutputRedirection = .collect(redirectStderr: false),
    startNewProcessGroup: Bool = true,
    loggingHandler: LoggingHandler? = .none
  ) async throws -> ProcessResult {
    let process = try Self.launch(
      arguments: arguments,
      environmentBlock: environmentBlock,
      workingDirectory: workingDirectory,
      outputRedirection: outputRedirection,
      startNewProcessGroup: startNewProcessGroup,
      loggingHandler: loggingHandler
    )
    return try await withTaskPriorityChangedHandler(initialPriority: Task.currentPriority) { @Sendable in
      setProcessPriority(pid: process.processID, newPriority: Task.currentPriority)
      return try await process.waitUntilExitStoppingProcessOnTaskCancellation()
    } taskPriorityChanged: {
      setProcessPriority(pid: process.processID, newPriority: Task.currentPriority)
    }
  }
}

/// Set the priority of the given process to a value that's equivalent to `newPriority` on the current OS.
private func setProcessPriority(pid: Process.ProcessID, newPriority: TaskPriority) {
  #if os(Windows)
  guard let handle = OpenProcess(UInt32(PROCESS_SET_INFORMATION), /*bInheritHandle*/ false, UInt32(pid)) else {
    logger.fault("Failed to get process handle for \(pid) to change its priority: \(GetLastError())")
    return
  }
  defer {
    CloseHandle(handle)
  }
  if !SetPriorityClass(handle, UInt32(newPriority.windowsProcessPriority)) {
    logger.fault("Failed to set process priority of \(pid) to \(newPriority.rawValue): \(GetLastError())")
  }
  #elseif canImport(Darwin) || canImport(Android)
  // `setpriority` is only able to decrease a process's priority and cannot elevate it. Since Swift task’s priorities
  // can only be elevated, this means that we can effectively only change a process's priority once, when it is created.
  // All subsequent calls to `setpriority` will fail. Because of this, don't log an error.
  setpriority(PRIO_PROCESS, UInt32(pid), newPriority.posixProcessPriority)
  #else
  setpriority(__priority_which_t(PRIO_PROCESS.rawValue), UInt32(pid), newPriority.posixProcessPriority)
  #endif
}

fileprivate extension TaskPriority {
  #if os(Windows)
  var windowsProcessPriority: Int32 {
    if self >= .high {
      // SourceKit-LSP’s request handling runs at `TaskPriority.high`, which corresponds to the normal priority class.
      return NORMAL_PRIORITY_CLASS
    }
    if self >= .medium {
      return BELOW_NORMAL_PRIORITY_CLASS
    }
    return IDLE_PRIORITY_CLASS
  }
  #else
  var posixProcessPriority: Int32 {
    if self >= .high {
      // SourceKit-LSP’s request handling runs at `TaskPriority.high`, which corresponds to the base 0 niceness value.
      return 0
    }
    if self >= .medium {
      return 5
    }
    if self >= .low {
      return 10
    }
    return 15
  }
  #endif
}