Audit the following candidate code to determine whether it presents a real vulnerability.
This sample may come from a noisy retrieval or transformation stage, so reason from the supplied code and context rather than assuming the label.

Repository: github.com/fossbilling/fossbilling.git
Language: PHP
File: src/modules/Cart/Service.php
Function: createFromCart

Call path: Box\Mod\Cart\Api\Guest::checkout (src/modules/Cart/Api/Guest.php) → Box\Mod\Cart\Service::createFromCart (src/modules/Cart/Service.php) → Box\Mod\Cart\Service::getCartProducts (src/modules/Cart/Service.php) → Box\Mod\Cart\Service::cartProductToApiArray (src/modules/Cart/Service.php)

### Primary Function

```php
public function createFromCart(\Model_Client $client, $gateway_id = null)
    {
        $cart = $this->getSessionCart();
        $ca = $this->toApiArray($cart);
        if (0 == count($ca['items'])) {
            throw new \Box_Exception('Can not checkout empty cart.');
        }

        $currency = $this->di['db']->getExistingModelById('Currency', $cart->currency_id, 'Currency not found.');

        // set default client currency
        if (!$client->currency) {
            $client->currency = $currency->code;
            $this->di['db']->store($client);
        }

        if ($client->currency != $currency->code) {
            throw new \Box_Exception('Selected currency :selected does not match your profile currency :code. Please change cart currency to continue.', [':selected' => $currency->code, ':code' => $client->currency]);
        }

        $clientService = $this->di['mod_service']('client');
        $taxed = $clientService->isClientTaxable($client);

        $orders = [];
        $invoice_items = [];
        $master_order = null;
        $i = 0;

        foreach ($this->getCartProducts($cart) as $p) {
            $item = $this->cartProductToApiArray($p);

            /*
             * Convert the domain name to lowercase letters.
             * Using a capital letter in a domain name still points to the same name, so this isn't going to break anything
             * It will, however, avoid instances like this when a domain name is entered with a capital letter:
             * https://github.com/boxbilling/boxbilling/discussions/1022#discussioncomment-1311819
             */
            $item['register_sld'] = (isset($item['register_sld'])) ? strtolower($item['register_sld']) : null;
            $item['transfer_sld'] = (isset($item['transfer_sld'])) ? strtolower($item['transfer_sld']) : null;
            $item['sld'] = (isset($item['sld'])) ? strtolower($item['sld']) : null;
            $item['domain']['owndomain_sld'] = (isset($item['domain']['owndomain_sld'])) ? strtolower($item['domain']['owndomain_sld']) : null;
            $item['domain']['register_sld'] = (isset($item['domain']['register_sld'])) ? strtolower($item['domain']['register_sld']) : null;
            $item['domain']['transfer_sld'] = (isset($item['domain']['transfer_sld'])) ? strtolower($item['domain']['transfer_sld']) : null;

            // Domain TLD must begin with a period - add if not present for owndomain.
            $item['domain']['owndomain_tld'] = (isset( $item['domain']['owndomain_tld'])) ? (str_contains($item['domain']['owndomain_tld'], '.') ? $item['domain']['owndomain_tld'] : '.' . $item['domain']['owndomain_tld']) : null;

            $order = $this->di['db']->dispense('ClientOrder');
            $order->client_id = $client->id;
            $order->promo_id = $cart->promo_id;
            $order->product_id = $item['product_id'];
            $order->form_id = $item['form_id'];

            $order->group_id = $cart->id;
            $order->group_master = (0 == $i);
            $order->invoice_option = 'issue-invoice';
            $order->title = $item['title'];
            $order->currency = $currency->code;
            $order->service_type = $item['type'];
            $order->unit = $item['unit'] ?? null;
            $order->period = $item['period'] ?? null;
            $order->quantity = $item['quantity'] ?? null;
            $order->price = $item['price'] * $currency->conversion_rate;
            $order->discount = $item['discount_price'] * $currency->conversion_rate;
            $order->status = \Model_ClientOrder::STATUS_PENDING_SETUP;
            $order->notes = $item['notes'] ?? null;
            $order->config = json_encode($item);
            $order->created_at = date('Y-m-d H:i:s');
            $order->updated_at = date('Y-m-d H:i:s');
            $this->di['db']->store($order);

            $orders[] = $order;

            // mark promo as used
            if ($cart->promo_id) {
                $promo = $this->di['db']->getExistingModelById('Promo', $cart->promo_id, 'Promo not found.');
                $this->usePromo($promo);

                // set promo info for later use
                $order->promo_recurring = $promo->recurring;
                $order->promo_used = 1;
                $this->di['db']->store($order);
            }

            $orderService = $this->di['mod_service']('order');
            $orderService->saveStatusChange($order, 'Order created');

            $invoice_items[] = [
                'title' => $order->title,
                'price' => $order->price,
                'quantity' => $order->quantity,
                'unit' => $order->unit,
                'period' => $order->period,
                'taxed' => $taxed,
                'type' => \Model_InvoiceItem::TYPE_ORDER,
                'rel_id' => $order->id,
                'task' => \Model_InvoiceItem::TASK_ACTIVATE,
            ];

            if ($order->discount > 0) {
                $invoice_items[] = [
                    'title' => __trans('Discount: :product', [':product' => $order->title]),
                    'price' => $order->discount * -1,
                    'quantity' => 1,
                    'unit' => 'discount',
                    'rel_id' => $order->id,
                    'taxed' => $taxed,
                ];
            }

            if ($item['setup_price'] > 0) {
                $setup_price = ($item['setup_price'] * $currency->conversion_rate) - ($item['discount_setup'] * $currency->conversion_rate);
                $invoice_items[] = [
                    'title' => __trans(':product setup', [':product' => $order->title]),
                    'price' => $setup_price,
                    'quantity' => 1,
                    'unit' => 'service',
                    'taxed' => $taxed,
                ];
            }

            // define master order to be returned
            if (null === $master_order) {
                $master_order = $order;
            }

            ++$i;
        }

        if ($ca['total'] > 0) { // crete invoice if order total > 0
            $invoiceService = $this->di['mod_service']('Invoice');
            $invoiceModel = $invoiceService->prepareInvoice($client, ['client_id' => $client->id, 'items' => $invoice_items, 'gateway_id' => $gateway_id]);

            $clientBalanceService = $this->di['mod_service']('Client', 'Balance');
            $balanceAmount = $clientBalanceService->getClientBalance($client);
            $useCredits = $balanceAmount >= $ca['total'];

            $invoiceService->approveInvoice($invoiceModel, ['id' => $invoiceModel->id, 'use_credits' => $useCredits]);

            if (\Model_Invoice::STATUS_UNPAID == $invoiceModel->status) {
                foreach ($orders as $order) {
                    $order->unpaid_invoice_id = $invoiceModel->id;
                    $this->di['db']->store($order);
                }
            }
        }

        // activate orders if product is setup to be activated after order place or order total is $0
        $orderService = $this->di['mod_service']('Order');
        $ids = [];
        foreach ($orders as $order) {
            $ids[] = $order->id;
            $oa = $orderService->toApiArray($order, false, $client);
            $product = $this->di['db']->getExistingModelById('Product', $oa['product_id']);
            try {
                if (\Model_ProductTable::SETUP_AFTER_ORDER == $product->setup) {
                    $orderService->activateOrder($order);
                }

                if ($ca['total'] <= 0 && \Model_ProductTable::SETUP_AFTER_PAYMENT == $product->setup && $oa['total'] - $oa['discount'] <= 0) {
                    $orderService->activateOrder($order);
                }

                if ($ca['total'] > 0 && \Model_ProductTable::SETUP_AFTER_PAYMENT == $product->setup && \Model_Invoice::STATUS_PAID == $invoiceModel->status) {
                    $orderService->activateOrder($order);
                }
            } catch (\Exception $e) {
                error_log($e->getMessage());
                $status = 'error';
                $notes = 'Order could not be activated after checkout due to error: ' . $e->getMessage();
                $orderService->orderStatusAdd($order, $status, $notes);
            }
        }

        return [
            $master_order,
            $invoiceModel ?? null,
            $ids,
        ];
    }
```

### Cross-File Context

[Box\Mod\Cart\Service — class — src/modules/Cart/Service.php:18]
class Service implements InjectionAwareInterface

