← Back to Pull requests

コンパイラと Runtime の Medium 指摘11件を修正 #16155

Merged
fumiya-kume merged 32 files (1137 lines) on Dec 01, 2026 13:15 UTC
View on GitHub
fumiya-kume fumiya-kume commented on Dec 01, 2026 12:21 UTC
Author

概要

  • スキャンで指摘された Medium 11件を修正し、回帰テストを追加しました。

  • ZIP の展開量と Android XML・JVM クラスの再帰深度を制限し、KLIB のマニフェスト参照に索引を使うようにしました。

  • APK の ZIP 追加時にファイル名をリテラルとして渡し、署名の子プロセスには環境変数でパスワードを渡すようにしました。

  • Runtime ビルド入力の書き込み権限とキャッシュの整合性を検証します。URLConnection のリダイレクト設定を適用し、ヘッダーを構造化して、応答の受信量と待機時間を制限しました。
  • 更新時の変更点

  • Android の署名パスワードを明示する場合は、--android-store-pass env:<名前> と --android-key-pass env:<名前> で環境変数名を指定します。パスワード本体は子プロセスの引数と失敗診断から除外しました。

  • Runtime キャッシュの形式を更新しました。リンク前にオブジェクトの実パス、所有者、書き込み権限、SHA-256 を確認します。旧キャッシュは初回の利用時に再構築されます。
  • 検証

  • 対象テスト79件が通過しました。パーサー32件、Runtime キャッシュ・APK 35件、Runtime ネットワーク7件、Android CLI 3件、Runtime ABI 2件です。

  • Kotlin のネイティブ結合テストは、空き容量が約3 GBまで低下したため LLVM のコード生成中に中断しました。

  • git diff --check と bash Scripts/build_lean.sh --verify が通過しました。全テストは未実行です。
  • <!-- devin-review-badge-begin -->

    ---

    <a href="https://app.devin.ai/review/kuu-lab/swifty-kotlin/pull/16155" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    Diff: 1137 lines (+890 / -247) across 32 files Reviewer: devin-ai-integration[bot] Review duration: 54m
    All Vouch review confidence checks passed
    Residual risk 0.18 = Change Risk (0.77) × (1 − Review Confidence (0.77)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.77 · 1137 lines diff across 32 files
    0.77
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.59 · 5 substantive comment(s)
    0.59
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    76%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    7 items
    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Dec 01, 2026 12:25 UTC
    Code Review
    Sources/CompilerBackend/CodegenRuntimeSupport+RuntimeObjects.swift:1
    @@ -217,30 +190,67 @@ extension CodegenRuntimeSupport {
             }
         }
     
    -    static func writeRuntimeObjectsManifest(_ paths: [String], to manifestURL: URL) throws {
    -        try FileManager.default.createDirectory(
    -            at: manifestURL.deletingLastPathComponent(),
    -            withIntermediateDirectories: true
    -        )
    -        try (paths.joined(separator: "\n") + "\n")
    -            .write(to: manifestURL, atomically: true, encoding: .utf8)
    +    private struct RuntimeObjectManifestEntry: Codable {
    +        let path: String
    +        let sha256: String
         }
     
    -    static func manifestValidatedRuntimeObjectPaths(manifestURL: URL) -> [String] {
    -        guard let contents = try? String(contentsOf: manifestURL, encoding: .utf8) else {
    -            return []
    +    @discardableResult
    +    static func writeRuntimeObjectsManifest(_ paths: [String], to manifestURL: URL) throws -> [String] {
    +        let root = try prepareTrustedRuntimeDirectory(manifestURL.deletingLastPathComponent())
    +        let prefix = root.path + "/"
    +        let entries = try paths.map { path in
    +            guard let checked = trustedRuntimeObject(at: path, within: root),
    +                  let fingerprint = FileFingerprint.compute(for: checked)
    +            else {
    +                throw CodegenRuntimeSupportError.runtimeBuildFailed("untrusted Runtime object: \(path)")

    <!-- devin-review-comment {"id": "BUG_pr-review-job-c214b2755d8a4b66a814cb73dcd75c85_0001", "file_path": "Sources/CompilerBackend/CodegenRuntimeSupport+RuntimeObjects.swift", "start_line": 202, "end_line": 206, "side": "RIGHT", "based_on_repo_rules": false, "kind": "bug"} -->

    🔴 umask 0002 では新規 Runtime キャッシュを作れず、実行ファイルをリンクできない

    umask が 0002 の環境で Runtime キャッシュを新規作成すると、SwiftPM の出力ディレクトリは 0775 になります。マニフェスト作成時にそのディレクトリが拒否され、正常にビルドできた Runtime をリンクできません。

    <details>
    <summary>Learn more</summary>

    runtimeLinkInputs はキャッシュを準備してから SwiftPM を起動し、生成されたオブジェクトをマニフェストに登録します。ディレクトリ準備処理 の 0700 はコンパイラが作るディレクトリにしか適用されません。SwiftPM の起動 は呼び出し元の umask を引き継ぐので、SwiftPM が既定のモードで作るサブディレクトリは 0002 の下で 0775 になります。オブジェクトの検査 はパス上の全ディレクトリを検査し、グループ書き込み可能なパス を拒否します。内部のディレクトリが外部から到達できない 0700 配下でも、生成直後に拒否されます。

    Example: 0755 のチェックアウトと未使用のプライベートキャッシュを用意し、umask 0002 でネイティブ実行ファイルをコンパイルします。SwiftPM のビルド後、0775 の出力ディレクトリにある Runtime オブジェクトが untrusted Runtime object で拒否されます。同じ umask では再試行しても同じモードで再生成されます。

    Recommended fix: Runtime ビルドの子プロセスだけにグループ・その他ユーザーの書き込みを禁止する umask を設定し、既存の所有者・権限検査は維持してください。呼び出し元の umask が 0002 の子プロセスから空のキャッシュを使ってリンクできることを回帰テストで確認してください。

    </details>

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/kuu-lab/swifty-kotlin/pull/16155" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    ---
    Was this helpful? React with 👍 or 👎 to provide feedback.

    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Dec 01, 2026 12:25 UTC
    Code Review
    Sources/Runtime/RuntimeJavaNetURL.swift:1
    @@ -143,34 +139,62 @@ private func javaNetPerformConnect(
             }
             return false
         }
    -    guard let httpResponse = resultBox.response else {
    +    guard let httpResponse = response.response else {
             outThrown?.pointee = runtimeAllocateIOException(message: "No HTTP response")
             return false
         }
         box.responseCode = httpResponse.statusCode
         box.responseMessage = HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode)
    -    var headers: [(String, [String])] = []
    +    var responseHeaders: [(String, [String])] = []
         for (key, value) in httpResponse.allHeaderFields {
             guard let name = key as? String else { continue }
             if let values = value as? [String] {
    -            headers.append((name, values))
    +            responseHeaders.append((name, values))
             } else {
    -            headers.append((name, ["\(value)"]))
    +            responseHeaders.append((name, ["\(value)"]))
             }
         }
    -    headers.sort { $0.0.localizedCaseInsensitiveCompare($1.0) == .orderedAscending }
    -    box.headerFields = headers
    -    box.bodyData = resultBox.data
    +    responseHeaders.sort { $0.0.localizedCaseInsensitiveCompare($1.0) == .orderedAscending }
    +    box.headerFields = responseHeaders
    +    box.bodyData = response.body
         box.connected = true
         return true
     }
     
    +private func javaNetSocketTimeout() -> Int {
    +    runtimeAllocateJavaNetExceptionShared(
    +        "java.net.SocketTimeoutException", "SocketTimeoutException",
    +        ["java.io.InterruptedIOException", "java.io.IOException"], "connect timed out"
    +    )
    +}
    +
    +func javaNetRequestHeaders(_ elements: [Int]) -> [(String, String)]? {
    +    guard elements.count.isMultiple(of: 2) else { return nil }
    +    let namePunctuation = Set("!#$%&'*+-.^_`|~".utf8)
    +    var headers: [(String, String)] = []
    +    for index in stride(from: 0, to: elements.count, by: 2) {
    +        guard let name = javaNetURLString(elements[index]), !name.isEmpty,
    +              name.utf8.allSatisfy({
    +                  (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0)
    +                      || namePunctuation.contains($0)
    +              }),
    +              let value = javaNetURLString(elements[index + 1]),
    +              value.utf8.allSatisfy({ $0 == 9 || ($0 >= 32 && $0 != 127) })
    +        else { return nil }
    +        headers.append((name, value))
    +    }
    +    return headers
    +}
    +
     @_cdecl("__kk_net_url_open_stream")
     public func __kk_net_url_open_stream(_ specRaw: Int, _ outThrown: UnsafeMutablePointer<Int>?) -> Int {
         return runtimeThrowingBridge(outThrown) {
             let spec = javaNetURLString(specRaw) ?? ""
             let box = RuntimeURLConnectionBox(spec: spec)
    -        guard javaNetPerformConnect(box, serializedHeaders: "", connectTimeoutMs: 0, readTimeoutMs: 0, outThrown: outThrown) else {
    +        guard javaNetPerformConnect(
    +            box, headers: [], followRedirects: true,
    +            connectTimeoutMs: 0, readTimeoutMs: 0, outThrown: outThrown

    <!-- devin-review-comment {"id": "BUG_pr-review-job-c214b2755d8a4b66a814cb73dcd75c85_0002", "file_path": "Sources/Runtime/RuntimeJavaNetURL.swift", "start_line": 194, "end_line": 196, "side": "RIGHT", "based_on_repo_rules": false, "kind": "bug"} -->

    🟡 URL.openStream がリダイレクト無効設定を無視する

    HttpURLConnection.setFollowRedirects(false) の後も、URL.openStream は常に転送をたどります。同じ URL を openConnection().getInputStream() で開いたときと異なり、転送先の本文を返します。

    <details>
    <summary>Learn more</summary>

    Java の URL.openStream() は openConnection().getInputStream() の短縮形です。URL.openConnection は HTTP(S) なら HttpURLConnection を作り、コンストラクタ が現在のリダイレクト設定を保持します。URLConnection.connect はその設定を Runtime に渡します。一方、URL.openStream は別の Runtime 関数を呼び、無条件にリダイレクトを許可します。

    Example: /start が本文 redirect とともに /end への 302 を返し、/end が本文 destination を返すとします。リダイレクトを無効にすると openConnection().getInputStream() は redirect を読みますが、openStream() は /end にアクセスして destination を読みます。

    Recommended fix: HTTP(S) の URL.openStream() を openConnection().getInputStream() に委譲し、両方で同じ設定を適用してください。既存の Kotlin 結合テストに、無効時の openStream() が転送元を読み、転送先に接続しないケースを追加してください。

    </details>

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/kuu-lab/swifty-kotlin/pull/16155" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    ---
    Was this helpful? React with 👍 or 👎 to provide feedback.

    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Dec 01, 2026 12:25 UTC
    Code Review
    Sources/CompilerCore/Klib/ZipArchive.swift:1
    @@ -75,6 +80,15 @@ package struct ZipArchive: Sendable {
                 }
                 _ = flags
     
    +            let uncompressedSize = Int(uncompressedSizeRaw)
    +            guard uncompressedSize <= maximumEntryBytes else {
    +                throw KlibFormatError.archiveExpansionLimit("entry '\(name)' exceeds \(maximumEntryBytes) bytes")
    +            }
    +            guard uncompressedSize <= maximumTotalBytes - totalUncompressedSize else {
    +                throw KlibFormatError.archiveExpansionLimit("archive exceeds \(maximumTotalBytes) bytes")
    +            }
    +            totalUncompressedSize += uncompressedSize

    <!-- devin-review-comment {"id": "ANALYSIS_pr-review-job-c214b2755d8a4b66a814cb73dcd75c85_0001", "file_path": "Sources/CompilerCore/Klib/ZipArchive.swift", "start_line": 83, "end_line": 90, "side": "RIGHT", "kind": "analysis"} -->

    🔍 未展開のリソースも JVM クラスパスの容量制限に含まれる

    クラスパス索引 はクラスファイルだけを展開しますが、ZIP の初期化は未使用のリソースも集計します。クラスパス用途でも JAR 全体を拒否する方針か確認してください。

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/kuu-lab/swifty-kotlin/pull/16155" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    ---
    Was this helpful? React with 👍 or 👎 to provide feedback.

    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Dec 01, 2026 12:26 UTC
    Code Review
    Sources/CompilerBackend/BackendPhaseProvider.swift:1
    @@ -63,8 +63,11 @@ final class RuntimeLinkInputPrefetch: @unchecked Sendable {
             while let current = slot, current.target == target, current.configuration == configuration {
                 if current.finished {
                     slot = nil
    -                guard let result = current.result,
    -                      result.objects.allSatisfy({ FileManager.default.fileExists(atPath: $0) })
    +                guard let result = current.result else { return nil }
    +                let manifestURL = CodegenRuntimeSupport.runtimeSharedScratchRoot()
    +                    .appendingPathComponent(result.fingerprint, isDirectory: true)
    +                    .appendingPathComponent("objects-\(configuration.rawValue).manifest")
    +                guard CodegenRuntimeSupport.manifestValidatedRuntimeObjectPaths(manifestURL: manifestURL) == result.objects

    <!-- devin-review-comment {"id": "ANALYSIS_pr-review-job-c214b2755d8a4b66a814cb73dcd75c85_0002", "file_path": "Sources/CompilerBackend/BackendPhaseProvider.swift", "start_line": 67, "end_line": 70, "side": "RIGHT", "kind": "analysis"} -->

    🔍 先読み済みの Runtime オブジェクトをリンク時に再ハッシュする

    先読み時の検証 と結果取得時の検証で、同じオブジェクト一式を読み直します。増分コンパイルの環境確認にも同じ検証があるため、ウォームキャッシュでリンク時間を計測してください。

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/kuu-lab/swifty-kotlin/pull/16155" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    ---
    Was this helpful? React with 👍 or 👎 to provide feedback.

    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Dec 01, 2026 12:26 UTC
    Code Review
    Sources/RuntimeABI/RuntimeABISpec+JavaNet.swift:1
    @@ -41,6 +41,7 @@ public extension RuntimeABISpec {
             abi.nt("__kk_net_url_connection_set_method", "boxRaw methodRaw", ret: .void),
             abi.nt("__kk_net_url_connection_set_do_output", "boxRaw value", ret: .void),
             abi.th("__kk_net_url_connection_connect", "boxRaw headersRaw connectTimeoutMs readTimeoutMs outThrown", ret: .void),
    +        abi.th("__kk_net_url_connection_connect_with_headers", "boxRaw headersRaw followRedirects connectTimeoutMs readTimeoutMs outThrown", ret: .void),

    <!-- devin-review-comment {"id": "ANALYSIS_pr-review-job-c214b2755d8a4b66a814cb73dcd75c85_0003", "file_path": "Sources/RuntimeABI/RuntimeABISpec+JavaNet.swift", "start_line": 44, "end_line": 44, "side": "RIGHT", "kind": "analysis"} -->

    🔍 非公開 Runtime ブリッジの純増理由が PR 本文にない

    旧ブリッジを残したまま新しいブリッジを追加するため、__kk_ が純増します。ブリッジ入場審査 に従い、理由コードと影響範囲を PR 本文に明記してください。

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/kuu-lab/swifty-kotlin/pull/16155" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    ---
    Was this helpful? React with 👍 or 👎 to provide feedback.*

    devin-ai-integration[bot] devin-ai-integration[bot] commented on Dec 01, 2026 12:26 UTC
    Reviewer

    Devin Review found 5 potential issues.

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/kuu-lab/swifty-kotlin/pull/16155" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    Assignees
    fumiya-kume fumiya-kume
    Labels
    risk: low confidence: 76.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 76.5% (HIGH) · Higher = larger blast radius
    76.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 76.9% · Lower = rushed or shallow review
    76.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 17.7% · Safe to merge
    17.7%