From 18e0db75a976e296682a81149b68223136eb8d3b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D0=BD=D1=82=D0=BE=D0=BD=20=D0=A2=D1=80=D0=BE=D1=88?=
=?UTF-8?q?=D0=B8=D0=BD?=
Date: Sun, 27 Sep 2026 02:14:49 +0300
Subject: [PATCH] feat: approximate NVRAM requirement from the CAP analysis
(v3.5.15)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
GlobalPlatform models this explicitly (GP Card Spec v2.3.1 Table 11-48,
load parameters): C6 = non-volatile code, C7 = volatile data, C8 =
non-volatile data, and 11.5.2.3.7 - when the card makes no code/data
distinction the required minimum is C6 + C8. The analysis now reports it:
- capmem.memory_json() accepts the load file size (all CAP components -
the package image the card stores) and returns code.load_file,
nvram.requirement = load_file + persistent data, and sets the suggested
C6 to the load file (the bytecode-only Method.cap figure stays in
code.method_component); _cap_info_body passes the size it already
computed.
- The CAP estimate box (both the RAM installer and the SCP81
Install-from-.cap form) leads with "NVRAM requirement ≈ code image +
data" plus the RAM estimate, keeps the bytecode/other-component split and
the full data breakdown in Details, and carries the GP citation with the
caveats (card memory management, allocation rounding and the registry
entry are not included; the static field image appears in both parts).
- An older server response without code.load_file still renders (the
bytecode size is used as the fallback).
Tests: Python +1 (load-file semantics) with extended cap-info assertions,
frontend +1 (renderer + fallback). Help EN/RU, docs/api.md, AGENTS.
587 frontend / 472 Python green; version 3.5.15; sw simple-v268.
---
docs/api.md | 15 +++++++++++++--
frontend/help-ru.html | 4 ++--
frontend/help.html | 4 ++--
frontend/index.html | 33 ++++++++++++++++++++++++++++-----
frontend/sw.js | 2 +-
frontend/tests/capmem.test.js | 27 ++++++++++++++++++++-------
pyproject.toml | 2 +-
pysim_simple_server/capmem.py | 29 +++++++++++++++++++++++------
pysim_simple_server/server.py | 6 ++++--
tests/test_cap_memory.py | 18 ++++++++++++++++++
10 files changed, 112 insertions(+), 28 deletions(-)
diff --git a/docs/api.md b/docs/api.md
index 9ea387f..688e69f 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -349,9 +349,10 @@ used for installation.
"package_aid": "AA1902BC226001",
"applet_count": 1, "applets": ["AA1902BC226001"],
"class_count": 3, "method_count": 12,
- "code": {"method_component": 850},
+ "code": {"method_component": 850, "load_file": 1234},
"nvram": {"static_image": 12, "array_init": 4, "install_objects": 100,
- "header_overhead": 24, "ref_storage": 8, "total": 148, "runtime": 0},
+ "header_overhead": 24, "ref_storage": 8, "total": 148, "runtime": 0,
+ "requirement": 1382},
"ram": {"transient_arrays": 16, "runtime_transient": 0, "peak_frame": 8, "total": 24},
"suggested": {"c6": 850, "c7": 272, "c8": 148},
"warnings": []
@@ -359,6 +360,16 @@ used for installation.
}
```
+`code.load_file` is the concatenated load file (all components) - the
+package image the card stores, our proxy for the GlobalPlatform Card Spec
+v2.3.1 Table 11-48 "non-volatile code" minimum memory requirement; the
+tool's bytecode-only figure stays in `code.method_component`. The suggested
+`C6` follows the load file, and `nvram.requirement` = `code.load_file` +
+`nvram.total` (the C6+C8-style total per §11.5.2.3.7: with no code/data
+split in the card's memory the required minimum is the sum of both). The
+estimate excludes card-specific memory management, allocation rounding and
+the GP registry entry.
+
**Errors** (HTTP 200 with `ok: false`, like `/api/scp81/gen-install`):
`{"ok": false, "error": "cap parse failed: File is not a zip file"}` for a
corrupt/wrong archive, or `cap analysis failed: …` when a component passes
diff --git a/frontend/help-ru.html b/frontend/help-ru.html
index 1cb37f4..1961618 100644
--- a/frontend/help-ru.html
+++ b/frontend/help-ru.html
@@ -319,7 +319,7 @@
Операция Описание
- Обзор карты (все данные GP) Запрос GET STATUS для ISD, приложений, ELF и модулей ELF, а также GET DATA FF21 для информации о памяти. Результаты отображаются в обзоре с кнопками Удалить для каждого элемента.
+ Установка пакета (.cap файл) Отправка .cap файла на карту через сервер: INSTALL[for load] → LOAD ×N → INSTALL[for install (+make selectable)]. Load-файл делится на LOAD APDU размера размер блока LOAD (1–240 байт полезной нагрузки, по умолчанию 240); каждый защищённый пакет доставляется одним SMS или, если он больше, конкатенированной SMS-PP загрузкой до 5 сегментов, так что большой .cap просто занимает несколько SMS. Сразу после выбора файл проверяется и в форме показывается оценка требований к памяти (код / NVRAM / RAM); повреждённый файл не проходит анализ, и Execute остаётся недоступной до успешного анализа.
@@ -376,7 +376,7 @@
Установка пакета (.cap файл) Отправка .cap файла на карту через сервер: INSTALL[for load] → LOAD ×N → INSTALL[for install (+make selectable)]. Load-файл делится на LOAD APDU размера размер блока LOAD (1–240 байт полезной нагрузки, по умолчанию 240); каждый защищённый пакет доставляется одним SMS или, если он больше, конкатенированной SMS-PP загрузкой до 5 сегментов, так что большой .cap просто занимает несколько SMS. Сразу после выбора файл проверяется и в форме показывается оценка требований к памяти: требование NVRAM (образ кода + постоянные данные, сумма в стиле C6+C8 из GP Card Spec) и оценка RAM; повреждённый файл не проходит анализ, и Execute остаётся недоступной до успешного анализа.
GET DATA FF21, листинги GET STATUS ISD/ELF/приложений, GET DATA 0085); длинные листинги автоматически продолжаются страницами SW 6310/CAFE..cap, при необходимости SD AID, параметры install/STK и Make selectable; кнопка Сгенерировать строит INSTALL [for load] → LOAD ×N → INSTALL [for install]. Файл используется только для генерации APDU — он не сохраняется, как и его имя. При выборе файл проверяется и показывается оценка требований к памяти (код / NVRAM / RAM); Сгенерировать недоступна до успешного анализа..cap, при необходимости SD AID, параметры install/STK и Make selectable; кнопка Сгенерировать строит INSTALL [for load] → LOAD ×N → INSTALL [for install]. Файл используется только для генерации APDU — он не сохраняется, как и его имя. При выборе файл проверяется и показывается оценка требований к памяти (требование NVRAM как сумма образа кода и постоянных данных, плюс RAM); Сгенерировать недоступна до успешного анализа.
Таблица показывает имя, тип, число APDU и время создания каждого скрипта, а также кнопки Редактировать и Удалить; в редакторе есть поле имени и текстовая область APDU. В ходе сессии сервер отдаёт по одному C-APDU на каждый POST карты и отслеживает выполнение: карта сообщает статус в следующем POST (X-Admin-Script-Status), оборвавшаяся сессия досылает только невыполненные APDU (X-Admin-Resume продолжает, новый диалог начинает заново), а завершённый скрипт закрывается ответом 204 No Content. Конструктор RAM/GP вкладки Remote APDU может отправить цепочку команд прямо в прогон кнопкой «В очередь SCP81».
.cap file to the card via the server: INSTALL[for load] → LOAD ×N → INSTALL[for install (+make selectable)]. The load file is split into LOAD APDUs of the LOAD block size (1–240 bytes of payload, 240 by default); each secured packet is delivered as a single SMS or, when larger, as a concatenated SMS-PP download of up to 5 segments, so a large .cap simply takes several SMS. As soon as the file is selected it is validated and its memory requirements are estimated (code / NVRAM / RAM) in the form; a corrupt or wrong-format file fails the analysis, and Execute stays disabled until a successful analysis..cap file to the card via the server: INSTALL[for load] → LOAD ×N → INSTALL[for install (+make selectable)]. The load file is split into LOAD APDUs of the LOAD block size (1–240 bytes of payload, 240 by default); each secured packet is delivered as a single SMS or, when larger, as a concatenated SMS-PP download of up to 5 segments, so a large .cap simply takes several SMS. As soon as the file is selected it is validated and its memory requirements are estimated in the form: the NVRAM requirement (the code image + persistent data, the GlobalPlatform Card Spec C6+C8 style total) and the RAM estimate; a corrupt or wrong-format file fails the analysis, and Execute stays disabled until a successful analysis.GET DATA FF21, GET STATUS ISD/ELF/application listings, GET DATA 0085); long listings auto-continue through the SW 6310/CAFE pages..cap plus optional SD AID, install/STK parameters and make selectable; Generate builds INSTALL [for load] → LOAD ×N → INSTALL [for install]. The file is only used to generate the APDUs — it is not stored, not even its name. On selection it is validated and its memory requirements are estimated (code / NVRAM / RAM); Generate stays disabled until the analysis succeeds..cap plus optional SD AID, install/STK parameters and make selectable; Generate builds INSTALL [for load] → LOAD ×N → INSTALL [for install]. The file is only used to generate the APDUs — it is not stored, not even its name. On selection it is validated and its memory requirements are estimated (the NVRAM requirement as the code-image + persistent-data total, plus RAM); Generate stays disabled until the analysis succeeds.The table lists each script with its kind, APDU count and creation time, plus Edit and Delete; the editor has a name field and the APDU textarea. Over a session the server serves one C-APDU per card POST and tracks execution: the card reports status in its next POST (X-Admin-Script-Status), a session that dies resends only the unexecuted APDUs (X-Admin-Resume continues, a fresh dialog restarts), and a completed script is closed with 204 No Content. The Remote APDU tab's RAM/GP builder can feed a command chain straight into the run with Queue in SCP81.