Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Log contextual requests that affect sourcekitd’s global state #2094

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Sources/Diagnose/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ add_library(Diagnose STATIC
StderrStreamConcurrencySafe.swift
SwiftFrontendCrashScraper.swift
Toolchain+SwiftFrontend.swift
Toolchain+PluginPaths.swift
TraceFromSignpostsCommand.swift)

set_target_properties(Diagnose PROPERTIES
Expand Down
4 changes: 4 additions & 0 deletions Sources/Diagnose/DiagnoseCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
package import ArgumentParser
import Foundation
import LanguageServerProtocolExtensions
import SKLogging
import SwiftExtensions
import TSCExtensions
import ToolchainRegistry
Expand Down Expand Up @@ -136,6 +137,7 @@ package struct DiagnoseCommand: AsyncParsableCommand {
break
} catch {
// Reducing this request failed. Continue reducing the next one, maybe that one succeeds.
logger.info("Reducing sourcekitd crash failed: \(error.forLogging)")
}
}
}
Expand Down Expand Up @@ -173,6 +175,7 @@ package struct DiagnoseCommand: AsyncParsableCommand {

let executor = OutOfProcessSourceKitRequestExecutor(
sourcekitd: sourcekitd,
pluginPaths: toolchain.pluginPaths,
swiftFrontend: crashInfo.swiftFrontend,
reproducerPredicate: nil
)
Expand Down Expand Up @@ -457,6 +460,7 @@ package struct DiagnoseCommand: AsyncParsableCommand {
let requestInfo = requestInfo
let executor = OutOfProcessSourceKitRequestExecutor(
sourcekitd: sourcekitd,
pluginPaths: toolchain.pluginPaths,
swiftFrontend: swiftFrontend,
reproducerPredicate: nil
)
Expand Down
1 change: 1 addition & 0 deletions Sources/Diagnose/MergeSwiftFiles.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ extension RequestInfo {
let compilerArgs = compilerArgs.filter { $0 != "-primary-file" && !$0.hasSuffix(".swift") } + ["$FILE"]
let mergedRequestInfo = RequestInfo(
requestTemplate: requestTemplate,
contextualRequestTemplates: contextualRequestTemplates,
offset: offset,
compilerArgs: compilerArgs,
fileContents: mergedFile
Expand Down
70 changes: 64 additions & 6 deletions Sources/Diagnose/OSLogScraper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

#if canImport(OSLog)
import OSLog
import SKLogging
import RegexBuilder

/// Reads oslog messages to find recent sourcekitd crashes.
struct OSLogScraper {
Expand Down Expand Up @@ -45,34 +47,90 @@ struct OSLogScraper {
#"subsystem CONTAINS "sourcekit-lsp" AND composedMessage CONTAINS "sourcekitd crashed" AND category = %@"#,
logCategory
)
var isInFileContentSection = false
enum LogSection {
case request
case fileContents
case contextualRequest
}
var section = LogSection.request
var request = ""
var fileContents = ""
var contextualRequests: [String] = []
let sourcekitdCrashedRegex = Regex {
"sourcekitd crashed ("
OneOrMore(.digit)
"/"
OneOrMore(.digit)
")"
}
let contextualRequestRegex = Regex {
"Contextual request "
OneOrMore(.digit)
" / "
OneOrMore(.digit)
":"
}

for entry in try getLogEntries(matching: predicate) {
for line in entry.composedMessage.components(separatedBy: "\n") {
if line.starts(with: "sourcekitd crashed (") {
if try sourcekitdCrashedRegex.wholeMatch(in: line) != nil {
continue
}
if line == "Request:" {
continue
}
if line == "File contents:" {
isInFileContentSection = true
section = .fileContents
continue
}
if line == "File contents:" {
section = .fileContents
continue
}
if try contextualRequestRegex.wholeMatch(in: line) != nil {
section = .contextualRequest
contextualRequests.append("")
continue
}
if line == "--- End Chunk" {
continue
}
if isInFileContentSection {
fileContents += line + "\n"
} else {
switch section {
case .request:
request += line + "\n"
case .fileContents:
fileContents += line + "\n"
case .contextualRequest:
if !contextualRequests.isEmpty {
contextualRequests[contextualRequests.count - 1] += line + "\n"
} else {
// Should never happen because we have appended at least one element to `contextualRequests` when switching
// to the `contextualRequest` section.
logger.fault("Dropping contextual request line: \(line)")
}
}
}
}

var requestInfo = try RequestInfo(request: request)

let contextualRequestInfos = contextualRequests.compactMap { contextualRequest in
orLog("Processsing contextual request") {
try RequestInfo(request: contextualRequest)
}
}.filter { contextualRequest in
if contextualRequest.fileContents != requestInfo.fileContents {
logger.error("Contextual request concerns a different file than the crashed request. Ignoring it")
return false
}
return true
}
requestInfo.contextualRequestTemplates = contextualRequestInfos.map(\.requestTemplate)
if requestInfo.compilerArgs.isEmpty {
requestInfo.compilerArgs = contextualRequestInfos.last(where: { !$0.compilerArgs.isEmpty })?.compilerArgs ?? []
}
requestInfo.fileContents = fileContents

return requestInfo
}

Expand Down
12 changes: 9 additions & 3 deletions Sources/Diagnose/ReduceCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

package import ArgumentParser
import Foundation
import SourceKitD
import ToolchainRegistry

import struct TSCBasic.AbsolutePath
Expand Down Expand Up @@ -68,12 +69,16 @@ package struct ReduceCommand: AsyncParsableCommand {

@MainActor
package func run() async throws {
guard let sourcekitd = try await toolchain?.sourcekitd else {
guard let toolchain = try await toolchain else {
throw GenericError("Unable to find toolchain")
}
guard let sourcekitd = toolchain.sourcekitd else {
throw GenericError("Unable to find sourcekitd.framework")
}
guard let swiftFrontend = try await toolchain?.swiftFrontend else {
guard let swiftFrontend = toolchain.swiftFrontend else {
throw GenericError("Unable to find sourcekitd.framework")
}
let pluginPaths = toolchain.pluginPaths

let progressBar = PercentProgressAnimation(stream: stderrStreamConcurrencySafe, header: "Reducing sourcekitd issue")

Expand All @@ -82,6 +87,7 @@ package struct ReduceCommand: AsyncParsableCommand {

let executor = OutOfProcessSourceKitRequestExecutor(
sourcekitd: sourcekitd,
pluginPaths: pluginPaths,
swiftFrontend: swiftFrontend,
reproducerPredicate: nsPredicate
)
Expand All @@ -96,6 +102,6 @@ package struct ReduceCommand: AsyncParsableCommand {
try reduceRequestInfo.fileContents.write(to: reducedSourceFile, atomically: true, encoding: .utf8)

print("Reduced Request:")
print(try reduceRequestInfo.request(for: reducedSourceFile))
print(try reduceRequestInfo.requests(for: reducedSourceFile).joined(separator: "\n\n\n\n"))
}
}
1 change: 1 addition & 0 deletions Sources/Diagnose/ReduceFrontendCommand.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ package struct ReduceFrontendCommand: AsyncParsableCommand {

let executor = OutOfProcessSourceKitRequestExecutor(
sourcekitd: sourcekitd,
pluginPaths: nil,
swiftFrontend: swiftFrontend,
reproducerPredicate: nsPredicate
)
Expand Down
14 changes: 8 additions & 6 deletions Sources/Diagnose/ReproducerBundle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,14 @@ func makeReproducerBundle(for requestInfo: RequestInfo, toolchain: Toolchain, bu
+ requestInfo.compilerArgs.replacing(["$FILE"], with: ["./input.swift"]).joined(separator: " \\\n")
try command.write(to: bundlePath.appendingPathComponent("command.sh"), atomically: true, encoding: .utf8)
} else {
let request = try requestInfo.request(for: URL(fileURLWithPath: "/input.swift"))
try request.write(
to: bundlePath.appendingPathComponent("request.yml"),
atomically: true,
encoding: .utf8
)
let requests = try requestInfo.requests(for: bundlePath.appendingPathComponent("input.swift"))
for (index, request) in requests.enumerated() {
try request.write(
to: bundlePath.appendingPathComponent("request-\(index).yml"),
atomically: true,
encoding: .utf8
)
}
}
for compilerArg in requestInfo.compilerArgs {
// Find the first slash so we are also able to copy files from eg.
Expand Down
Loading