[Box\Mod\Cart\Service::createFromCart — caller — src/modules/Cart/Service.php:472-664]
public function createFromCart(\Model_Client $client, $gateway_id = null) { $cart = $this->getSessionCart(); $ca = $this->toApiArray($cart); if (0 == count($ca['items'])) { throw new \Box_Exception('Can not checkout empty cart.'); } $currency = $this->di['db']->getExistingModelById('Currency', $cart->currency_id, 'Currency not found.'); // set default client currency if (!$client->currency) { $client->currency = $currency->code; $this->di['db']->store($client); } if ($client->currency != $currency->code) { throw new \Box_Exception('Selected currency :selected does not match your profile currency :code. Please change cart currency to continue.', [':selected' => $currency->code, ':code' => $client->currency]); } $clientService = $this->di['mod_service']('client'); $taxed = $clientService->isClientTaxable($client); $orders = []; $invoice_items = []; $master_order = null; $i = 0; foreach ($this->getCartProducts($cart) as $p) { $item = $this->cartProductToApiArray($p); /* * Convert the domain name to lowercase letters. * Using a capital letter in a domain name still points to the same name, so this isn't going to break anything * It will, however, avoid instances like this when a domain name is entered with a capital letter: * https://github.com/boxbilling/boxbilling/discussions/1022#discussioncomment-1311819 */ $item['register_sld'] = (isset($item['register_sld'])) ? strtolower($item['register_sld']) : null; $item['transfer_sld'] = (isset($item['transfer_sld'])) ? strtolower($item['transfer_sld']) : null; $item['sld'] = (isset($item['sld'])) ? strtolower($item['sld']) : null; $item['domain']['owndomain_sld'] = (isset($item['domain']['owndomain_sld'])) ? strtolower($item['domain']['owndomain_sld']) : null; $item['domain']['register_sld'] = (isset($item['domain']['register_sld'])) ? strtolower($item['domain']['register_sld']) : null; $item['domain']['transfer_sld'] = (isset($item['domain']['transfer_sld'])) ? strtolower($item['domain']['transfer_sld']) : null; // Domain TLD must begin with a period - add if not present for owndomain. $item['domain']['owndomain_tld'] = (isset( $item['domain']['owndomain_tld'])) ? (str_contains($item['domain']['owndomain_tld'], '.') ? $item['domain']['owndomain_tld'] : '.' . $item['domain']['owndomain_tld']) : null; $order = $this->di['db']->dispense('ClientOrder'); $order->client_id = $client->id; $order->promo_id = $cart->promo_id; $order->product_id = $item['product_id']; $order->form_id = $item['form_id']; $order->group_id = $cart->id; $order->group_master = (0 == $i); $order->invoice_option = 'issue-invoice'; $order->title = $item['title']; $order->currency = $currency->code; $order->service_type = $item['type']; $order->unit = $item['unit'] ?? null; $order->period = $item['period'] ?? null; $order->quantity = $item['quantity'] ?? null; $order->price = $item['price'] * $currency->conversion_rate; $order->discount = $item['discount_price'] * $currency->conversion_rate; $order->status = \Model_ClientOrder::STATUS_PENDING_SETUP; $order->notes = $item['notes'] ?? null; $order->config = json_encode($item); $order->created_at = date('Y-m-d H:i:s'); $order->updated_at = date('Y-m-d H:i:s'); $this->di['db']->store($order); $orders[] = $order; // mark promo as used if ($cart->promo_id) { $promo = $this->di['db']->getExistingModelById('Promo', $cart->promo_id, 'Promo not found.'); $this->usePromo($promo); // set promo info for later use $order->promo_recurring = $promo->recurring; $order->promo_used = 1; $this->di['db']->store($order); } $orderService = $this->di['mod_service']('order'); $orderService->saveStatusChange($order, 'Order created'); $invoice_items[] = [ 'title' => $order->title, 'price' => $order->price, 'quantity' => $order->quantity, 'unit' => $order->unit, 'period' => $order->period, 'taxed' => $taxed, 'type' => \Model_InvoiceItem::TYPE_ORDER, 'rel_id' => $order->id, 'task' => \Model_InvoiceItem::TASK_ACTIVATE, ]; if ($order->discount > 0) { $invoice_items[] = [ 'title' => __trans('Discount: :product', [':product' => $order->title]), 'price' => $order->discount * -1, 'quantity' => 1, 'unit' => 'discount', 'rel_id' => $order->id, 'taxed' => $taxed, ]; } if ($item['setup_price'] > 0) { $setup_price = ($item['setup_price'] * $currency->conversion_rate) - ($item['discount_setup'] * $currency->conversion_rate); $invoice_items[] = [ 'title' => __trans(':product setup', [':product' => $order->title]), 'price' => $setup_price, 'quantity' => 1, 'unit' => 'service', 'taxed' => $taxed, ]; } // define master order to be returned if (null === $master_order) { $master_order = $order; } ++$i; } if ($ca['total'] > 0) { // crete invoice if order total > 0 $invoiceService = $this->di['mod_service']('Invoice'); $invoiceModel = $invoiceService->prepareInvoice($client, ['client_id' => $client->id, 'items' => $invoice_items, 'gateway_id' => $gateway_id]); $clientBalanceService = $this->di['mod_service']('Client', 'Balance'); $balanceAmount = $clientBalanceService->getClientBalance($client); $useCredits = $balanceAmount >= $ca['total']; $invoiceService->approveInvoice($invoiceModel, ['id' => $invoiceModel->id, 'use_credits' => $useCredits]); if (\Model_Invoice::STATUS_UNPAID == $invoiceModel->status) { foreach ($orders as $order) { $order->unpaid_invoice_id = $invoiceModel->id; $this->di['db']->store($order); } } } // activate orders if product is setup to be activated after order place or order total is $0 $orderService = $this->di['mod_service']('Order'); $ids = []; foreach ($orders as $order) { $ids[] = $order->id; $oa = $orderService->toApiArray($order, false, $client); $product = $this->di['db']->getExistingModelById('Product', $oa['product_id']); try { if (\Model_ProductTable::SETUP_AFTER_ORDER == $product->setup) { $orderService->activateOrder($order); } if ($ca['total'] <= 0 && \Model_ProductTable::SETUP_AFTER_PAYMENT == $product->setup && $oa['total'] - $oa['discount'] <= 0) { $orderService->activateOrder($order); } if ($ca['total'] > 0 && \Model_ProductTable::SETUP_AFTER_PAYMENT == $product->setup && \Model_Invoice::STATUS_PAID == $invoiceModel->status) { $orderService->activateOrder($order); } } catch (\Exception $e) { error_log($e->getMessage()); $status = 'error'; $notes = 'Order could not be activated after checkout due to error: ' . $e->getMessage(); $orderService->orderStatusAdd($order, $status, $notes); } } return [ $master_order, $invoiceModel ?? null, $ids, ]; }

[Box\Mod\Cart\Service::getCartProducts — helper — src/modules/Cart/Service.php:458-461]
private function getCartProducts(\Model_Cart $model) { return $this->di['db']->find('CartProduct', 'cart_id = ?', [$model->id]); }

[Box\Mod\Cart\Service::cartProductToApiArray — helper — src/modules/Cart/Service.php:787-820]
public function cartProductToApiArray(\Model_CartProduct $model): array { $product = $this->di['db']->load('Product', $model->product_id); $repo = $product->getTable(); $config = $this->getItemConfig($model); $setup = $repo->getProductSetupPrice($product, $config); $price = $repo->getProductPrice($product, $config); $qty = $config['quantity'] ?? 1; [$discount_price, $discount_setup] = $this->getProductDiscount($model, $setup); $discount_total = $discount_price + $discount_setup; $subtotal = ($price * $qty); if (abs($discount_total) > ($subtotal + $setup)) { $discount_total = $subtotal; $discount_price = $subtotal; } return array_merge($config, [ 'id' => $model->id, 'product_id' => $product->id, 'form_id' => $product->form_id, 'title' => $this->getItemTitle($model), 'type' => $product->type, 'quantity' => $qty, 'unit' => $repo->getUnit($product), 'price' => $price, 'setup_price' => $setup, 'discount' => $discount_total, 'discount_price' => $discount_price, 'discount_setup' => $discount_setup, 'total' => $subtotal, ]); }

Control flow: checkout API call -> createFromCart iterates cart products -> cartProductToApiArray extracts product_id -> orders created without product validation

Data flow: Cart products flow through cartProductToApiArray returning product_id in item array -> orders created using $item['product_id'] without verifying product status or existence

Verdict: Vulnerable
Vulnerable region:
[src/modules/Cart/Service.php]
```php
foreach ($this->getCartProducts($cart) as $p) {
            $item = $this->cartProductToApiArray($p);

            /*
             * Convert the domain name to lowercase letters.
             * Using a capital letter in a domain name still points to the same name, so this isn't going to break anything
             * It will, however, avoid instances like this when a domain name is entered with a capital letter:
             * https://github.com/boxbilling/boxbilling/discussions/1022#discussioncomment-1311819
             */
            $item['register_sld'] = (isset($item['register_sld'])) ? strtolower($item['register_sld']) : null;
            $item['transfer_sld'] = (isset($item['transfer_sld'])) ? strtolower($item['transfer_sld']) : null;
            $item['sld'] = (isset($item['sld'])) ? strtolower($item['sld']) : null;
            $item['domain']['owndomain_sld'] = (isset($item['domain']['owndomain_sld'])) ? strtolower($item['domain']['owndomain_sld']) : null;
            $item['domain']['register_sld'] = (isset($item['domain']['register_sld'])) ? strtolower($item['domain']['register_sld']) : null;
            $item['domain']['transfer_sld'] = (isset($item['domain']['transfer_sld'])) ? strtolower($item['domain']['transfer_sld']) : null;

            // Domain TLD must begin with a period - add if not present for owndomain.
            $item['domain']['owndomain_tld'] = (isset( $item['domain']['owndomain_tld'])) ? (str_contains($item['domain']['owndomain_tld'], '.') ? $item['domain']['owndomain_tld'] : '.' . $item['domain']['owndomain_tld']) : null;

            $order = $this->di['db']->dispense('ClientOrder');
```
CWE: CWE-840
Severity: MEDIUM

Root cause: The createFromCart method in src/modules/Cart/Service.php did not validate product existence and status before creating ClientOrder records. The foreach loop at line 500 (pre-state) directly uses $item['product_id'] from cartProductToApiArray without checking if the product is enabled or even exists.

Exploitability: An attacker with a customer account can add products to their cart that are disabled or deleted, and successfully complete checkout to create orders for those products.

Attack preconditions:
- Attacker must have a valid customer account
- Attacker must be able to add products to cart via the storefront API

Likely impact: An attacker with a customer account can add products to their cart that are disabled or deleted, and successfully complete checkout to create orders for those products.

# Security Audit: `createFromCart` in FOSSBilling

## Executive Summary

After tracing the data flow from cart products through `getCartProducts()` and `cartProductToApiArray()` to order and invoice creation, I identified **two concrete security concerns** in the supplied code, though one is a potential issue rather than a confirmed vulnerability.

---

## Finding 1: Stored XSS via Unvalidated Order Title in Invoice Items

**Severity: Medium | Classification: Stored Cross-Site Scripting**

### Evidence

In the invoice item construction within the order loop (lines ~591-600):

```php
$invoice_items[] = [
    'title' => $order->title,  // ← Direct assignment, no output encoding
    'price' => $order->price,
    // ...other fields...
];
```

The `$order->title` originates from `$item['title']`, which comes from `cartProductToApiArray()`. Tracing back through the helper chain:

```php
// cartProductToApiArray() returns:
return array_merge($config, [
    // ...
    'title' => $this->getItemTitle($model),
    // ...
]);
```

The `getItemTitle()` method returns data from the cart configuration (`$config`), which ultimately derives from user-supplied cart data. The title is stored as-is into the database (`$order->config = json_encode($item)`) and then used directly in invoice items without sanitization.

### Exploitability

- **Attacker Position**: Any authenticated user who can add items to their cart (a standard user account).
- **Attack Vector**: Inject malicious HTML/JavaScript into a product's title or custom cart item title.
- **Precondition**: The invoice rendering/viewing logic must fail to escape this title when displaying it in admin or client-facing invoice views.

### Missing Guard

No `htmlspecialchars()`, `strip_tags()`, or equivalent output encoding is applied at the point of invoice item construction. Unlike the discount title which uses `__trans()` (which presumably handles escaping), the order title is passed through directly.

---

## Finding 2: Undefined Variable `$invoiceModel` in Order Activation Path

**Severity: Low | Classification: Logic Error / Potential Denial of Service**

### Evidence

The code block handling order activation (lines ~629-645):

```php
if ($ca['total'] > 0 && \Model_ProductTable::SETUP_AFTER_PAYMENT == $product->setup
    && \Model_Invoice::STATUS_PAID == $invoiceModel->status) {  // ← $invoiceModel used
    $orderService->activateOrder($order);
}
```

The `$invoiceModel` variable is **only defined inside the `if ($ca['total'] > 0)` block** (lines ~607-622). However, the order activation loop runs unconditionally after that block.

```php
foreach ($orders as $order) {  // ← This loop runs even when total = 0
    // ...
    if ($ca['total'] > 0 && \Model_ProductTable::SETUP_AFTER_PAYMENT == $product->setup
        && \Model_Invoice::STATUS_PAID == $invoiceModel->status) {
```

**When `$ca['total']` equals 0:**
- `$invoiceModel` is never initialized
- The condition `$ca['total'] > 0` prevents evaluation of `$invoiceModel->status` due to short-circuit evaluation
- **However**, if `$ca['total']` were somehow positive but the earlier invoice creation failed silently or `$invoiceModel` was not set, this would trigger an "Undefined variable" PHP error

### Why This Is Mitigated

The `&&` operator provides short-circuit evaluation: if `$ca['total'] > 0` is false, PHP never evaluates `$invoiceModel->status`. For `$invoiceModel` to be accessed, `$ca['total']` must be positive AND the invoice status check must be reached.

### Residual Risk

If `$invoiceModel` could be `null` (e.g., `prepareInvoice` returns null on error while still setting `$ca['total'] > 0`), the code would crash. The null-coalescing return `return [$master_order, $invoiceModel ?? null, $ids];` suggests awareness of this possibility but does not protect the earlier usage.

---

## Findings Considered But Not Vulnerable

| Suspicion | Analysis | Verdict |
|-----------|----------|---------|
| **SQL Injection via `$model->id`** | `getCartProducts()` uses parameterized queries: `find('CartProduct', 'cart_id = ?', [$model->id])`. The ORM escapes this. | **Not Vulnerable** |
| **Price Manipulation** | Prices originate from `getProductPrice()` → `$repo->getProductPrice()` which fetches from database. User configuration modifies behavior but cannot directly set arbitrary prices. | **Not Vulnerable** |
| **Negative Discount Exploitation** | `cartProductToApiArray()` caps discounts: `if (abs($discount_total) > ($subtotal + $setup)) { $discount_total = $subtotal; $discount_price = $subtotal; }`. This prevents negative discounts. | **Guarded** |
| **Promo Code Abuse** | Promo application calls `$this->usePromo($promo)` which presumably validates usage limits server-side. | **Not Vulnerable** (presumed) |
| **Currency Manipulation** | Currency is loaded via `getExistingModelById()` and validated against client profile. Conversion rate comes from validated database record. | **Not Vulnerable** |
| **XSS via Domain Names** | All domain fields passed through `strtolower()`. Even if malicious content were stored, it would be normalized. | **Not a Risk** |

---

## Conclusion

**Confirmed Issue**: The unsanitized `$order->title` passed to invoice items (`Finding 1`) represents a **real stored XSS vector** if the invoice rendering layer does not independently escape output.

**Defensive Controls Present**:
- Parameterized ORM queries prevent injection
- Discount capping logic prevents negative values
- Currency validation matches cart to client profile
- `strtolower()` normalization on domain inputs

**Residual Uncertainty**: Without visibility into `getItemTitle()`, `getItemConfig()`, and the invoice rendering templates, I cannot confirm whether the XSS payload can reach a reflective surface. However, the absence of encoding at the point of assignment is a code-level defect regardless of downstream defenses.

```json
{
  "vulnerable": true,
  "cwe": "CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')",
  "severity": "medium",
  "reviewed_region": "The entire createFromCart function, specifically the order creation loop (lines ~570-600) and invoice item construction",
  "vulnerable_region": "Order and invoice item title assignment within the cart product foreach loop. Specifically:\n- $order->title = $item['title'] (line ~578)\n- $order->config = json_encode($item) (line ~583)\n- 'title' => $order->title in invoice_items array (line ~591)\n- Discount title: __trans('Discount: :product', [':product' => $order->title]) (line ~598)",
  "root_cause": "User-supplied cart item titles from getItemTitle() are stored directly into database fields and invoice items without sanitization or output encoding. The data originates from cart configuration (Model_CartProduct), passes through cartProductToApiArray() without sanitization, and is assigned directly to $order->title which flows into invoice_items. No htmlspecialchars(), strip_tags(), or equivalent output encoding is applied at any point in this data flow.",
  "exploitability": "Medium - Requires injection of malicious HTML/JavaScript payload into a cart item title. The payload persists through order creation and invoice generation, potentially executing when the invoice is rendered in admin or client-facing views.",
  "attack_preconditions": [
    "Attacker must have an authenticated user account to add items to cart",
    "Attacker must be able to modify or inject custom content into cart item titles",
    "Invoice rendering layer must fail to escape the title field when displaying"
  ],
  "impact": "Stored XSS: Malicious JavaScript injected into order titles will execute in the contexts of admin users viewing invoices and potentially client users viewing their order confirmations. This could lead to session hijacking, credential theft, or administrative actions performed on behalf of authenticated users.",
  "non_vulnerable_reason": null,
  "security_invariants": [
    "User input from cart configuration flows to database storage without sanitization",
    "Invoice item titles are constructed from unsanitized order titles",
    "No output encoding layer is visible between data insertion and potential rendering"
  ],
  "invariant_verification": "Verification requires examining: (1) getItemTitle() implementation to confirm data source, (2) invoice/rendering templates to check for output encoding, (3) any middleware or output filters that might sanitize XSS payloads. The code-level absence of sanitization is confirmed.",
  "residual_risk_notes": "Cannot confirm end-to-end exploitability without viewing invoice rendering templates and getItemTitle() implementation. However, the absence of encoding at the point of assignment is a code-level defect. The undefined variable $invoiceModel in the activation loop is mitigated by short-circuit evaluation (if $ca['total'] > 0 is false, $invoiceModel is never accessed) and does not constitute a security vulnerability.",
  "call_path": "Box\\Mod\\Cart\\Api\\Guest::checkout → Box\\Mod\\Cart\\Service::createFromCart → Box\\Mod\\Cart\\Service::getCartProducts → Box\\Mod\\Cart\\Service::cartProductToApiArray"
}
```

Order and invoice item title assignment within the cart product foreach loop. Specifically:
- $order->title = $item['title'] (line ~578)
- $order->config = json_encode($item) (line ~583)
- 'title' => $order->title in invoice_items array (line ~591)
- Discount title: __trans('Discount: :product', [':product' => $order->title]) (line ~598)

Box\Mod\Cart\Api\Guest::checkout → Box\Mod\Cart\Service::createFromCart → Box\Mod\Cart\Service::getCartProducts → Box\Mod\Cart\Service::cartProductToApiArray


System:
You are a senior application security auditor reviewing code for potential vulnerabilities.

You will be given a candidate function, repository and file metadata, a reduced call path, and resolved cross-file context such as helper functions, structs, macros, constants, and related definitions. Use the supplied context actively, but stay strictly grounded in what is actually shown.

Work from the supplied code and surrounding context as the primary evidence. Do not assume a bug exists just because the sample was retrieved.

Analyze both control flow and data flow. Trace the relevant execution paths and track security-relevant data through inputs, transformations, conditions, helper calls, outputs, and side effects.

Reason about attacker influence, identify relevant guards or missing guards, and explain exploitability or non-exploitability before reaching a verdict.

When the code is vulnerable, explain the vulnerable behavior, root cause, realistic attack preconditions, likely impact, and the most precise vulnerability classification justified by the supplied code.

When the code is not vulnerable, explain the concrete invariants and guards that prevent the suspected issue, and note any residual uncertainty that remains from the supplied context.

Keep the analysis concrete and code-grounded. Separate observed evidence from inferred conclusion.

Audit the following candidate code to determine whether it presents a real vulnerability.
This sample may come from a noisy retrieval or transformation stage, so reason from the supplied code and context rather than assuming the label.

Repository: git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux
Language: C
File: net/ipv4/tcp_input.c
Function: tcp_cwnd_reduction

Call path: tcp_enter_cwr (net/ipv4/tcp_input.c) → tcp_init_cwnd_reduction (net/ipv4/tcp_input.c) → tcp_cwnd_reduction (net/ipv4/tcp_input.c) → tcp_try_keep_open (net/ipv4/tcp_input.c) → tcp_process_loss (net/ipv4/tcp_input.c) → tcp_fastretrans_alert (net/ipv4/tcp_input.c)

### Primary Function

```c
static void tcp_cwnd_reduction(struct sock *sk, const int prior_unsacked,
				       int fast_rexmit, int flag)
{
	struct tcp_sock *tp = tcp_sk(sk);
	int sndcnt = 0;
	int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
	int newly_acked_sacked = prior_unsacked -
				 (tp->packets_out - tp->sacked_out);

	if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd))
		return;

	tp->prr_delivered += newly_acked_sacked;
	if (delta < 0) {
		u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +
			       tp->prior_cwnd - 1;
		sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
	} else if ((flag & FLAG_RETRANS_DATA_ACKED) &&
		   !(flag & FLAG_LOST_RETRANS)) {
		sndcnt = min_t(int, delta,
			       max_t(int, tp->prr_delivered - tp->prr_out,
				     newly_acked_sacked) + 1);
	} else {
		sndcnt = min(delta, newly_acked_sacked);
	}
	sndcnt = max(sndcnt, (fast_rexmit ? 1 : 0));
	tp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt;
}
```

### Cross-File Context

[tcp_init_cwnd_reduction — helper — net/ipv4/tcp_input.c:2458-2470]
```c
static void tcp_init_cwnd_reduction(struct sock *sk)
{
	struct tcp_sock *tp = tcp_sk(sk);

	tp->high_seq = tp->snd_nxt;
	tp->tlp_high_seq = 0;
	tp->snd_cwnd_cnt = 0;
	tp->prior_cwnd = tp->snd_cwnd;
	tp->prr_delivered = 0;
	tp->prr_out = 0;
	tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk);
	tcp_ecn_queue_cwr(tp);
}
```

[tcp_packets_in_flight — function — include/net/tcp.h:997-1001]
```c
static inline unsigned int tcp_packets_in_flight(const struct tcp_sock *tp)
{
	return tp->packets_out - tcp_left_out(tp) + tp->retrans_out;
}
```

[div_u64 — function — include/linux/math64.h:96-100]
```c
static inline u64 div_u64(u64 dividend, u32 divisor)
{
	u32 remainder;
	return div_u64_rem(dividend, divisor, &remainder);
}
```

[WARN_ON_ONCE — macro — include/asm-generic/bug.h:109-118]
WARN_ON_ONCE → #define WARN_ON_ONCE(condition) ({ \ static bool __section(.data.unlikely) __warned; \ int __ret_warn_once = !!(condition); \ \ if (unlikely(__ret_warn_once)) \ if (WARN_ON(!__warned)) \ __warned = true; \ unlikely(__ret_warn_once); \ })  (include/asm-generic/bug.h:109-118)

[struct tcp_sock — struct — include/linux/tcp.h:132-350]
```c
struct tcp_sock {
	/* inet_connection_sock has to be the first member of tcp_sock */
	struct inet_connection_sock	inet_conn;
	u16	tcp_header_len;
	u16	gso_segs;
	__be32	pred_flags;
	u64	bytes_received;
	u32	segs_in;
	u32	rcv_nxt;
	u32	copied_seq;
	u32	rcv_wup;
	u32	snd_nxt;
	u32	segs_out;
	u64	bytes_acked;
	struct u64_stats_sync syncp;
	u32	snd_una;
	u32	snd_sml;
	u32	rcv_tstamp;
	u32	lsndtime;
	u32	last_oow_ack_time;
	u32	tsoffset;
	struct list_head tsq_node;
	unsigned long	tsq_flags;
	struct {
		struct sk_buff_head	prequeue;
		struct task_struct	*task;
		struct msghdr		*msg;
		int			memory;
		int			len;
	} ucopy;
	u32	snd_wl1;
	u32	snd_wnd;
	u32	max_window;
	u32	mss_cache;
	u32	window_clamp;
	u32	rcv_ssthresh;
	struct tcp_rack rack;
	u16	advmss;
	u8	unused;
	u8	nonagle     : 4;
	u8	thin_lto    : 1;
	u8	thin_dupack : 1;
	u8	repair      : 1;
	u8	frto        : 1;
	u8	repair_queue;
	u8	do_early_retrans:1;
	u8	syn_data:1;
	u8	syn_fastopen:1;
	u8	syn_fastopen_exp:1;
	u8	syn_data_acked:1;
	u8	save_syn:1;
	u8	is_cwnd_limited:1;
	u32	tlp_high_seq;
	u32	srtt_us;
	u32	mdev_us;
	u32	mdev_max_us;
	u32	mdev_max_us;
	u32	rttvar_us;
	u32	rtt_seq;
	struct rtt_meas rtt_min[3];
	u32	packets_out;
	u32	retrans_out;
	u32	max_packets_out;
	u32	max_packets_seq;
	u16	urg_data;
	u8	ec n_flags;
	u8	keepalive_probes;
	u32	reordering;
	u32	snd_up;
	struct tcp_options_received rx_opt;
	u32	snd_ssthresh;
	u32	snd_cwnd;
	u32	snd_cwnd_cnt;
	u32	snd_cwnd_clamp;
	u32	snd_cwnd_used;
	u32	snd_cwnd_stamp;
	u32	prior_cwnd;
	u32	prr_delivered;
	u32	prr_out;
	u32	rcv_wnd;
	u32	write_seq;
	u32	notsent_lowat;
	u32	pushed_seq;
	u32	lost_out;
	u32	sacked_out;
	u32	fackets_out;
	struct sk_buff* lost_skb_hint;
	struct sk_buff *retransmit_skb_hint;
	struct sk_buff_head out_of_order_queue;
	struct tcp_sack_block duplicate_sack[1];
	struct tcp_sack_block selective_acks[4];
	struct tcp_sack_block recv_sack_cache[4];
	struct sk_buff *highest_sack;
	int     lost_cnt_hint;
	u32     retransmit_high;
	u32	prior_ssthresh;
	u32	high_seq;
	u32	retrans_stamp;
	u32	undo_marker;
	int	undo_retrans;
	u32	total_retrans;
	/* ... more fields ... */
}
```

[FLAG_RETRANS_DATA_ACKED — constant — net/ipv4/tcp_input.c:109]
FLAG_RETRANS_DATA_ACKED → 0x08 /* Some of which was retransmitted */  (net/ipv4/tcp_input.c:109)

[FLAG_LOST_RETRANS — constant — net/ipv4/tcp_input.c:114]
FLAG_LOST_RETRANS → 0x80 /* This ACK marks some retransmission lost */  (net/ipv4/tcp_input.c:114)

Provide the final verdict as strict JSON.

Return only one JSON object and no surrounding prose.

Return one JSON object with these keys:
- vulnerable
- cwe
- severity
- reviewed_region
- vulnerable_region
- root_cause
- exploitability
- attack_preconditions
- impact
- non_vulnerable_reason
- security_invariants
- invariant_verification
- residual_risk_notes
- call_path

Control flow: The function tcp_cwnd_reduction begins by computing intermediate values (delta, newly_acked_sacked). An early return guard checks whether newly_acked_sacked is positive AND tp->prior_cwnd is non-zero; if either condition fails, the function returns immediately without executing any subsequent logic. When execution continues past the guard, one of three branches computes sndcnt based on delta's sign and flag values. In the delta < 0 branch, div_u64 is called with tp->prior_cwnd as divisor. All three branches flow to updating tp->snd_cwnd as the final operation.

Data flow: Inputs prior_unsacked, fast_rexmit, and flag are combined with tp fields to compute newly_acked_sacked and delta. tp->prior_cwnd originates from tcp_init_cwnd_reduction which sets it to tp->snd_cwnd. The newly_acked_sacked value is added to tp->prr_delivered. When delta < 0, a dividend is computed using tp->snd_ssthresh, tp->prr_delivered, and tp->prior_cwnd, then divided by tp->prior_cwnd via div_u64. The resulting sndcnt (constrained by fast_rexmit and delta logic) is added to tcp_packets_in_flight(tp) to set tp->snd_cwnd.

Verdict: Not Vulnerable

Reviewed region:
[net/ipv4/tcp_input.c]
```c
static void tcp_cwnd_reduction(struct sock *sk, const int prior_unsacked,
				       int fast_rexmit, int flag)
{
	struct tcp_sock *tp = tcp_sk(sk);
	int sndcnt = 0;
	int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
	int newly_acked_sacked = prior_unsacked -
				 (tp->packets_out - tp->sacked_out);

	if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd))
		return;

	tp->prr_delivered += newly_acked_sacked;
	if (delta < 0) {
		u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered +
			       tp->prior_cwnd - 1;
		sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
	} else if ((flag & FLAG_RETRANS_DATA_ACKED) &&
		   !(flag & FLAG_LOST_RETRANS)) {
		sndcnt = min_t(int, delta,
			       max_t(int, tp->prr_delivered - tp->prr_out,
				     newly_acked_sacked) + 1);
	} else {
		sndcnt = min(delta, newly_acked_sacked);
	}
	sndcnt = max(sndcnt, (fast_rexmit ? 1 : 0));
	tp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt;
}
```

Why it is not vulnerable: The division by tp->prior_cwnd in the delta < 0 branch (div_u64(dividend, tp->prior_cwnd)) is protected by an early return guard at the function entry: 'if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd)) return;'. The short-circuit evaluation of the || operator ensures that if tp->prior_cwnd is zero, the function returns before reaching the division operation. This guard is evaluated before any code path that uses tp->prior_cwnd as a divisor.

Security invariants:
- tp->prior_cwnd must be non-zero before div_u64(dividend, tp->prior_cwnd) is reached. This is enforced by the guard 'if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd)) return;' which uses short-circuit || evaluation, guaranteeing early return when tp->prior_cwnd is zero.
- The short-circuit evaluation of || ensures the WARN_ON_ONCE(!tp->prior_cwnd) check is always evaluated before any division by tp->prior_cwnd occurs, since the return statement immediately follows the guard.
- tcp_init_cwnd_reduction sets tp->prior_cwnd = tp->snd_cwnd, establishing that prior_cwnd reflects the congestion window value at the time congestion control state is initialized.

Invariant verification:
- Division by zero prevention for tp->prior_cwnd: holds=true. Evidence: The guard 'if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd)) return;' at the function entry ensures tp->prior_cwnd != 0 before any subsequent code executes, including the div_u64(dividend, tp->prior_cwnd) call in the delta < 0 branch. The || operator's short-circuit semantics guarantee the check is evaluated and the return is taken if prior_cwnd is zero.
- All code paths reaching division pass the non-zero guard: holds=true. Evidence: The function has a single entry point and the guard is placed before all computational branches. The delta < 0 branch containing div_u64(dividend, tp->prior_cwnd) can only be reached after the guard has confirmed tp->prior_cwnd is non-zero.

Residual risk notes: The safety of the division relies on tp->prior_cwnd remaining non-zero between the guard check and the div_u64 call. If concurrent modification of tp->prior_cwnd were possible, a TOCTOU issue could arise. However, the surrounding TCP input processing context typically holds the socket lock (sk_lock), serializing access to these fields. Without visibility into the locking discipline in the callers, this assumption cannot be fully verified from the supplied context alone.

No concrete vulnerability impact is demonstrated in the supplied code and context.

Looking at this `tcp_cwnd_reduction` function, I'll trace the control flow and data flow to identify potential vulnerabilities.

## Analysis

### Function Purpose
This function implements TCP's Proportional Rate Reduction (PRR) algorithm per RFC 6675, calculating how many packets can be sent during loss recovery to adjust the congestion window (`snd_cwnd`).

### Key Data Flow Analysis

**Inputs to the function:**
- `prior_unsacked`: packets unacked at loss detection
- `fast_rexmit`, `flag`: control flow flags
- `tp->prior_cwnd`, `tp->prr_delivered`, `tp->prr_out`: recovery state
- `tp->snd_ssthresh`: congestion threshold

### Guard Analysis

1. **Early return on line 2-3:**
   ```c
   if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd))
       return;
   ```
   - Prevents division by zero when `prior_cwnd == 0`
   - Prevents processing when no progress is made

2. **Integer arithmetic in the `delta < 0` branch:**
   ```c
   u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered + tp->prior_cwnd - 1;
   sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out;
   ```
   - Uses **u64** for the multiplication, preventing overflow up to ~4×10¹⁹
   - `div_u64` divides by the now-verified non-zero `prior_cwnd`
   - The `-1` in the dividend is per RFC 6675 for conservative rounding

3. **Bounds on sndcnt in the else branches:**
   - `sndcnt = min(delta, newly_acked_sacked)` — bounded by ssthresh delta
   - `sndcnt = min_t(int, delta, max_t(int, ..., newly_acked_sacked) + 1)` — bounded
   - `sndcnt = max(sndcnt, (fast_rexmit ? 1 : 0))` — ensures at least 1 on fast rexmit

4. **snd_cwnd calculation:**
   ```c
   tp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt;
   ```
   - `tcp_packets_in_flight(tp)` returns `tp->packets_out - tcp_left_out(tp) + tp->retrans_out`
   - `sndcnt` is bounded by `snd_ssthresh` and related state variables
   - `snd_ssthresh` is set by `ssthresh()` callback and bounded by `snd_cwnd_clamp`

### Potential Concern Investigated

**Could `delta` underflow?**
```c
int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp);
```
If `tcp_packets_in_flight > snd_ssthresh`, `delta` becomes negative. However:
- `snd_ssthresh` is set to the *current* cwnd at recovery entry (in `tcp_init_cwnd_reduction`)
- `tcp_packets_in_flight` can temporarily exceed ssthresh due to ACK clocking, but the delta computation handles this via the conservative bound branch
- The result `sndcnt` is always bounded by min/max operations

**Could sndcnt overflow when added to snd_cwnd?**
- `sndcnt` is bounded by `delta` or PRR formula results
- `snd_ssthresh` ≤ `snd_cwnd_clamp` (typically 65535)
- The sum stays within u32 range under normal TCP state constraints

### Verification Against Call Path

The call chain (`tcp_fastretrans_alert` → `tcp_process_loss` → `tcp_try_keep_open` → `tcp_cwnd_reduction`) ensures this runs only during legitimate loss recovery events with properly initialized state.

---

## Verdict: **NOT VULNERABLE**

The function contains appropriate guards:
1. `WARN_ON_ONCE(!tp->prior_cwnd)` prevents division by zero
2. u64 intermediate calculations prevent multiplication overflow
3. All `sndcnt` calculations are bounded by min/max operations constrained by TCP state variables
4. `snd_cwnd` assignment is bounded by the sndcnt calculation logic

The PRR algorithm as implemented correctly limits sending rate during recovery, and the arithmetic is protected against overflow. No concrete attack path exists that could exploit these calculations to produce a dangerous `snd_cwnd` value.

```json
{
  "vulnerable": false,
  "cwe": null,
  "severity": null,
  "reviewed_region": "net/ipv4/tcp_input.c tcp_cwnd_reduction function (lines ~2472-2499)",
  "vulnerable_region": null,
  "root_cause": null,
  "exploitability": "Not exploitable",
  "attack_preconditions": [],
  "impact": "None - function operates correctly within TCP congestion control invariants",
  "non_vulnerable_reason": "The function contains multiple protective guards: (1) WARN_ON_ONCE(!tp->prior_cwnd) guard prevents division by zero on line 2-3; (2) u64 intermediate type for multiplication ((u64)tp->snd_ssthresh * tp->prr_delivered) prevents overflow in the conservative branch; (3) all sndcnt branches are bounded by min/max operations that constrain the output to valid TCP state ranges; (4) sndcnt is bounded by delta or newly_acked_sacked, both of which derive from valid TCP packet accounting; (5) the final snd_cwnd assignment is the sum of in-flight packets plus the bounded sndcnt value",
  "security_invariants": [
    "tp->prior_cwnd != 0 when entering the computation (guarded by WARN_ON_ONCE)",
    "sndcnt is bounded by snd_ssthresh - packets_in_flight or newly_acked_sacked",
    "snd_cwnd is set to packets_in_flight + bounded sndcnt, never exceeding ssthresh-based bounds",
    "All arithmetic uses appropriate integer sizes (u64 for intermediate dividend)"
  ],
  "invariant_verification": "Guard (1) verified by explicit WARN_ON_ONCE check at line 3. Invariant (2) verified by min() operations at lines 17, 21, and max() at line 23. Invariant (3) holds because sndcnt computation in delta<0 branch uses div_u64(dividend, prior_cwnd) which produces result ≤ (snd_ssthresh * prr_delivered)/prior_cwnd ≈ snd_ssthresh. Invariant (4) verified by explicit cast to u64 for multiplication.",
  "residual_risk_notes": "No residual risk identified within this function. The PRR algorithm per RFC 6675 is correctly implemented with appropriate overflow protection. The function is only called from defined call paths (tcp_try_keep_open via loss recovery state machine) where tp->prior_cwnd is properly initialized in tcp_init_cwnd_reduction.",
  "call_path": "tcp_fastretrans_alert (net/ipv4/tcp_input.c) → tcp_process_loss (net/ipv4/tcp_input.c) → tcp_try_keep_open (net/ipv4/tcp_input.c) → tcp_cwnd_reduction (net/ipv4/tcp_input.c)"
}
```


Audit the following candidate code to determine whether it presents a real vulnerability.
This sample may come from a noisy retrieval or transformation stage, so reason from the supplied code and context rather than assuming the label.

Repository: git.kernel.org/pub/scm/linux/kernel/git/stable/linux
Language: C
File: drivers/usb/typec/altmodes/displayport.c
Function: pin_assignment_show

Call path: pin_assignment_show (drivers/usb/typec/altmodes/displayport.c) → get_count_order (include/linux/bitops.h) → get_current_pin_assignments (drivers/usb/typec/altmodes/displayport.c) → DP_CAP_PIN_ASSIGN_UFP_D (include/linux/usb/typec_dp.h) → DP_CAP_PIN_ASSIGN_DFP_D (include/linux/usb/typec_dp.h)

### Primary Function

```c
static ssize_t pin_assignment_show(struct device *dev,
				   struct device_attribute *attr, char *buf)
{
	struct dp_altmode *dp = dev_get_drvdata(dev);
	u8 assignments;
	int len = 0;
	u8 cur;
	int i;

	mutex_lock(&dp->lock);

	cur = get_count_order(DP_CONF_GET_PIN_ASSIGN(dp->data.conf));

	assignments = get_current_pin_assignments(dp);

	for (i = 0; assignments && i < DP_PIN_ASSIGN_MAX; assignments >>= 1, i++) {
		if (assignments & 1) {
			if (i == cur)
				len += sprintf(buf + len, "[%s] ",
					       pin_assignments[i]);
			else
				len += sprintf(buf + len, "%s ",
					       pin_assignments[i]);
		}
	}

	mutex_unlock(&dp->lock);

	/* get_current_pin_assignments can return 0 when no matching pin assignments are found */
	if (len == 0)
		len++;

	buf[len - 1] = '\n';
	return len;
}
```

### Cross-File Context

[DP_PIN_ASSIGN_MAX — enum — include/linux/usb/typec_dp.h:52-60]
enum { DP_PIN_ASSIGN_A, /* Not supported after v1.0b */ DP_PIN_ASSIGN_B, /* Not supported after v1.0b */ DP_PIN_ASSIGN_C, DP_PIN_ASSIGN_D, DP_PIN_ASSIGN_E, DP_PIN_ASSIGN_F, /* Not supported after v1.0b */ DP_PIN_ASSIGN_MAX, };

[get_count_order — helper — include/linux/bitops.h:189-195]
```c
static inline int get_count_order(unsigned int count)
{
	if (count == 0)
		return -1;

	return fls(--count);
}
```

[get_current_pin_assignments — helper — drivers/usb/typec/altmodes/displayport.c:439-445]
```c
static u8 get_current_pin_assignments(struct dp_altmode *dp)
{
	if (DP_CONF_CURRENTLY(dp->data.conf) == DP_CONF_DFP_D)
		return DP_CAP_PIN_ASSIGN_DFP_D(dp->alt->vdo);
	else
		return DP_CAP_PIN_ASSIGN_UFP_D(dp->alt->vdo);
}
```

[DP_CAP_PIN_ASSIGN_UFP_D — helper — include/linux/usb/typec_dp.h:77-78]
DP_CAP_PIN_ASSIGN_UFP_D → #define DP_CAP_PIN_ASSIGN_UFP_D(_cap_) ((_cap_ & DP_CAP_RECEPTACLE) ? \ DP_CAP_UFP_D_PIN_ASSIGN(_cap_) : DP_CAP_DFP_D_PIN_ASSIGN(_cap_))  (include/linux/usb/typec_dp.h:77-78)

[DP_CAP_PIN_ASSIGN_DFP_D — helper — include/linux/usb/typec_dp.h:80-81]
DP_CAP_PIN_ASSIGN_DFP_D → #define DP_CAP_PIN_ASSIGN_DFP_D(_cap_) ((_cap_ & DP_CAP_RECEPTACLE) ? \ DP_CAP_DFP_D_PIN_ASSIGN(_cap_) : DP_CAP_UFP_D_PIN_ASSIGN(_cap_))  (include/linux/usb/typec_dp.h:80-81)

[pin_assignments — constant — drivers/usb/typec/altmodes/displayport.c:403-410]
pin_assignments → static const char * const pin_assignments[] = { [DP_PIN_ASSIGN_A] = "A", [DP_PIN_ASSIGN_B] = "B", [DP_PIN_ASSIGN_C] = "C", [DP_PIN_ASSIGN_D] = "D", [DP_PIN_ASSIGN_E] = "E", [DP_PIN_ASSIGN_F] = "F", };  (drivers/usb/typec/altmodes/displayport.c:403-410)

[DP_CONF_GET_PIN_ASSIGN — macro — include/linux/usb/typec_dp.h:107-108 (post), drivers/usb/typec/altmodes/displayport.c:29 (pre)]
DP_CONF_GET_PIN_ASSIGN → #define DP_CONF_GET_PIN_ASSIGN(_conf_) (((_conf_) & GENMASK(15, 8)) >> 8)  (include/linux/usb/typec_dp.h:107-108 (post), drivers/usb/typec/altmodes/displayport.c:29 (pre))

[DP_CAP_UFP_D_PIN_ASSIGN — macro — include/linux/usb/typec_dp.h:69 (pre), include/linux/usb/typec_dp.h:76 (post)]
DP_CAP_UFP_D_PIN_ASSIGN → #define DP_CAP_UFP_D_PIN_ASSIGN(_cap_) (((_cap_) & GENMASK(23, 16)) >> 16)  (include/linux/usb/typec_dp.h:69 (pre), include/linux/usb/typec_dp.h:76 (post))

[DP_CAP_DFP_D_PIN_ASSIGN — macro — include/linux/usb/typec_dp.h:68 (pre), include/linux/usb/typec_dp.h:75 (post)]
DP_CAP_DFP_D_PIN_ASSIGN → #define DP_CAP_DFP_D_PIN_ASSIGN(_cap_) (((_cap_) & GENMASK(15, 8)) >> 8)  (include/linux/usb/typec_dp.h:68 (pre), include/linux/usb/typec_dp.h:75 (post))

Control flow: The function acquires dp->lock, computes cur via get_count_order on the extracted pin assignment from dp->data.conf, and obtains assignments bitmask from get_current_pin_assignments. It then iterates through the bits of assignments using a for loop with condition 'assignments && i < DP_PIN_ASSIGN_MAX'. Inside the loop, when the current bit is set (assignments & 1), it appends either '[X] ' or 'X ' to buf using sprintf, where X is pin_assignments[i]. After the loop, the mutex is released. If no assignments were found (len == 0), len is incremented. A newline is placed at buf[len-1] and len is returned.

Data flow: dp->data.conf flows through DP_CONF_GET_PIN_ASSIGN macro to extract bits 8-15, then through get_count_order to produce cur. dp->alt->vdo flows through DP_CAP_PIN_ASSIGN_DFP_D or DP_CAP_PIN_ASSIGN_UFP_D macros (which extract bits 16-23) to produce assignments. The loop variable i iterates from 0 upward, bounded by DP_PIN_ASSIGN_MAX, and is used to index into pin_assignments[]. sprintf accumulates output into buf using buf + len as the write offset.

Verdict: Not Vulnerable

Reviewed region:
[drivers/usb/typec/altmodes/displayport.c]
```c
static ssize_t pin_assignment_show(struct device *dev,
				   struct device_attribute *attr, char *buf)
{
	struct dp_altmode *dp = dev_get_drvdata(dev);
	u8 assignments;
	int len = 0;
	u8 cur;
	int i;

	mutex_lock(&dp->lock);

	cur = get_count_order(DP_CONF_GET_PIN_ASSIGN(dp->data.conf));

	assignments = get_current_pin_assignments(dp);

	for (i = 0; assignments && i < DP_PIN_ASSIGN_MAX; assignments >>= 1, i++) {
		if (assignments & 1) {
			if (i == cur)
				len += sprintf(buf + len, "[%s] ",
					       pin_assignments[i]);
			else
				len += sprintf(buf + len, "%s ",
					       pin_assignments[i]);
		}
	}

	mutex_unlock(&dp->lock);

	/* get_current_pin_assignments can return 0 when no matching pin assignments are found */
	if (len == 0)
		len++;

	buf[len - 1] = '\n';
	return len;
}
```

Why it is not vulnerable: The array access pin_assignments[i] in the loop is safely bounded. The loop condition 'assignments && i < DP_PIN_ASSIGN_MAX' ensures i never reaches DP_PIN_ASSIGN_MAX. Given the enum definition where DP_PIN_ASSIGN_MAX is the sentinel after DP_PIN_ASSIGN_F, DP_PIN_ASSIGN_MAX equals 7. The pin_assignments array has 7 elements (indices 0-6, corresponding to DP_PIN_ASSIGN_A through DP_PIN_ASSIGN_F). Therefore i is always in range [0, 6] when pin_assignments[i] is accessed, which is within valid array bounds.

Security invariants:
- The loop index i must remain strictly less than DP_PIN_ASSIGN_MAX to prevent out-of-bounds access to pin_assignments[i]. This is enforced by the loop condition 'i < DP_PIN_ASSIGN_MAX'.
- The pin_assignments array must have at least DP_PIN_ASSIGN_MAX elements. The array is initialized with explicit indices [DP_PIN_ASSIGN_A] through [DP_PIN_ASSIGN_F], providing exactly DP_PIN_ASSIGN_MAX valid indices.
- Concurrent access to dp->data.conf and dp->alt->vdo must be serialized. This is enforced by mutex_lock(&dp->lock) before reads and mutex_unlock(&dp->lock) after.
- The sprintf write offset (buf + len) must not overflow the buffer. The buffer is provided by the sysfs infrastructure with a bounded size (typically PAGE_SIZE), and the loop runs at most DP_PIN_ASSIGN_MAX iterations with bounded output per iteration.

Invariant verification:
- Loop index bounds for pin_assignments array access: holds=true. Evidence: The for loop condition 'for (i = 0; assignments && i < DP_PIN_ASSIGN_MAX; assignments >>= 1, i++)' ensures i < DP_PIN_ASSIGN_MAX. The enum defines DP_PIN_ASSIGN_MAX as the value after DP_PIN_ASSIGN_F (index 6), so DP_PIN_ASSIGN_MAX = 7. The pin_assignments array has elements at indices 0-6, matching valid i values of 0 through 6.
- Mutex protection for shared state reads: holds=true. Evidence: mutex_lock(&dp->lock) is called before reading dp->data.conf and calling get_current_pin_assignments (which reads dp->alt->vdo). mutex_unlock(&dp->lock) is called after these reads complete, ensuring serialization.
- get_count_order handles zero input safely: holds=true. Evidence: get_count_order returns -1 when count == 0. This means cur can be -1, but cur is only used in the comparison 'i == cur'. Since i starts at 0 and is always non-negative in the loop, the comparison simply never matches when cur is -1, which is semantically correct.

Residual risk notes: The sprintf calls accumulate into buf without explicit bounds checking against the actual buffer size. While sysfs attributes provide a buffer of PAGE_SIZE and the loop is bounded to at most 7 iterations with small format strings (max ~7 bytes per iteration plus 1 byte for newline), the absence of an explicit scnprintf or explicit buffer size check means the safety of the write relies on the sysfs infrastructure guarantee. Additionally, if len were to reach 0 unexpectedly before the newline assignment, buf[len-1] = '\n' would write to buf[-1], but the code handles this with 'if (len == 0) len++' which ensures len is at least 1 before the newline write.

Looking at this code, I need to trace the data flow and identify any potential security issues.

## Analysis of `pin_assignment_show`

### Function Purpose
This is a sysfs show function that displays DisplayPort pin assignments, highlighting the currently selected one in brackets.

### Key Data Flow

**Input sources:**
- `dp->data.conf`: Configuration register (extracted via `DP_CONF_GET_PIN_ASSIGN`)
- `dp->alt->vdo`: VDO (Vendor Defined Message) register

**Key computations:**
1. `cur = get_count_order(DP_CONF_GET_PIN_ASSIGN(dp->data.conf))` — computes index of selected pin assignment
2. `assignments = get_current_pin_assignments(dp)` — bitmask of available assignments
3. Loop iterates through bits 0-5 of `assignments`, printing corresponding pin names

### Potential Issues

**1. Silent truncation of pin assignments:**
`assignments` is a `u8` (8 bits), but `DP_PIN_ASSIGN_MAX` is 6. If bits 6 or 7 are set in the VDO register, they are silently ignored:
```c
for (i = 0; assignments && i < DP_PIN_ASSIGN_MAX; assignments >>= 1, i++)
```
Bits beyond position 5 are never accessed.

**2. Mismatch between selected and displayed:**
`get_count_order()` can return values 0-7. For `cur > 5`:
- The loop never reaches index `cur`, so no assignment gets bracketed
- If `assignments` contains bits 6-7 but not 0-5, the bracketed assignment references a non-existent index
- The selected configuration doesn't match any printed assignment

**3. Out-of-bounds write when `len == 0`:**
```c
if (len == 0)
    len++;

buf[len - 1] = '\n';
```
If `get_current_pin_assignments` returns 0 and no bits are printed, `len` is incremented to 1 and a newline is unconditionally written to `buf[0]`. This is safe only if the caller provides at least 1 byte of buffer space.

**4. No buffer overflow in sprintf chain:**
The loop iterates at most 6 times with each iteration printing at most ~5 characters, totaling <40 bytes. Sysfs buffers are typically `PAGE_SIZE` (4096 bytes), so this path is not exploitable.

### Verdict

**NOT VULNERABLE** in the traditional sense.

The code does not exhibit classic security vulnerabilities (buffer overflows, use-after-free, TOCTOU). The bounds checking `i < DP_PIN_ASSIGN_MAX` in the loop condition prevents out-of-bounds array access into `pin_assignments[]`. The `sprintf` calls cannot overflow a properly-sized sysfs buffer.

**Residual concern:** The logic allows `cur` from `get_count_order()` to exceed the valid array index range (0-5), but this results in silently ignoring some assignments rather than memory corruption. This is a correctness/specification compliance issue rather than a security vulnerability given the supplied context.

```json
{
  "vulnerable": false,
  "cwe": null,
  "severity": null,
  "reviewed_region": "drivers/usb/typec/altmodes/displayport.c:386-418 (pin_assignment_show function)",
  "vulnerable_region": null,
  "root_cause": null,
  "exploitability": "Not exploitable - no memory corruption or security boundary violation exists in the supplied code.",
  "attack_preconditions": null,
  "impact": null,
  "non_vulnerable_reason": "The loop bounds check `i < DP_PIN_ASSIGN_MAX` (value 6) prevents out-of-bounds array access to `pin_assignments[]`. The sprintf chain writes at most ~40 bytes to the sysfs buffer, which is guaranteed to be PAGE_SIZE (4096 bytes). The unconditional newline write when `len == 0` is safe as it writes only to `buf[0]` which the caller must provide. The mutex protects against concurrent modification.",
  "security_invariants": [
    "Loop index `i` is bounded by `DP_PIN_ASSIGN_MAX` (6), preventing out-of-bounds access to `pin_assignments[]`",
    "Total bytes written via sprintf chain is bounded by loop iterations (max 6) times max string length (~5 bytes), well within PAGE_SIZE",
    "Mutex lock held during entire data access and buffer population prevents race conditions",
    "The `len == 0` fallback case only writes one byte (newline) to `buf[0]`, which is always valid if caller provides at least 1 byte"
  ],
  "invariant_verification": "The array `pin_assignments` has 6 entries (indices 0-5 for A through F). The loop iterates `i` from 0 while `i < DP_PIN_ASSIGN_MAX` (6), so `pin_assignments[i]` is always accessed with valid indices 0-5. The buffer write at `buf[len - 1] = '\n'` executes only after len is guaranteed to be at least 1 due to the preceding increment logic.",
  "residual_risk_notes": "There is a minor correctness concern: `get_count_order()` can return values 0-7, but the loop only displays indices 0-5. If the configured pin assignment (bits 8-15 of conf) refers to an index > 5, no bracketing occurs. Additionally, if the VDO contains set bits in positions 6-7, they are silently ignored. However, these are specification compliance or display completeness issues, not security vulnerabilities.",
  "call_path": "pin_assignment_show → get_count_order → get_current_pin_assignments → DP_CAP_PIN_ASSIGN_UFP_D/DP_CAP_PIN_ASSIGN_DFP_D"
}
```

The array `pin_assignments` has 6 entries (indices 0-5 for A through F). The loop iterates `i` from 0 while `i < DP_PIN_ASSIGN_MAX` (6), so `pin_assignments[i]` is always accessed with valid indices 0-5. The buffer write at `buf[len - 1] = '
'` executes only after len is guaranteed to be at least 1 due to the preceding increment logic.


Audit the following candidate code to determine whether it presents a real vulnerability.
This sample may come from a noisy retrieval or transformation stage, so reason from the supplied code and context rather than assuming the label.

Repository: git.kernel.org/pub/scm/linux/kernel/git/stable/linux
Language: C
File: kernel/sched/fair.c
Function: reweight_eevdf

Call path: reweight_eevdf (kernel/sched/fair.c) → entity_eligible (kernel/sched/fair.c) → pick_eevdf (kernel/sched/fair.c) → update_entity_lag (kernel/sched/fair.c) → calc_delta_fair (kernel/sched/fair.c) → avg_vruntime (kernel/sched/fair.c)

### Primary Function

```c
static void reweight_eevdf(struct sched_entity *se, u64 avruntime,
			   unsigned long weight)
{
	unsigned long old_weight = se->load.weight;
	s64 vlag, vslice;

	/*
	 * VRUNTIME
	 * ========
	 *
	 * COROLLARY #1: The virtual runtime of the entity needs to be
	 * adjusted if re-weight at !0-lag point.
	 *
	 * Proof: For contradiction assume this is not true, so we can
	 * re-weight without changing vruntime at !0-lag point.
	 *
	 *             Weight	VRuntime   Avg-VRuntime
	 *     before    w          v            V
	 *      after    w'         v'           V'
	 *
	 * Since lag needs to be preserved through re-weight:
	 *
	 *	lag = (V - v)*w = (V'- v')*w', where v = v'
	 *	==>	V' = (V - v)*w/w' + v		(1)
	 *
	 * Let W be the total weight of the entities before reweight,
	 * since V' is the new weighted average of entities:
	 *
	 *	V' = (WV + w'v - wv) / (W + w' - w)	(2)
	 *
	 * by using (1) & (2) we obtain:
	 *
	 *	(WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v
	 *	==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v
	 *	==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v
	 *	==>	(V - v)*W/(W + w' - w) = (V - v)*w/w' (3)
	 *
	 * Since we are doing at !0-lag point which means V != v, we
	 * can simplify (3):
	 *
	 *	==>	W / (W + w' - w) = w / w'
	 *	==>	Ww' = Ww + ww' - ww
	 *	==>	W * (w' - w) = w * (w' - w)
	 *	==>	W = w	(re-weight indicates w' != w)
	 *
	 * So the cfs_rq contains only one entity, hence vruntime of
	 * the entity @v should always equal to the cfs_rq's weighted
	 * average vruntime @V, which means we will always re-weight
	 * at 0-lag point, thus breach assumption. Proof completed.
	 *
	 *
	 * COROLLARY #2: Re-weight does NOT affect weighted average
	 * vruntime of all the entities.
	 *
	 * Proof: According to corollary #1, Eq. (1) should be:
	 *
	 *	(V - v)*w = (V' - v')*w'
	 *	==>	    v' = V' - (V - v)*w/w'		(4)
	 *
	 * According to the weighted average formula, we have:
	 *
	 *	V' = (WV - wv + w'v') / (W - w + w')
	 *	   = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w')
	 *	   = (WV - wv + w'V' - Vw + wv) / (W - w + w')
	 *	   = (WV + w'V' - Vw) / (W - w + w')
	 *
	 *	==>	V'*(W - w + w') = WV + w'V' - Vw
	 *	==>	V' * (W - w) = (W - w) * V	(5)
	 *
	 * If the entity is the only one in the cfs_rq, then reweight
	 * always occurs at 0-lag point, so V won't change. Or else
	 * there are other entities, hence W != w, then Eq. (5) turns
	 * into V' = V. So V won't change in either case, proof done.
	 *
	 *
	 * So according to corollary #1 & #2, the effect of re-weight
	 * on vruntime should be:
	 *
	 *	v' = V' - (V - v) * w / w'		(4)
	 *	   = V  - (V - v) * w / w'
	 *	   = V  - vl * w / w'
	 *	   = V  - vl'
	 */
	if (avruntime != se->vruntime) {
		vlag = entity_lag(avruntime, se);
		vlag = div_s64(vlag * old_weight, weight);
		se->vruntime = avruntime - vlag;
	}

	/*
	 * DEADLINE
	 * ========
	 *
	 * When the weight changes, the virtual time slope changes and
	 * we should adjust the relative virtual deadline accordingly.
	 *
	 *	d' = v' + (d - v)*w/w'
	 *	   = V' - (V - v)*w/w' + (d - v)*w/w'
	 *	   = V  - (V - v)*w/w' + (d - v)*w/w'
	 *	   = V  + (d - V)*w/w'
	 */
	vslice = (s64)(se->deadline - avruntime);
	vslice = div_s64(vslice * old_weight, weight);
	se->deadline = avruntime + vslice;
}
```

### Cross-File Context

[entity_lag — function — kernel/sched/fair.c:699]
```c
static s64 entity_lag(u64 avruntime, struct sched_entity *se)
{
	s64 vlag, limit;

	vlag = avruntime - se->vruntime;
	limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);

	return clamp(vlag, -limit, limit);
}
```

[update_entity_lag — helper — kernel/sched/fair.c:709]
```c
static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
	SCHED_WARN_ON(!se->on_rq);

	se->vlag = entity_lag(avg_vruntime(cfs_rq), se);
}
```

[calc_delta_fair — helper — kernel/sched/fair.c:296]
```c
static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
{
	if (unlikely(se->load.weight != NICE_0_LOAD))
		delta = __calc_delta(delta, NICE_0_LOAD, &se->load);

	return delta;
}
```

[avg_vruntime — helper — kernel/sched/fair.c:665]
```c
u64 avg_vruntime(struct cfs_rq *cfs_rq)
{
	struct sched_entity *curr = cfs_rq->curr;
	s64 avg = cfs_rq->avg_vruntime;
	long load = cfs_rq->avg_load;

	if (curr && curr->on_rq) {
		unsigned long weight = scale_load_down(curr->load.weight);

		avg += entity_key(cfs_rq, curr) * weight;
		load += weight;
	}

	if (load) {
		/* sign flips effective floor / ceil */
		if (avg < 0)
			avg -= (load - 1);
		avg = div_s64(avg, load);
	}

	return cfs_rq->min_vruntime + avg;
}
```

[entity_eligible — callee — kernel/sched/fair.c:749]
```c
int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
{
	return vruntime_eligible(cfs_rq, se->vruntime);
}
```

[pick_eevdf — callee — kernel/sched/fair.c:884]
```c
static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
{
	struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
	struct sched_entity *se = __pick_first_entity(cfs_rq);
	struct sched_entity *curr = cfs_rq->curr;
	struct sched_entity *best = NULL;

	if (cfs_rq->nr_running == 1)
		return curr && curr->on_rq ? curr : se;

	if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
		curr = NULL;

	if (sched_feat(RUN_TO_PARITY) && curr && curr->vlag == curr->deadline)
		return curr;

	if (se && entity_eligible(cfs_rq, se)) {
		best = se;
		goto found;
	}

	while (node) {
		struct rb_node *left = node->rb_left;

		if (left && vruntime_eligible(cfs_rq,
					__node_2_se(left)->min_vruntime)) {
			node = left;
			continue;
		}

		se = __node_2_se(node);

		if (entity_eligible(cfs_rq, se)) {
			best = se;
			break;
		}

		node = node->rb_right;
	}
found:
	if (!best || (curr && entity_before(curr, best)))
		best = curr;

	return best;
}
```

[sched_entity — struct — include/linux/sched.h:536]
```c
struct sched_entity {
	/* For load-balancing: */
	struct load_weight		load;
	struct rb_node			run_node;
	u64				deadline;
	u64				min_vruntime;

	struct list_head		group_node;
	unsigned int			on_rq;

	u64				exec_start;
	u64			sum_exec_runtime;
	u64			prev_sum_exec_runtime;
	u64			vruntime;
	s64			vlag;
	u64			slice;

	u64			nr_migrations;

#ifdef CONFIG_FAIR_GROUP_SCHED
	int			depth;
	struct sched_entity	*parent;
	/* rq on which this entity is (to be) queued: */
	struct cfs_rq		*cfs_rq;
	/* rq "owned" by this entity/group: */
	struct cfs_rq		*my_q;
	/* cached value of my_q->h_nr_running */
	unsigned long		-runnable_weight;
#endif

#ifdef CONFIG_SMP
	/*
	 * Per entity load average tracking.
	 *
	 * Put into separate cache line so it does not
	 * collide with read-mostly values above.
	 */
	struct sched_avg	avg;
#endif
};
```

[clamp — macro — linux/kernel.h]
clamp → #define clamp(val, lo, hi) min_t(typeof(val), max_t(typeof(val), val, lo), hi)  (linux/kernel.h)

[TICK_NSEC — constant — linux/jiffies.h]
TICK_NSEC → (NSEC_PER_SEC / HZ)  (linux/jiffies.h)

Control flow: The reweight_eevdf function has two sequential branches: (1) VRUNTIME adjustment block that executes only when avruntime != se->vruntime, computing entity_lag, scaling by weight ratio via div_s64, and updating se->vruntime; (2) DEADLINE adjustment block that unconditionally computes vslice from se->deadline and avruntime, scales by weight ratio via div_s64, and updates se->deadline. There are no error paths, cleanup paths, or early returns—both sections execute linearly when their conditions are met.

Data flow: Input: se (sched_entity pointer), avruntime (u64 weighted average vruntime), weight (unsigned long new weight). Intermediate: old_weight extracted from se->load.weight. In the VRUNTIME branch, entity_lag(avruntime, se) returns a clamped lag value via entity_lag() which subtracts se->vruntime from avruntime and clamps to [-limit, limit] where limit is calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se). The clamped vlag is then multiplied by old_weight and divided by weight using div_s64, producing a scaled lag. se->vruntime is set to avruntime - scaled_vlag. In the DEADLINE branch, vslice is computed as (se->deadline - avruntime) cast to s64, then scaled by old_weight/weight via div_s64. se->deadline is set to avruntime + scaled_vslice. All output writes modify fields within se.

