Sweeping public Ada code with AdaLang Analyzer: 24 real bugs, 54 fixes to the analyzer

Hello all,

For the past few weeks I have been testing AdaLang Analyzer, the Libadalang-based static analyzer I develop, on code other people wrote rather than on my own test files. Here is how I did it, how it improved the analyzer, and the real bugs it found along the way.

Corpora with an oracle

The repository keeps a set of independently written codebases under benchmarks/, and every release is run on all of them:

  • GNATprove as ground truth on five fully proved SPARK corpora (SPARKNaCl, Saatana, libkeccak, coap_spark, Tokeneer), plus CubeDOS and 124 tests of the SPARK testsuite. Of the 15,043 checks GNATprove proves there, --verify proves 12,038 (80%). On the 5,685 obligations both tools have at the same place, it has never called a definite error something that GNATprove proved safe. It also proves 9 checks that GNATprove leaves unproved, and all nine hold.
  • GNATcheck as ground truth on ten corpora, for the rules the two tools share.
  • Breadth on large ordinary Ada: AWS, GNATCOLL core and the Ada Drivers Library.

Any verdict that changes between two releases is explained before the release goes out.

Sweeps without an oracle

Corpora catch regressions, but they cannot show how the analyzer does on code it has never seen. So I also swept public code where nobody knows the answers in advance. Nothing was built or run: crates were fetched with an isolated Alire setup and only analyzed, with both --recommended and --verify. Then I read in the source every finding of the rules that usually mean a bug (definite errors, Same_Operand, Duplicate_Condition, Uninitialized_*, Infinite_Loop, Global contracts, …) and decided whether it was a real bug or a mistake of the analyzer.

Sweep Real bugs Analyzer issues fixed
Alire itself 0 5
The 42 most-used and most-starred Alire crates 8 15
57 more crates, and the first full results on PHCpack and Honki-Tonks-Zivilisationen 12 6
Brent Seidel’s repositories, ravenadm, Synth, AdaBase 1 5
13 more of Gautier de Montmollin’s repositories (GWindows, LEA, AZip, GLOBE_3D, …) 1 5
coreboot’s libgfxinit and libhwbase, 8 platform configurations 0 10
The Ironclad kernel, x86_64 and riscv64 2 8
Total 24 54

What the analyzer learned

