Skip to content

Commit b315d43

Browse files
committed
Use response files to index files if argument list exceeds maximum number of arguments
1 parent eb4b083 commit b315d43

File tree

6 files changed

+168
-7
lines changed

6 files changed

+168
-7
lines changed

Sources/BuildSystemIntegration/BuildSettingsLogger.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ package actor BuildSettingsLogger {
4848
"""
4949

5050
let chunks = splitLongMultilineMessage(message: log)
51-
for (index, chunk) in chunks.enumerated() {
51+
// Only print the first 100 chunks. If the argument list gets any longer, we don't want to spam the log too much.
52+
// In practice, 100 chunks should be sufficient.
53+
for (index, chunk) in chunks.enumerated().prefix(100) {
5254
logger.log(
5355
level: level,
5456
"""

Sources/SKTestSupport/BuildServerTestProject.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ package class BuildServerTestProject: MultiFileTestProject {
6565
buildServerConfigLocation: RelativeFileLocation = ".bsp/sourcekit-lsp.json",
6666
buildServer: String,
6767
options: SourceKitLSPOptions? = nil,
68+
enableBackgroundIndexing: Bool = false,
6869
testName: String = #function
6970
) async throws {
7071
var files = files
@@ -92,6 +93,7 @@ package class BuildServerTestProject: MultiFileTestProject {
9293
try await super.init(
9394
files: files,
9495
options: options,
96+
enableBackgroundIndexing: enableBackgroundIndexing,
9597
testName: testName
9698
)
9799
}

Sources/SKTestSupport/INPUTS/AbstractBuildServer.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ def handle_message(self, message: Dict[str, object]) -> Optional[Dict[str, objec
7070
return self.initialized(params)
7171
elif method == "build/shutdown":
7272
return self.shutdown(params)
73+
elif method == "buildTarget/prepare":
74+
return self.buildtarget_prepare(params)
7375
elif method == "buildTarget/sources":
7476
return self.buildtarget_sources(params)
7577
elif method == "textDocument/registerForChanges":
@@ -80,6 +82,8 @@ def handle_message(self, message: Dict[str, object]) -> Optional[Dict[str, objec
8082
return self.workspace_did_change_watched_files(params)
8183
elif method == "workspace/buildTargets":
8284
return self.workspace_build_targets(params)
85+
elif method == "workspace/waitForBuildSystemUpdates":
86+
return self.workspace_waitForBuildSystemUpdates(params)
8387

8488
# ignore other notifications
8589
if "id" in message:
@@ -120,10 +124,8 @@ def initialize(self, request: Dict[str, object]) -> Dict[str, object]:
120124
"version": "0.1",
121125
"bspVersion": "2.0",
122126
"rootUri": "blah",
123-
"capabilities": {"languageIds": ["a", "b"]},
127+
"capabilities": {"languageIds": ["swift", "c", "cpp", "objective-c", "objective-c"]},
124128
"data": {
125-
"indexDatabasePath": "some/index/db/path",
126-
"indexStorePath": "some/index/store/path",
127129
"sourceKitOptionsProvider": True,
128130
},
129131
}
@@ -144,6 +146,11 @@ def textdocument_sourcekitoptions(
144146
def shutdown(self, request: Dict[str, object]) -> Dict[str, object]:
145147
return {}
146148

149+
def buildtarget_prepare(self, request: Dict[str, object]) -> Dict[str, object]:
150+
raise RequestError(
151+
code=-32601, message=f"'buildTarget/prepare' not implemented"
152+
)
153+
147154
def buildtarget_sources(self, request: Dict[str, object]) -> Dict[str, object]:
148155
raise RequestError(
149156
code=-32601, message=f"'buildTarget/sources' not implemented"
@@ -157,6 +164,9 @@ def workspace_build_targets(self, request: Dict[str, object]) -> Dict[str, objec
157164
code=-32601, message=f"'workspace/buildTargets' not implemented"
158165
)
159166

167+
def workspace_waitForBuildSystemUpdates(self, request: Dict[str, object]) -> Dict[str, object]:
168+
return {}
169+
160170

161171
class LegacyBuildServer(AbstractBuildServer):
162172
def send_sourcekit_options_changed(self, uri: str, options: List[str]):

Sources/SemanticIndex/UpdateIndexStoreTaskDescription.swift

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import TSCExtensions
2424
import struct TSCBasic.AbsolutePath
2525
import class TSCBasic.Process
2626
import struct TSCBasic.ProcessResult
27+
import enum TSCBasic.SystemError
2728
#else
2829
import BuildServerProtocol
2930
import BuildSystemIntegration
@@ -38,6 +39,7 @@ import TSCExtensions
3839
import struct TSCBasic.AbsolutePath
3940
import class TSCBasic.Process
4041
import struct TSCBasic.ProcessResult
42+
import enum TSCBasic.SystemError
4143
#endif
4244

4345
private let updateIndexStoreIDForLogging = AtomicUInt32(initialValue: 1)
@@ -415,7 +417,7 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription {
415417
let result: ProcessResult
416418
do {
417419
result = try await withTimeout(timeout) {
418-
try await Process.run(
420+
try await Process.runUsingResponseFileIfTooManyArguments(
419421
arguments: processArguments,
420422
workingDirectory: workingDirectory,
421423
outputRedirection: .stream(
@@ -464,3 +466,68 @@ package struct UpdateIndexStoreTaskDescription: IndexTaskDescription {
464466
}
465467
}
466468
}
469+
470+
fileprivate extension Process {
471+
/// Run a process with the given arguments. If the number of arguments exceeds the maximum number of arguments allows,
472+
/// create a response file and use it to pass the arguments.
473+
static func runUsingResponseFileIfTooManyArguments(
474+
arguments: [String],
475+
workingDirectory: AbsolutePath?,
476+
outputRedirection: OutputRedirection = .collect(redirectStderr: false)
477+
) async throws -> ProcessResult {
478+
do {
479+
return try await Process.run(
480+
arguments: arguments,
481+
workingDirectory: workingDirectory,
482+
outputRedirection: outputRedirection
483+
)
484+
} catch {
485+
let argumentListTooLong: Bool
486+
#if os(Windows)
487+
if let nserror = error as? NSError {
488+
argumentListTooLong = nserror.underlyingErrors.contains(where: { underlyingError in
489+
guard let underlyingError = underlyingError as? NSError else {
490+
return false
491+
}
492+
return underlyingError.domain == "org.swift.Foundation.WindowsError"
493+
&& underlyingError.code == 206 /* ERROR_FILENAME_EXCED_RANGE */
494+
})
495+
} else {
496+
argumentListTooLong = false
497+
}
498+
#else
499+
if case SystemError.posix_spawn(E2BIG, _) = error {
500+
argumentListTooLong = true
501+
} else {
502+
argumentListTooLong = false
503+
}
504+
#endif
505+
506+
guard argumentListTooLong else {
507+
throw error
508+
}
509+
510+
logger.debug("Argument list is too long. Using response file.")
511+
let responseFile = FileManager.default.temporaryDirectory.appendingPathComponent(
512+
"index-response-file-\(UUID()).txt"
513+
)
514+
defer {
515+
orLog("Failed to remove temporary response file") {
516+
try FileManager.default.removeItem(at: responseFile)
517+
}
518+
}
519+
FileManager.default.createFile(atPath: try responseFile.filePath, contents: nil)
520+
let handle = try FileHandle(forWritingTo: responseFile)
521+
for argument in arguments.dropFirst() {
522+
handle.write(Data((argument.spm_shellEscaped() + "\n").utf8))
523+
}
524+
try handle.close()
525+
526+
return try await Process.run(
527+
arguments: arguments.prefix(1) + ["@\(responseFile.filePath)"],
528+
workingDirectory: workingDirectory,
529+
outputRedirection: outputRedirection
530+
)
531+
}
532+
}
533+
}

Sources/SourceKitLSP/Swift/DocumentFormatting.swift

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import TSCExtensions
2323

2424
import struct TSCBasic.AbsolutePath
2525
import class TSCBasic.Process
26-
import func TSCBasic.withTemporaryFile
2726
#else
2827
import Foundation
2928
import LanguageServerProtocol
@@ -37,7 +36,6 @@ import TSCExtensions
3736

3837
import struct TSCBasic.AbsolutePath
3938
import class TSCBasic.Process
40-
import func TSCBasic.withTemporaryFile
4139
#endif
4240

4341
fileprivate extension String {

Tests/SourceKitLSPTests/BackgroundIndexingTests.swift

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2040,6 +2040,88 @@ final class BackgroundIndexingTests: XCTestCase {
20402040
return hoverAfterAddingDependencyDeclaration != nil
20412041
}
20422042
}
2043+
2044+
func testUseResponseFileIfTooManyArguments() async throws {
2045+
// The build system returns too many arguments to fit them into a command line invocation, so we need to use a
2046+
// response file to invoke the indexer.
2047+
2048+
let project = try await BuildServerTestProject(
2049+
files: [
2050+
// File name contains a space to ensure we escape it in the response file.
2051+
"Test File.swift": """
2052+
func 1️⃣myTestFunc() {}
2053+
"""
2054+
],
2055+
buildServer: """
2056+
class BuildServer(AbstractBuildServer):
2057+
2058+
def initialize(self, request: Dict[str, object]) -> Dict[str, object]:
2059+
return {
2060+
"displayName": "test server",
2061+
"version": "0.1",
2062+
"bspVersion": "2.0",
2063+
"rootUri": "blah",
2064+
"capabilities": {"languageIds": ["swift", "c", "cpp", "objective-c", "objective-c"]},
2065+
"data": {
2066+
"indexDatabasePath": r"$TEST_DIR/index-db",
2067+
"indexStorePath": r"$TEST_DIR/index",
2068+
"prepareProvider": True,
2069+
"sourceKitOptionsProvider": True,
2070+
},
2071+
}
2072+
2073+
def workspace_build_targets(self, request: Dict[str, object]) -> Dict[str, object]:
2074+
return {
2075+
"targets": [
2076+
{
2077+
"id": {"uri": "bsp://dummy"},
2078+
"tags": [],
2079+
"languageIds": [],
2080+
"dependencies": [],
2081+
"capabilities": {},
2082+
}
2083+
]
2084+
}
2085+
2086+
def buildtarget_sources(self, request: Dict[str, object]) -> Dict[str, object]:
2087+
return {
2088+
"items": [
2089+
{
2090+
"target": {"uri": "bsp://dummy"},
2091+
"sources": [
2092+
{"uri": "$TEST_DIR_URL/Test.swift", "kind": 1, "generated": False}
2093+
],
2094+
}
2095+
]
2096+
}
2097+
2098+
def textdocument_sourcekitoptions(self, request: Dict[str, object]) -> Dict[str, object]:
2099+
return {
2100+
"compilerArguments": [r"$TEST_DIR/Test File.swift", "-DDEBUG", $SDK_ARGS] + \
2101+
[f"-DTHIS_IS_AN_OPTION_THAT_CONTAINS_MANY_BYTES_{i}" for i in range(0, 50_000)]
2102+
}
2103+
2104+
def buildtarget_prepare(self, request: Dict[str, object]) -> Dict[str, object]:
2105+
return {}
2106+
""",
2107+
enableBackgroundIndexing: true
2108+
)
2109+
try await project.testClient.send(PollIndexRequest())
2110+
2111+
let symbols = try await project.testClient.send(WorkspaceSymbolsRequest(query: "myTestFunc"))
2112+
XCTAssertEqual(
2113+
symbols,
2114+
[
2115+
.symbolInformation(
2116+
SymbolInformation(
2117+
name: "myTestFunc()",
2118+
kind: .function,
2119+
location: try project.location(from: "1️⃣", to: "1️⃣", in: "Test File.swift")
2120+
)
2121+
)
2122+
]
2123+
)
2124+
}
20432125
}
20442126

20452127
extension HoverResponseContents {

0 commit comments

Comments
 (0)