Verdict: Not Vulnerable

Reviewed region:
[kernel/sched/fair.c]
```c
static void reweight_eevdf(struct sched_entity *se, u64 avruntime,
			   unsigned long weight)
{
	unsigned long old_weight = se->load.weight;
	s64 vlag, vslice;

	/*
	 * VRUNTIME
	 * ========
	 *
	 * COROLLARY #1: The virtual runtime of the entity needs to be
	 * adjusted if re-weight at !0-lag point.
	 *
	 * Proof: For contradiction assume this is not true, so we can
	 * re-weight without changing vruntime at !0-lag point.
	 *
	 *             Weight	VRuntime   Avg-VRuntime
	 *     before    w          v            V
	 *      after    w'         v'           V'
	 *
	 * Since lag needs to be preserved through re-weight:
	 *
	 *	lag = (V - v)*w = (V'- v')*w', where v = v'
	 *	==>	V' = (V - v)*w/w' + v		(1)
	 *
	 * Let W be the total weight of the entities before reweight,
	 * since V' is the new weighted average of entities:
	 *
	 *	V' = (WV + w'v - wv) / (W + w' - w)	(2)
	 *
	 * by using (1) & (2) we obtain:
	 *
	 *	(WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v
	 *	==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v
	 *	==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v
	 *	==>	(V - v)*W/(W + w' - w) = (V - v)*w/w' (3)
	 *
	 * Since we are doing at !0-lag point which means V != v, we
	 * can simplify (3):
	 *
	 *	==>	W / (W + w' - w) = w / w'
	 *	==>	Ww' = Ww + ww' - ww
	 *	==>	W * (w' - w) = w * (w' - w)
	 *	==>	W = w	(re-weight indicates w' != w)
	 *
	 * So the cfs_rq contains only one entity, hence vruntime of
	 * the entity @v should always equal to the cfs_rq's weighted
	 * average vruntime @V, which means we will always re-weight
	 * at 0-lag point, thus breach assumption. Proof completed.
	 *
	 *
	 * COROLLARY #2: Re-weight does NOT affect weighted average
	 * vruntime of all the entities.
	 *
	 * Proof: According to corollary #1, Eq. (1) should be:
	 *
	 *	(V - v)*w = (V' - v')*w'
	 *	==>	    v' = V' - (V - v)*w/w'		(4)
	 *
	 * According to the weighted average formula, we have:
	 *
	 *	V' = (WV - wv + w'v') / (W - w + w')
	 *	   = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w')
	 *	   = (WV - wv + w'V' - Vw + wv) / (W - w + w')
	 *	   = (WV + w'V' - Vw) / (W - w + w')
	 *
	 *	==>	V'*(W - w + w') = WV + w'V' - Vw
	 *	==>	V' * (W - w) = (W - w) * V	(5)
	 *
	 * If the entity is the only one in the cfs_rq, then reweight
	 * always occurs at 0-lag point, so V won't change. Or else
	 * there are other entities, hence W != w, then Eq. (5) turns
	 * into V' = V. So V won't change in either case, proof done.
	 *
	 *
	 * So according to corollary #1 & #2, the effect of re-weight
	 * on vruntime should be:
	 *
	 *	v' = V' - (V - v) * w / w'		(4)
	 *	   = V  - (V - v) * w / w'
	 *	   = V  - vl * w / w'
	 *	   = V  - vl'
	 */
	if (avruntime != se->vruntime) {
		vlag = entity_lag(avruntime, se);
		vlag = div_s64(vlag * old_weight, weight);
		se->vruntime = avruntime - vlag;
	}

	/*
	 * DEADLINE
	 * ========
	 *
	 * When the weight changes, the virtual time slope changes and
	 * we should adjust the relative virtual deadline accordingly.
	 *
	 *	d' = v' + (d - v)*w/w'
	 *	   = V' - (V - v)*w/w' + (d - v)*w/w'
	 *	   = V  - (V - v)*w/w' + (d - v)*w/w'
	 *	   = V  + (d - V)*w/w'
	 */
	vslice = (s64)(se->deadline - avruntime);
	vslice = div_s64(vslice * old_weight, weight);
	se->deadline = avruntime + vslice;
}
```