The sweeps found many more mistakes of the analyzer than bugs in the code, and that is what they are for. Each mistake was reduced to a small test case, recorded in quality/known_analysis_issues.tsv (FP-145 to FP-198), fixed, and checked by running every corpus and every sweep again, so that a fix which removes one false report but costs a proof somewhere else is caught before the release. Releases 1.17.1 to 1.17.7 (20 to 28 November) carry 53 of the fixes, and the last one goes into the next release. The precision test suite now has more than 700 cases.

  • 49 false positives. Some examples: the out actual of a call nested in another call; a view conversion T (X) given as an out actual; 'Read and 'Asm_Output; writes through an overlay (with Address => Result'Address); for C of Buffer loop C := ' '; end loop;; loops over a static range, which always run at least once; exception handlers that read a flag; Relaxed_Initialization; the constituents of a Refined_State in Global contracts; a goto out of a loop; Ada.Text_IO.Delete, which closes the file it deletes.
  • 5 false negatives, one of them a soundness bug: with V : Unsigned_32, the analyzer took -1 for the integer -1 instead of the type’s last value, so if V = -1 then was “always false” and --verify called its branch unreachable. Engine-3D’s perfectly correct if Video_Selector = -1 then showed it.
  • Robustness. Sources compiled with -gnatW8, as Alire compiles every crate, are now read as UTF-8 (Honki-Tonks-Zivilisationen had 359,313 parse errors before), and PHCpack’s --recommended run, which timed out at 15 minutes, now finishes in under 8.

One number sums it up: on the first 42 crates, 1.17.1 reported 124 definite errors under --verify, and 3 of them were real. Two releases later, those 3 were all that was left.

The bugs

Each report gives the file and line, what goes wrong and a suggested fix, so it can be checked without the analyzer. Reports are named as owner/repository#number, on GitHub unless said otherwise.

Simple Components (Dmitry A. Kazakov), six defects: dak_simple_components#9

  • Add of the bounded maps (generic_bounded_map.adb:210, and the same in the indefinite one) passes Index => Offset to Insert in the branch where Offset <= 0, but Insert’s Index is Positive: adding any new key raises Constraint_Error. Found by a definite range check of --verify.
  • julia.adb: nine copy-paste slips in the checks that the Julia symbols were loaded, so a missing symbol is not reported and is later called through a null access:
      elsif Links.Box_Bool = null then
         Error ("jl_box_bool");
      elsif Links.Box_Bool = null then
         Error ("jl_box_char");
      --  ...
      elsif Links.Box_Int8 = null then
         Error ("jl_box_int32");
  • strings_edit-distinguished_names.adb:114: the error branch builds its message from Source (Start .. Source'Last), but only the other branches set Start.
  • unbounded_unsigneds-parallel.adb:99: S1.Length > 0 and then S1.Length > 0 (S2 was meant).
  • strings_edit-base64.adb:367: (Text'Length + 3 / 3) * 4, a precedence slip that makes the buffer about three times larger than needed.
  • parsers-generic_ada_parser.adb:3028: an elsif repeats the condition two lines above, so its branch is dead.

PHCpack (Jan Verschelde), seven defects: PHCpack#87, fixed by the author within three days

  function "<" ( x,y : triple_double ) return boolean is
  begin
    return ((x.hi < y.hi)
         or (x.hi = y.hi and x.mi < y.mi)
         or (x.mi = y.mi and x.mi = y.mi and x.lo < y.lo));
  end "<";

The last line should begin with x.hi = y.hi. The others: the divergence test (ncorr > s.corr) and then (ncorr > s.corr) in 24 places of the path-tracker correctors, so the relative residual was never tested; the same kind of slip in homotopy_newton_steps.adb; a ">" that lacks a clause all its siblings have; a dead elsif; an interactive loop with no exit; and a test datum c6/c6 for c6/c7.

ada-enet (Stéphane Carrez), stcarrez/ada-enet#24. NTP_Timestamp "-" returns 0 whenever Left is earlier than Right:

      if T1 > T2 then
         return Integer_64 (T1 - T2);
      else
         return -Integer_64 (T2 - T2);
      end if;

BBS-BBB-Ada (Brent Seidel), BrentSeidel/BBS-BBB-Ada#12. The parameter enable hides the literal enable of (disable, enable), so the RA8875 graphic cursor is turned on even for disable:

   procedure selectGraphCursor(self : RA8875_record; curs : MWCR1_GCURS_SET;
                               enable : MWCR1_GCURS_ENABLE) is
      --  ...
      if (enable = enable) then
         temp := temp + MWCR1_GCURS_EN;
      end if;

Sim-CPU (Brent Seidel), BrentSeidel/Sim-CPU#27. In the KT11 memory management unit, a trace prints num before it is set, and a condition tests has_super and has_super (its siblings test has_super and has_ID). The author then ran DEC’s diagnostics on the KT11 and will look at the further errors they reported in the same issue.

Excel Writer (Gautier de Montmollin), zertovitch/excel-writer#8. Write_as_Formula never marks a formula that does not parse as invalid, so "=1+" is written as a FORMULA record with an empty token array instead of a label (text) record. Confirmed by running it; the author is looking into it.

LEA (Gautier de Montmollin), zertovitch/lea#17. Save writes opt.tree_portion under the project_tree_portion key, so the project tree width you set is lost at restart (found by Identical_Case_Alternative):

            when tree_portion =>
              R (opt.tree_portion'Wide_Image);
            when project_tree_portion =>
              R (opt.tree_portion'Wide_Image);

Honki-Tonks-Zivilisationen, HonkiTonk/Honki-Tonks-Zivilisationen#25. abs (SenkrechteSchleifenwert) = 3 or abs (SenkrechteSchleifenwert) = 3 (and the same with 2): when the AI looked for a site for a new city, it checked only the vertical distance to the existing cities. Fixed upstream in commit 7043f76.

Ironclad, two issues on Codeberg (Ironclad/Ironclad), filed on 28 November:

  • Issue 29: on riscv64, Hard_Panic calls Print_Triple ("X31", "SEPC", "SSTATUS", ...), but the precondition of Print_Triple is N1'Length <= 3 and N2'Length <= 3 and N3'Length <= 3. This is the only definite error --verify reports on the kernel, and GNATprove 16.1.0 agrees.
  • Issue 30: the Global contracts of Arch.Clocks leave out state that the bodies use (Message_State, Panic_State, the monotonic clock state). GNATprove’s flow analysis reports the same places.

Ironclad’s CI checks the kernel at SPARK’s stone level, where flow analysis and proof do not run, which is how both could go unnoticed.

Smaller ones. Gnoga (Blady-Com/gnoga#13) tests two multimedia event names twice, which is harmless dead code. HiRTOS had pragma Compile_Time_Error (Max_Num_Timers > Max_Num_Timers, ...), which can never fire; it was already fixed upstream after the 2.0.0 release that Alire carries, so I did not report it.

Clean results. Alire itself, coreboot’s libgfxinit and libhwbase (no definite error in any of the 8 configurations, and every finding read), ravenadm, Synth, AdaBase and the other repositories above gave no real bug, only analyzer mistakes to fix. That is a useful result too.

Thanks, and where to get it

Many thanks to the maintainers who replied or fixed things so quickly (Jan Verschelde, Brent Seidel, Gautier de Montmollin and HonkiTonk) and to the Alire maintainers for passing the Simple Components report on.

AdaLang Analyzer 1.17.7 is on GitHub, with ready-to-run binaries for Linux, macOS and Windows. It is also in the Alire index as adalang_analyzer (1.17.7 is waiting for review there). The corpus results and the GNATprove ledger are in benchmarks/ in the repository.

The first one is not an error, because Offset is never 0. Others are.

It should have been ((Text'Length + 2) / 3) * 4. Intended was rounding of n/3 before multiplying by 4.

Thanks for reporting.

Thanks for checking them so quickly, Dmitry.

On the first one: I agree that Offset is never 0, so Index := -Offset is fine. The problem is the call on the next line, which passes Offset itself rather than -Offset:

      if Offset <= 0 then
         Index := -Offset;
         Insert
         (  Container => Container,
            Index     => Offset,  --  at most -1 here

In this branch Offset is the negated insertion position, so it is at most -1, while Insert’s Index is Positive. With checks on (the Debug mode, the default), the check on the parameter raises Constraint_Error before Insert is entered, for every new key added through the Add with Index : out Positive. With -gnatp (Release, Optimized) there is no exception: unless the map is empty, Insert computes Offset := First + Index - 1 from the negative Index and writes the item at a wrong place, or outside Data. The other Add passes Index => -Index. The same line is in generic_bounded_indefinite_map.adb:225; both are in 4.81.1 and on the master of the GitHub mirror Alire uses.

On base64: yes, ((Text'Length + 2) / 3) * 4 is the fix the issue suggests too.