Skip to content

Commit 5541060

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

File tree

6 files changed

+170
-7
lines changed

6 files changed

+170
-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: 70 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,11 @@ import TSCExtensions
3839
import struct TSCBasic.AbsolutePath
3940
import class TSCBasic.Process
4041
import struct TSCBasic.ProcessResult
42+
import enum TSCBasic.SystemError
43+
#endif
44+
45+
#if os(Windows)
46+
import WinSDK
4147
#endif
4248

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

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)