Why it is not vulnerable: The critical operation vlag * old_weight in the VRUNTIME branch cannot overflow because vlag is clamped by entity_lag() to [-limit, limit] where limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se). Since entity_lag() uses clamp() with a bounded limit derived from the scheduling quantum (slice and TICK_NSEC), the intermediate product vlag * old_weight remains well within s64 range. The div_s64() function safely handles division including zero-divisor edge cases. Similarly, vslice * old_weight in the DEADLINE branch uses a time difference that is bounded by reasonable scheduling deadlines, and div_s64() provides safe signed division semantics.

Security invariants:
- vlag must be bounded before multiplication by old_weight; enforced by entity_lag() which returns clamp(vlag, -limit, limit) where limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se)
- Division by weight must not cause division-by-zero or undefined behavior; enforced by div_s64() which checks for zero divisor and returns a safe fallback value
- The signed arithmetic in vlag = div_s64(vlag * old_weight, weight) must not overflow; enforced by the clamping invariant limiting vlag magnitude and old_weight being bounded by the kernel weight scale
- The signed cast (s64)(se->deadline - avruntime) must represent a valid time difference; enforced by deadline and avruntime both being u64 nanosecond timestamps from the same scheduling domain

Invariant verification:
- vlag clamping before scaling multiplication: holds=true. Evidence: entity_lag() computes vlag = avruntime - se->vruntime, then limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se), then returns clamp(vlag, -limit, limit). This clamped result is passed to reweight_eevdf which multiplies it by old_weight in div_s64(vlag * old_weight, weight).
- Safe signed division with zero-divisor protection: holds=true. Evidence: Both vlag and vslice scaling use div_s64() for division by weight. div_s64() is a kernel utility that checks for zero divisors and returns a defined fallback, preventing division-by-zero or undefined behavior.
- Bounded intermediate product magnitude: holds=true. Evidence: Since vlag is clamped to [-limit, limit] and old_weight is an unsigned long bounded by MAX_WEIGHT (1024 in kernel scheduler), the product vlag * old_weight fits within s64 (±2^63). The limit itself is derived from TICK_NSEC and se->slice, both bounded time values.
- vslice computation uses valid time representation: holds=true. Evidence: vslice = (s64)(se->deadline - avruntime) where both se->deadline and avruntime are u64 nanosecond timestamps. The subtraction produces a reasonable time difference that, when scaled by weight ratio, fits within s64 range for normal scheduling parameters.

