Skip to content
Back to skills

Polyspace Analyze Generated Code

ASecurity

Use this skill to check the code generated from a Simulink model with Polyspace Bug Finder or Code Prover (model-link analysis), tracing each finding to its block. Use when asked to check the generated code or Embedded Coder output with Polyspace; check the robustness of the generated code; find overflows, divisions by zero, out-of-bounds accesses, or other defects and run-time errors in it; prove it free of run-time errors; check it for MISRA C, MISRA C++, CERT C/C++, CWE, or AUTOSAR C++14; ...

  • 1,443 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 4, 2026
ai-agentsgoc++gitapidatabase

Works with

  • api
  • mcp

Security analysis

A100/100

Pro scans all 5 files and shows the line behind each finding

Scanned December 4, 2026

npx -y skills add matlab/simulink-agentic-toolkit --skill polyspace-analyze-generated-code --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Polyspace Analyze Generated Code?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Polyspace Analyze Generated Code
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/matlab-polyspace-analyze-generated-code/badge)](https://www.skillsdirectory.com/skills/matlab-polyspace-analyze-generated-code)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: polyspace-analyze-generated-code
description: >
  Use this skill to check the code generated from a Simulink model with
  Polyspace Bug Finder or Code Prover (model-link analysis), tracing each
  finding to its block. Use when asked to check the generated code or Embedded
  Coder output with Polyspace; check the robustness of the generated code; find
  overflows, divisions by zero, out-of-bounds accesses, or other defects and
  run-time errors in it; prove it free of run-time errors; check it for MISRA C,
  MISRA C++, CERT C/C++, CWE, or AUTOSAR C++14; re-run an analysis keeping
  earlier justifications; re-check after a fix; or package it (polyspacePackNGo)
  to analyze on a CI server, Polyspace Server or another machine. When asked to
  make generated code MISRA compliant, checks it before and after
  simulink-optimize-embedded-code does. Generates or updates the code first. Not
  for checking the model itself (model-advisor-check-model-compliance,
  design-verifier-resolve-design-errors) or reviewing findings or deciding their
  fix (polyspace-review-generated-code-findings).
license: https://www.mathworks.com/content/dam/mathworks/license/pmrl/license.md
metadata:
  author: MathWorks
  version: "1.0"
---

# Analyze Generated Code with Polyspace

Use MATLAB/Simulink model-link analysis so Polyspace keeps model awareness
and links generated-code findings to Simulink blocks.

## When to Use

- Check the code generated from a Simulink model, or its Embedded Coder output,
  with Polyspace (Bug Finder, Code Prover)
- Check the robustness of the generated code: find overflows, divisions by
  zero, out-of-bounds accesses, or other defects and run-time errors, or prove
  the generated code free of run-time errors
- Check the code generated from a model for MISRA C, MISRA C++, CERT C/C++,
  CWE, or AUTOSAR C++14
- Re-run an analysis to verify a fix or to carry prior justifications forward
- Make generated code MISRA compliant: check it before and after the changes;
  `simulink-optimize-embedded-code` makes the changes
- Package the generated code with its Polyspace options for an analysis on
  another machine: a CI server, Polyspace Bug Finder Server or Code Prover
  Server without Simulink, or a supplier (see "Package for another machine")

## When NOT to Use

- Analyze handwritten or standalone C/C++ source files: use the Polyspace
  Agentic Toolkit skill `run-polyspace-bug-finder-analysis` or
  `run-polyspace-code-prover-analysis`. If the toolkit is not installed, do not
  analyze them: say this skill covers only code generated from a Simulink model,
  and recommend installing the Polyspace Agentic Toolkit
- Model-level compliance checks with Model Advisor (MISRA, CERT C, MAB, JMAAB,
  ISO 26262, DO-178C) where the user does not mention generated code or
  Polyspace: use `model-advisor-check-model-compliance`
- Design errors (division by zero, overflow, dead logic) detected on the model
  with Simulink Design Verifier, without generating code: use
  `design-verifier-resolve-design-errors`
- Configure the model for code generation (target, hardware, language, MISRA
  code generation profile): use `simulink-configure-model-for-code-generation`,
  then return here
- Change code generation settings to make generated code compliant or to
  optimize it: use `simulink-optimize-embedded-code`; this skill checks the
  result
- Prove that generated code is equivalent to the model (Simulink Code
  Inspector): use `simulink-code-inspector-check-compatibility`
- Package generated code to compile it elsewhere, without Polyspace: that is
  plain `packNGo`
- Checker configuration only: use the Polyspace Agentic Toolkit skill
  `polyspace-configure-checkers` (`configure-checkers` in toolkit 1.0). If the
  toolkit is not installed, recommend installing it
- For reading, reviewing, or interpreting existing results, or deciding how to
  fix findings, use `polyspace-review-generated-code-findings`
- For justifying results, use `polyspace-justify-generated-code-findings`
- The project has its own script to run Polyspace: use that script

## Prerequisites

- Polyspace Bug Finder and Polyspace Code Prover, integrated with MATLAB and
  Simulink. Step 2 checks this; stop if it fails. Packaging for another
  machine needs no Polyspace product here.
- Embedded Coder, Simulink Coder, and MATLAB Coder to generate code.
- The Polyspace Agentic Toolkit (Polyspace MCP server) is recommended. If its
  tools are available (for example `configure_checkers_for_polyspace`), use them
  where this workflow says so. Step 2 checks whether it is installed; every step
  works with the MATLAB API alone.

## Workflow

### 1. Establish the model
Use the named model. If omitted and a model is open, use `bdroot(gcs)`: the top model, even when a subsystem is selected. If no model is open and exactly one `.slx` exists, load it. Stop only if multiple plausible models exist and no safe default exists.

```matlab
modelName = "myModel";
load_system(modelName);
```

### 2. Verify Availability of Polyspace
Confirm MATLAB can access the Polyspace model-link API. If not, report the missing integration and stop.

```matlab
polyspaceIntegration = which("polyspace.ModelLinkOptions");
assert(~isempty(polyspaceIntegration), ...
    "Polyspace is not integrated with MATLAB/Simulink. See https://mathworks.com/help/codeprover/ref/polyspacesetup.html");
```

Also check whether the Polyspace Agentic Toolkit tools are available (for example `configure_checkers_for_polyspace`). If they are not, tell the user once in your answer that installing it is recommended (https://github.com/mathworks/polyspace-agentic-toolkit), and continue with the MATLAB API.

### 3. Generate code
Read the model's `SystemTargetFile` and `GenerateTraceInfo` with the
`model_query_params` tool, not with `get_param`. If the target is not an
ERT-based target, or the user asks to change the target, hardware, or MISRA code
generation profile, stop and use `simulink-configure-model-for-code-generation`
first. If that skill is not available, report which settings must change, name
`simulink-configure-model-for-code-generation` as the skill that changes them,
and stop. Do not change the configuration in this skill. If
`GenerateTraceInfo` is `off`, tell the user that Polyspace cannot link
findings back to blocks until model-to-code traceability is enabled.

Tell the user that code generation can take several minutes. Unless there are
project-specific scripts to generate code from the model, use:
```matlab
slbuild(modelName);
```

On failure, preserve diagnostics and stop. Polyspace model-link analysis uses the generated code and build information from this step.

### 4. Choose the product/analysis type
- Use *Bug Finder* for defects, coding rules, MISRA, CERT, CWE, and metrics. A request to *find* overflows, divisions by zero, or out-of-bounds accesses is a defect search: Bug Finder.
- Use *Code Prover* for robustness proofs, value analysis, call trees, and proving absence of run-time errors. A request to *check the robustness* of the generated code is Code Prover.

If both are requested, run separate analyses.

C and C++ code generation (the model's `TargetLang`) are both supported; model-link selects the analysis language from the generated code.

### 5. Create model-link options
Configure model-link analysis with a deterministic results folder; keep the project object. Use separate folders for separate models, products, and standards.

```matlab
analysisMode = "BugFinder";  % or "CodeProver"
resultsFolder = fullfile(pwd, "polyspace-results", modelName, analysisMode);

opts = polyspace.ModelLinkOptions(modelName);
opts.ResultsDir = resultsFolder;
proj = polyspace.Project;
proj.Configuration = opts;
```
This configures analysis for `modelName` **without** referenced (sub-)models.
To include referenced models, seed the options from `pslinkoptions`:

```matlab
linkOpts = pslinkoptions(modelName);
linkOpts.ModelRefVerifDepth = 'All';
opts = polyspace.ModelLinkOptions(modelName, linkOpts);
opts.ResultsDir = resultsFolder;
proj.Configuration = opts;
```

If `resultsFolder` already holds an earlier run, rename it with a timestamp
before analyzing again, so no results or `ps_comments.db` are overwritten or
deleted. The renamed folder is the previous run:

```matlab
previousResultsFolder = "";
if isfolder(resultsFolder)
    previousResultsFolder = resultsFolder + "-" + string(datetime("now", Format="yyyyMMdd-HHmmss"));
    movefile(resultsFolder, previousResultsFolder);
end
```

See `references/model-link-api.md` in this folder, if more API details are needed.

### 6. If Bug Finder, configure checkers
Skip this step unless specific standards or checker families like "MISRA" are requested.

**If the Polyspace Agentic Toolkit is installed** (`configure_checkers_for_polyspace` is available), invoke `configure_checkers_for_polyspace` to create an XML file defining checker selection, and attach it to the model-link options:
```matlab
checkersFile = fullfile(pwd, 'polyspace-results', modelName, 'checkers.xml');
opts.Advanced.Additional = [opts.Advanced.Additional, ' -checkers-activation-file "', char(checkersFile), '"'];  % must stay one char vector or string scalar
```

**Otherwise**, use the model-link options directly to select checkers. For example, to enable MISRA C:2023:
```matlab
opts.CodingRulesCodeMetrics.EnableMisraC2023 = true;
opts.CodingRulesCodeMetrics.MisraC2023 = "all";
```
For other checker options, see `references/model-link-api.md` in this folder.

For C++ code generation, the options have C++ coding-rule properties instead (CWE works for C and C++):

```matlab
opts.CodingRulesCodeMetrics.EnableMisraCpp2023 = true;
opts.CodingRulesCodeMetrics.MisraCpp2023 = "all";
% CERT C++: EnableCertCpp / CertCpp; AUTOSAR C++14: EnableAutosarCpp14 / AutosarCpp14
```

**Important**: For MISRA C, always use the categories for generated code (AGC mode; MISRA C++ has no AGC mode). From R2026b, set the `MisraAgcMode` property; in earlier releases, add the flag matching the requested standard. Do not add the flag when the property exists: model-link then drops the MISRA standard.

```matlab
if isprop(opts.CodingRulesCodeMetrics, "MisraAgcMode")  % R2026b and later
    opts.CodingRulesCodeMetrics.MisraAgcMode = true;
else
    % MISRA C:2023; for MISRA C:2012 use " -misra3-agc-mode"
    opts.Advanced.Additional = opts.Advanced.Additional + " -misra-c-2023-agc-mode";
end
```

### 7. If Code Prover, keep the configuration from the model
Model-link generates `main` (calling `<model>_initialize`, then the step function in a loop) and data range specifications from the design Min/Max of inputs. Keep these defaults unless the user asks otherwise:

- To analyze parameters over their Min/Max instead of their current value, set `ParamRangeMode = 'DesignMinMax'` in `pslinkoptions`.
- To analyze tasks concurrently, declare one entry point per task and remove the step functions from the generated loop. With entry points, `<model>_initialize` is not analyzed; tell the user.

Do not write a data range specification file by hand when the ranges are in the model. See `references/code-prover-configuration.md` for the settings and code.

### 8. Import prior justification comments if requested
To compare results, or carry database comments and justifications into a new
analysis, set `ImportComments` to the previous analysis results folder before
running the project. The value is the folder path that contains the previous
results.

```matlab
importFolder = previousResultsFolder;  % renamed in step 5, or the folder the user names
if strlength(importFolder) > 0 && isfolder(importFolder)
    opts.ImportComments = importFolder;
    proj.Configuration = opts;
end
```

If there is no previous run, or the folder the user names does not exist, do not set `ImportComments` and tell the user that no comments are imported. Polyspace ignores a missing folder with only a warning and still returns 0. After the run, confirm the import in the log (`Importing comments from <folder>`).

Use a previous analysis of the same model and product so Polyspace can match the findings. Preserve that complete results folder, including `ps_comments.db`, as analysis evidence.

Only comments stored in the previous results (`ps_comments.db`) need this import. Model annotations are written into the code again when it is regenerated.

**Interpret import statistics carefully:** The "matched results with a comment coming from source code annotation" count describes comment matching during `ImportComments`; it is not a count of annotations in the current model or generated source. A zero count does not mean a newly generated model annotation failed.

### 9. Run analysis
Launch the selected product with `proj.run("BugFinder")` or `proj.run("CodeProver")`.

On non-zero return value, inspect logs in results folder.

After a successful analysis, hand off to `polyspace-review-generated-code-findings` to
load and review the findings. Communicate `resultsFolder`, the results file in it (`.psbf` for Bug Finder, `.pscp` for Code Prover), and the selected analysis product from this workflow.

If this run verifies a justification, report back to
`polyspace-justify-generated-code-findings` instead. If it re-checks a fix, hand
off to `polyspace-review-generated-code-findings` to compare the runs. In both
cases, pass the current and the previous results folder.

## Package for another machine

When the analysis runs elsewhere (CI server, Polyspace Server without
Simulink, supplier), do step 1 and the configuration check of step 3, then
follow `references/package-for-another-machine.md` in this folder instead of
steps 2 and 4–9: it builds after enabling packaging. In short:

- Enable `PackageGeneratedCodeAndArtifacts` in memory with `model_edit`,
  rebuild before every packaging, restore the setting, and do not save the model.
- Call `polyspacePackNGo` with the receiver's product; for a top model with
  referenced models, set `ModelRefVerifDepth = "All"` first.
- Hand over the archive that `polyspacePackNGo` writes, unchanged. Coding
  standards are never packaged: give them on the receiver's Bug Finder command
  (Code Prover ignores them). Report `polyspacePackNGo` defects instead of
  editing the archive.

## Conventions

- Prefer separate results folders per model, product, and coding standard
- Preserve prior results folders and their `ps_comments.db` files used for GUI justifications
- Set `opts.ImportComments` to the prior results folder to import justification/suppression comments

## Common Mistakes

- Running Polyspace directly on generated `.c` files instead of using model-link analysis. Findings lose their link to blocks.
- Selecting checkers both with a checkers-activation file and with the `CodingRulesCodeMetrics` standard properties. They are mutually exclusive; `MisraAgcMode` is not a checker selection and applies with either
- Using `polyspace-configure` for generated code. Model-link analysis already provides the build context.
- Running `pslinkrun` with a hand-written project file (`EnablePrjConfigFile`, `PrjConfigFile`) to reach options that `pslinkoptions` does not expose, such as MISRA C:2023, CERT C, CWE or task entry points. Set them on `polyspace.ModelLinkOptions` and run `polyspace.Project`.
- Re-running into the same results folder. The previous results and their `ps_comments.db` are lost.
- Editing, re-zipping or hand-building a `polyspacePackNGo` archive. The next packaging loses the edits, and the product defect stays hidden.

----

Copyright 2026 The MathWorks, Inc.

----

Files in this skill

  • SKILL.md15.3 KB
  • manifest.yaml743 B
  • references/code-prover-configuration.md3.2 KB
  • references/model-link-api.md4.5 KB
  • references/package-for-another-machine.md4 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.