Residual risk notes: The vslice calculation in the DEADLINE branch does not apply explicit clamping like the vlag path. While vslice represents a bounded scheduling deadline difference in practice, an unusually large deadline value combined with a large old_weight could theoretically approach s64 limits. However, se->deadline is set by the scheduler using avruntime + vslice patterns that keep values in reasonable ranges, and div_s64 provides overflow-safe division semantics. The weight parameter is not validated for zero at the call site, but div_s64 handles this defensively.

Looking at this `reweight_eevdf` function, I need to trace the data flow through the call chain and analyze whether the arithmetic operations can produce exploitable values.

## Analysis

### Key Code Paths

**1. vruntime adjustment:**
```c
if (avruntime != se->vruntime) {
    vlag = entity_lag(avruntime, se);        // Clamped to [-limit, limit]
    vlag = div_s64(vlag * old_weight, weight); // NO BOUNDS CHECK
    se->vruntime = avruntime - vlag;
}
```

**2. deadline adjustment:**
```c
vslice = (s64)(se->deadline - avruntime);
vslice = div_s64(vslice * old_weight, weight);  // NO BOUNDS CHECK
se->deadline = avruntime + vslice;
```

### The Clamping Mismatch

`entity_lag` clamps the initial vlag:
```c
return clamp(vlag, -limit, limit);
```
where `limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se)`.

However, in `reweight_eevdf`, **after dividing by weight**, there is **no re-clamping**. The scaled vlag can grow unbounded when `old_weight >> weight`.

### Concrete Example

Assume:
- `avruntime = 10,000,000`
- `se->vruntime = 500,000`
- Initial `vlag = 9,500,000` (not clamped if entity was severely disadvantaged)
- `old_weight = 1048575` (SCHED_IDLE weight)
- `weight = 1024` (SCHED_NORMAL nice=0)

Result:
```
vlag = 9,500,000 * 1048575 / 1024 ≈ 9,709,090
se->vruntime = 10,000,000 - 9,709,090 = 290,910
```

The entity's vruntime becomes extremely small (benefited), allowing it to monopolize CPU time.

### Attack Preconditions

1. An entity's vruntime must significantly lag behind or exceed avg_vruntime
2. A large weight reduction must occur (`old_weight >> weight`)
3. The caller must be able to trigger weight changes (e.g., via `sched_setattr()` with different nice values, or cgroup weight adjustments)

### Impact

- **CPU starvation**: Entities with corrupted vruntime can dominate scheduling
- **Denial of service**: Legitimate tasks may be starved indefinitely
- **Fairness violation**: The core EEVDF property that `deadline >= vruntime` and lag-based fairness guarantees are broken

### Vulnerability Classification

**Integer arithmetic/calculation error with missing bounds check** — the weight-scaling division in `reweight_eevdf` lacks the bounds checking present in the upstream `entity_lag` function, allowing attacker influence over scheduling parameters when weight reduction is combined with vruntime deviation.

The comment block in the function provides the mathematical proof for correct behavior at 0-lag points, but when `V ≠ v` (non-zero lag) and weights change significantly, the implementation fails to constrain the resulting vruntime/deadline values to prevent scheduling corruption.

**Verdict: VULNERABLE** — The lack of post-division clamping allows unbounded growth of `vlag` and `vslice`, enabling corruption of core scheduler state that governs CPU allocation.

```json
{
  "vulnerable": true,
  "cwe": "CWE-190: Integer Overflow or Wraparound",
  "severity": "High",
  "reviewed_region": "kernel/sched/fair.c:reweight_eevdf",
  "vulnerable_region": "Lines 64-67 and 87-88: The vlag and vslice calculations perform weight-scaling division without re-clamping the results to safe bounds, allowing unbounded growth of scheduling parameters.",
  "root_cause": "The entity_lag function clamps vlag to [-limit, limit] for scheduling stability, but after scaling vlag by (old_weight/weight) in reweight_eevdf, there is no re-clamping. When old_weight >> weight (e.g., SCHED_IDLE to SCHED_NORMAL), the scaled vlag and vslice can grow far beyond the intended limit, corrupting vruntime and deadline values.",
  "exploitability": "Medium - Requires privilege (CAP_SYS_NICE or root) to trigger weight changes, but once triggered the calculation error produces deterministic, exploitable scheduler state corruption.",
  "attack_preconditions": "1. An entity must have non-zero lag (avruntime != se->vruntime) where avruntime lags behind or ahead of the entity's vruntime; 2. A large weight reduction must be triggered (old_weight >> weight, e.g., SCHED_IDLE to nice=0); 3. The attacker must have CAP_SYS_NICE capability or root privileges to set scheduling attributes; 4. Integer division truncation toward zero can further amplify the effect.",
  "impact": "1. CPU starvation: Entities with corrupted vruntime can monopolize CPU by appearing perpetually disadvantaged; 2. Fairness violation: Legitimate tasks may be indefinitely deferred; 3. Core EEVDF invariant breach: The lag-based fairness guarantees (deadline >= vruntime relationship) are violated; 4. Potential for sustained denial-of-service against co-scheduled entities.",
  "non_vulnerable_reason": null,
  "security_invariants": "1. vruntime values should be constrained to prevent entities from gaining unfair scheduling advantage; 2. The lag-based fairness (entity_lag) should remain bounded even during weight transitions; 3. Deadline >= vruntime invariant should hold for all entities.",
  "invariant_verification": "The entity_lag function provides bounds checking that is bypassed in reweight_eevdf. The clamping in entity_lag constrains vlag to calc_delta_fair limits, but this protection is removed after the weight-scaling division in reweight_eevdf. The mathematical proof in comments describes correct behavior assuming bounded vlag, but the implementation fails to maintain that bound when weight changes and vruntime differs from avruntime.",
  "residual_risk_notes": "The vulnerability requires CAP_SYS_NICE privilege, limiting exploitation to privileged processes. The exact impact depends on how pick_eevdf and entity_eligible interact with corrupted state - if pick_eevdf's eligibility checks happen on a different cfs_rq than the corrupted entity, exploitation may be prevented. Whether pick_eevdf operates on the same cfs_rq where reweight_eevdf was called requires further call graph analysis.",
  "call_path": "reweight_eevdf → entity_lag → calc_delta_fair → avg_vruntime (via callers of reweight_eevdf)"
}
```


Audit the following candidate code to determine whether it presents a real vulnerability.
This sample may come from a noisy retrieval or transformation stage, so reason from the supplied code and context rather than assuming the label.

Repository: github.com/ImageMagick/ImageMagick
Language: C
File: coders/wpg.c
Function: ExtractPostscript

Call path: ReadWPGImage (coders/wpg.c) → ExtractPostscript (coders/wpg.c) → GetMagicInfo (MagickCore/magic.c) → ReadImage (MagickCore/image.c)

### Primary Function

```c
static Image *ExtractPostscript(Image *image,const ImageInfo *image_info,
  MagickOffsetType PS_Offset,ssize_t PS_Size,ExceptionInfo *exception)
{
  char
    postscript_file[MaxTextExtent];

  const MagicInfo
    *magic_info;

  FILE
    *ps_file;

  ImageInfo
    *clone_info;

  Image
    *image2;

  unsigned char
    magick[2*MaxTextExtent];

  if ((clone_info=CloneImageInfo(image_info)) == NULL)
    return(image);
  clone_info->blob=(void *) NULL;
  clone_info->length=0;

  /* Obtain temporary file */
  (void) AcquireUniqueFilename(postscript_file);
  ps_file=fopen_utf8(postscript_file,"wb");
  if (ps_file == (FILE *) NULL)
    goto FINISH;

  /* Copy postscript to temporary file */
  (void) SeekBlob(image,PS_Offset,SEEK_SET);
  (void) ReadBlob(image, 2*MaxTextExtent, magick);

  (void) SeekBlob(image,PS_Offset,SEEK_SET);
  while(PS_Size-- > 0)
    {
      (void) fputc(ReadBlobByte(image),ps_file);
    }
  (void) fclose(ps_file);

    /* Detect file format - Check magic.mgk configuration file. */
  magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
  if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
  /*     printf("Detected:%s  \n",magic_info->name); */
  if(exception->severity != UndefinedException) goto FINISH_UNL;
  if(magic_info->name == (char *) NULL) goto FINISH_UNL;

  (void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent);

    /* Read nested image */
  /*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
  FormatLocaleString(clone_info->filename,MaxTextExtent,"%s",postscript_file);
  image2=ReadImage(clone_info,exception);

  if (!image2)
    goto FINISH_UNL;

  /*
    Replace current image with new image while copying base image
    attributes.
  */
  (void) CopyMagickString(image2->filename,image->filename,MaxTextExtent);
  (void) CopyMagickString(image2->magick_filename,image->magick_filename,MaxTextExtent);
  (void) CopyMagickString(image2->magick,image->magick,MaxTextExtent);
  image2->depth=image->depth;
  DestroyBlob(image2);
  image2->blob=ReferenceBlob(image->blob);

  if ((image->rows == 0) || (image->columns == 0))
    DeleteImageFromList(&image);

  AppendImageToList(&image,image2);

 FINISH_UNL:
  (void) RelinquishUniqueFileResource(postscript_file);
 FINISH:
  DestroyImageInfo(clone_info);
  return(image);
}
```

### Cross-File Context

[MaxTextExtent — macro — MagickCore/method-attribute.h:80]
MaxTextExtent → MagickPathExtent  (MagickCore/method-attribute.h:80)

[MagickPathExtent — macro — MagickCore/method-attribute.h:79]
MagickPathExtent → 4096  (MagickCore/method-attribute.h:79)

[_MagicInfo — struct — MagickCore/magic.c:82]
```c
struct _MagicInfo
{
  char
    *name;

  unsigned char
    *magic;

  size_t
    length;

  MagickOffsetType
    offset;

  MagickBooleanType
    skip_spaces;

  size_t
    signature;
};
```

[_ImageInfo — struct — MagickCore/image.h:358]
```c
struct _ImageInfo
{
  ...
  char
    magick[MagickPathExtent],    /* image file format (file magick) */
  ...
};
```

[GetMagicInfo — callee — MagickCore/magic.c:303]
```c
MagickExport const MagicInfo *GetMagicInfo(const unsigned char *magic,
  const size_t length,ExceptionInfo *exception)
```

Control flow: ReadWPGImage parses a WPG file and calls ExtractPostscript when encountering embedded PostScript data (record type 0x11). ExtractPostscript creates a temporary file, writes PostScript data to it, uses GetMagicInfo to detect the file format based on magic bytes, then uses strncpy to copy the detected format name into clone_info->magick before calling ReadImage to read the nested image.

Data flow: The magick format name flows from GetMagicInfo (which returns a MagicInfo struct with a name field) through strncpy into clone_info->magick buffer, then to ReadImage which uses clone_info->magick to determine the image format. The vulnerability occurs when the name field is >= 4096 bytes, causing strncpy to not null-terminate the 4096-byte magick buffer.

Verdict: Vulnerable
Vulnerable region:
[coders/wpg.c]
```c
/*     printf("Detected:%s  \n",magic_info->name); */
```
CWE: CWE-189
Severity: MEDIUM

Root cause: The strncpy at line 806 in coders/wpg.c copies at most MaxTextExtent (4096) bytes from magic_info->name into clone_info->magick, which is declared as char magick[MagickPathExtent] (also 4096 bytes). When magic_info->name is exactly MaxTextExtent (4096) bytes or longer, strncpy fills the entire buffer without null-terminating it, because strncpy only guarantees null-termination when the source string is strictly shorter than the specified size.

Exploitability: An attacker can craft a WPG file containing embedded PostScript data with a magic name that is 4096 bytes or longer, triggering the missing null-termination vulnerability when ImageMagick processes the file.

Attack preconditions:
- Attacker can provide a specially crafted WPG file to ImageMagick for processing
- The WPG file must contain embedded PostScript data with a detected magic format name >= 4096 characters

Likely impact: An attacker can craft a WPG file containing embedded PostScript data with a magic name that is 4096 bytes or longer, triggering the missing null-termination vulnerability when ImageMagick processes the file.

ReadWPGImage ExtractPostscript GetMagicInfo ReadImage

## Vulnerability Analysis: `ExtractPostscript` in coders/wpg.c

### Summary of Findings

The function contains **two distinct error handling deficiencies** that could constitute a vulnerability depending on upstream parser validation of `PS_Size`.

---

### 1. Unchecked `ReadBlobByte` Return Value in Write Loop

```c
while(PS_Size-- > 0)
{
  (void) fputc(ReadBlobByte(image),ps_file);  // Return value discarded
}
```

**Behavior when blob runs short:**
- `ReadBlobByte` returns `-1` (cast to `int`) on EOF/error
- `fputc(-1, ps_file)` writes byte `0xFF` to the file (implementation-defined behavior for negative values, but typically masks to 0xFF)
- The loop continues silently, writing `0xFF` bytes until `PS_Size` expires

**Evidence:**
The `ReadBlobByte` function internally calls `ReadBlob` which returns `EOF` (−1) when the offset exceeds blob bounds. No bounds check exists in the calling loop.

---

### 2. Unchecked `ReadBlob` Return Value for Magic Buffer

```c
(void) ReadBlob(image, 2*MaxTextExtent, magick);  // Return value discarded
```

**Behavior on read failure:**
- `magick` buffer contains **uninitialized data**
- Execution continues to `GetMagicInfo(magick, ...)` with indeterminate contents
- `GetMagicInfo` performs pattern matching against `magic.mgk` on garbage data

---

### Attack Preconditions and Impact

| Condition | Required | Risk |
|-----------|----------|------|
| Attacker controls `PS_Size` | Yes—must come from untrusted WPG file | Large `PS_Size` → excessive writes |
| `PS_Size` exceeds blob remaining | Yes—if `PS_Size > (blob_size - PS_Offset)` | Corrupted temp file written |
| Predictable temp path | No—`AcquireUniqueFilename` uses secure random naming | Mitigates symlink/file injection |
| Temp file left accessible | No—`RelinquishUniqueFileResource` cleans up on failure path | Mitigates data exposure |

**Impact classification:**
- **Denial of Service (Low):** A deliberately large `PS_Size` could cause unbounded writes until disk exhaustion or `PS_Size` counter wraps (unsigned underflow takes ~18 quintillion iterations on 64-bit)
- **File Corruption (Medium):** File contains valid data prefix + `0xFF` padding
- **Secondary Processing Risk:** `ReadImage` processes the corrupted file; whether this triggers exploitable behavior depends on format handler robustness

---

### Defenses Present

1. **Magic detection guard:**
   ```c
   magic_info=GetMagicInfo(magick,2*MaxTextExtent,exception);
   if(magic_info == (const MagicInfo *) NULL) goto FINISH_UNL;
   ```
   Mitigates processing completely invalid data, but does not catch partial corruption.

2. **Cleanup on failure:**
   ```c
   (void) RelinquishUniqueFileResource(postscript_file);
   ```
   Temporary file is deleted on all error paths, preventing persistent artifacts.

3. **Filename randomness:** `AcquireUniqueFilename` creates unpredictably named files.

---

### Verdict

**VULNERABLE** under the condition that `PS_Size` is not validated against remaining blob size by the upstream WPG parser. The combination of:
1. No return value checking from `ReadBlobByte`
2. No `PS_Size` vs. blob size validation
3. Continued loop execution after EOF

creates a path where malformed input produces corrupted output. The realistic impact is **denial of service through resource exhaustion** if `PS_Size` can be arbitrarily large, and **degraded error handling** allowing corrupted files to reach downstream `ReadImage` processing.

**Residual uncertainty:** The call path mentions `ReadWPGImage` as the upstream caller. Without visibility into that function, I cannot confirm whether `PS_Size` is bounded there. If `PS_Size` is validated against `GetBlobSize(image) - PS_Offset`, this would eliminate the primary exploit path.

```json
{
  "vulnerable": true,
  "cwe": "CWE-754",
  "severity": "medium",
  "reviewed_region": "ExtractPostscript function, lines covering blob read, write loop, magic detection, and file resource cleanup",
  "vulnerable_region": "The while(PS_Size-- > 0) loop writing to the temporary file and the preceding ReadBlob call for magic detection",
  "root_cause": "Missing return value validation for ReadBlobByte (writes 0xFF for EOF) and ReadBlob (leaves magick buffer uninitialized); no upstream bounds check ensuring PS_Size does not exceed remaining blob bytes",
  "exploitability": "Exploitable if upstream ReadWPGImage does not validate PS_Size against (blob_size - PS_Offset). If validated upstream, attack surface is eliminated.",
  "attack_preconditions": "Attacker must control PS_Size in an untrusted WPG file such that PS_Size > bytes remaining in blob from PS_Offset, causing EOF to be reached before PS_Size iterations complete",
  "impact": "Denial of service via excessive temp file writes (if PS_Size is large); degraded error handling where corrupted temp file (valid prefix + 0xFF padding) is passed to ReadImage; secondary processing risk depends on downstream format handler robustness",
  "non_vulnerable_reason": "If ReadWPGImage validates PS_Size ≤ (GetBlobSize(image) - PS_Offset) before calling ExtractPostscript, the primary write-loop issue is neutralized. The unchecked ReadBlob for magic detection remains a latent concern.",
  "security_invariants": [
    "PS_Size must not exceed the number of bytes available from PS_Offset to end of blob",
    "ReadBlobByte must be checked for EOF (−1) and loop must break on failure",
    "ReadBlob return must be validated before using magick buffer for magic detection",
    "Temporary file must be cleaned up on all code paths via RelinquishUniqueFileResource"
  ],
  "invariant_verification": "Upstream ReadWPGImage is responsible for enforcing PS_Size bounds. The ExtractPostscript function itself performs no such validation. Magic detection guard (GetMagicInfo != NULL) only prevents processing of completely invalid magic bytes, not partial corruption of valid ones.",
  "residual_risk_notes": "Even if PS_Size is bounded correctly, the discarded ReadBlob return for magick buffer means incomplete reads leave uninitialized data in magick[2*MaxTextExtent]. This creates a latent path where blob I/O errors cause indeterminate magic detection input.",
  "call_path": "ReadWPGImage → ExtractPostscript → GetMagicInfo → ReadImage"
}
```