Defect report · 2026-11-14

Forty-one defects in the ISDA CDS Standard Model

Found while porting the 2009 C library to C++20 — all 163 in-scope functions, with both implementations run side by side under AddressSanitizer and UBSan. Most cannot occur in the port, because the types stopped permitting them. Thirty-nine are reproduced faithfully; two are corrected, and that decision is argued below.

Library examined
ISDA CDS Standard Model 1.8.3 (C, 2009)
Obtained from
cdsmodel.com, under the ISDA CDS Standard Model Public License
Method
In-process differential testing vs. a C++20 port, with ASan + UBSan
Coverage
All 163 in-scope functions, across 41 of the 49 files in lib/src
Reproduce
./build/debug/defect_evidence
Fixed upstream
None — see below

Register

ID Defect Severity Status in the port
UPSTREAM-1 Month validated after it indexes a 13-element table Low · UB Cannot occur
UPSTREAM-2 JPMCDS_DEFAULT and FAILURE are both -1 Design Cannot occur
UPSTREAM-3 Lowercase 'y' advances a date quarterly, not annually High · mispricing Cannot occur
UPSTREAM-4 Stack buffer overflow from string input High · memory safety Fixed deliberately
UPSTREAM-21 An empty cash flow list crashes the bootstrap — including the handler that exists to report the error Medium · SIGSEGV Cannot occur
UPSTREAM-22 When the final payment lands on the curve's last date, every branch declines and the function reports success having done nothing Medium · silent no-op Cannot occur
UPSTREAM-26 Supplying a substitution table silently disables the bad day convention, so an unlisted Saturday stays a Saturday Low · documented purpose only Reproduced; signature fixed
UPSTREAM-41 An upper-cased copy of every line that nobody reads — so the weekend directives are case-sensitive, and a lower-case one is dropped in silence High · silently wrong calendar Corrected — near-misses refused
UPSTREAM-39 An unparseable year is invented, not refused — the month and day in the same function do check; the year is read with a bare atol eleven lines later High · silent wrong date Corrected — the only one
UPSTREAM-38 Three bytes lowercased however short the token is — a bounded copy followed by an unchecked read past its result High · memory safety Cannot occur
UPSTREAM-40 Digits accumulated into a signed long with no range check — UB on any 19-digit number, from untrusted text Low-Medium · UB, out of scope Not applicable
UPSTREAM-37 A NULL guard on one path out of four — the guarded path teaches the caller NULL is fine, and three others punish them for believing it Medium · store through NULL Cannot occur
UPSTREAM-36 The fourth unguarded fArray[fNumItems-1] — at four occurrences it is an idiom the codebase trusts, not four accidents Medium · null-derived read Cannot occur
UPSTREAM-35 toupper on a plain char — undefined for 127 of the 128 high-bit bytes, and legal for the 128th by collision with EOF Low · UB, no consequence shown Cannot occur
UPSTREAM-34 A validator that reports a NULL pointer and then dereferences it — because it accumulates failures, and one check guards another Medium · null dereference Cannot occur
UPSTREAM-33 The root finder is handed the last curve slot, not the one it just added — and the curve inserts in sorted order, not at the end Low · misleading failure Cannot occur
UPSTREAM-32 The bizarre rate got a guard; the bizarre maturity did not — a read-modify-write through NULL[-1], two statements after the careful bit Medium · null write Cannot occur
UPSTREAM-31 An output written after the error label, from a variable never set — the first finding here that no sanitizer could have caught Low · UB, value discarded Cannot occur
UPSTREAM-29 A schedule the library returns and its own validator rejects — zero coupon periods, reported SUCCESS, then indexed at fArray[-1] by zcswap.c Medium · out-of-bounds read Cannot occur
UPSTREAM-30 A heap buffer sized from one date span and filled from another, at a public entry point that validates none of its nine arguments Medium · heap overflow Cannot occur
UPSTREAM-28 Interpolating past the end of a curve leaves order validation disabled process-wide and permanently — the same global as UPSTREAM-13, leaking on the success paths instead Medium · permanent effect Cannot occur
UPSTREAM-27 A day <= 28 guess declares month-end schedules off cycle when they are not — and the previous coupon date moves with it Low · 14 of 600, all leap days Reproduced deliberately
UPSTREAM-25 A one-date schedule with a stub reads and writes past a one-element allocation — and reads before it in the other direction Medium · heap overflow Cannot occur
UPSTREAM-24 A roll date is consulted when there is no stub and ignored when there is one — the opposite of what its header documents Low · one day, leap years Reproduced deliberately
UPSTREAM-23 A bare if (rate >= 0.0) drops curve points on a negative-rate curve, in the function whose job is to add them Low · no pricing effect found Not reproduced
UPSTREAM-20 A public merge documents one precondition and checks it, while omitting the one the algorithm actually needs — that both inputs are ordered Low · public header only Cannot occur
UPSTREAM-19 The guard against an unusable discount factor is if (discount<=0.0) — the one comparison every NaN passes Medium · NaN as success Cannot occur
UPSTREAM-18 A bad discount factor is detected, the error message is written, and the function returns SUCCESS with a fabricated 1.0 — a forward rate of exactly zero Medium · fabricated answer Cannot occur
UPSTREAM-17 A fast path for the common case returns infinity where the general path it replaces rejects the input — and the infinity is stored in the curve Medium · stored infinity Cannot occur
UPSTREAM-16 A missing return adds a curve point twice; on one input the second route fails, so the function reports failure with the curve already mutated Medium · partial mutation Cannot occur
UPSTREAM-15 A validating curve constructor accepts 30/360 and empty curves that JpmcdsZeroPrice then prices as NaN Medium · silent NaN Cannot occur
UPSTREAM-14 Bond day-count metrics return uninitialised stack memory for a pre-1601 date, and report success Medium · wrong answer Cannot occur · port is correct
UPSTREAM-13 One failed interpolation call leaks a global and disables sorted-input validation process-wide Medium · permanent effect Cannot occur
UPSTREAM-12 A lunar-month interval computes its value and then falls through a missing break into the error branch Low · hand-built intervals only Cannot occur
UPSTREAM-11 Accrual on a defaulted CDS goes negative once settlement crosses a coupon date — returned as success High · wrong money Fixed · documented intent
UPSTREAM-10 Unbounded vsprintf into a 4096-byte stack buffer — the single function every error message passes through Medium · memory safety Cannot occur · no error log exists
UPSTREAM-9 An error message with two %s conversions formatted with one argument Medium · undefined behaviour Cannot occur
UPSTREAM-8 !price > THRESHOLD precedence bug disables a validation guard, in four places Low · guard only Resolved · guards the real failure
UPSTREAM-7 Date list truncation ignored when fewer than two dates survive; two implementations fail in opposite directions High · silently wrong Fixed · documented intent
UPSTREAM-6 Business-day adjustment never returns for a calendar with no business weekday High · liveness Cannot occur
UPSTREAM-5 Days never format as weeks (missing break) Cosmetic Reproduced

What “fixed” means here, precisely

Nothing is fixed in upstream. The original sources are never edited — they are the numerical oracle the port is verified against, and editing them would destroy the only independent check the project has. Every user of the official C library still has all five.

Of the first six, four were not fixed so much as made unrepresentable — and that ratio held as the register grew to forty. No patch was written for UPSTREAM-1, -2, -3 or -6; the types stopped permitting them. A month that cannot be 13. A result that cannot carry a sentinel. A period type normalised at construction. A loop whose bound is derived rather than hoped for. That is the strongest single argument for the port existing: those four died as a side effect of choosing better types and stating preconditions, not as a side effect of hunting for bugs.

Two defects the port consciously declines to reproduce. UPSTREAM-4, because faithfully reproducing a buffer overflow is not fidelity; and UPSTREAM-39, because there the code contradicts itself eleven lines apart, so there is no single behaviour to be faithful to. Everything else is reproduced exactly, divergences included.

UPSTREAM-5 is the only one deliberately kept, because its output is observable by callers; abbreviating "14D" to "2W" would be a behaviour change dressed up as a fix.

UPSTREAM-3

Lowercase 'y' advances a date quarterly, not annually

High · silent mispricing Cannot occur in the port

lib/src/ldate.c · JpmcdsDtFwdAny

Mechanism

Inside case 'Y': the month multiplier is chosen like this:

if (upperPrdTyp == 'M')
    intval.prd = interval->prd;
else if (upperPrdTyp == 'A' || interval->prd_typ == 'Y')   /* raw, not upper-cased */
    intval.prd = interval->prd * JPMCDS_MONTHS_PER_YEAR;
else if (upperPrdTyp == 'S')
    intval.prd = interval->prd * JPMCDS_MONTHS_PER_SEMI;
else
    intval.prd = interval->prd * JPMCDS_MONTHS_PER_QUARTER;  /* 'y' lands here */

The second test checks the upper-cased type for 'A' but the raw type for 'Y'. A lowercase 'y' matches neither, falls to the else, and is multiplied by 3 instead of 12.

Evidence

Start date 2008-01-03, one period, measured against the live library:

  type   upstream       months advanced
  'Y'    2009-01-03     12
  'y'    2008-04-03     3
  'A'    2009-01-03     12
  'a'    2009-01-03     12
  'M'    2008-02-03     1
  'm'    2008-02-03     1
  'S'    2008-07-03     6
  's'    2008-07-03     6
  'Q'    2008-04-03     3
  'q'    2008-04-03     3

'y' is the only period type in the library whose meaning depends on letter case.

Reachability

Not reachable through JpmcdsMakeDateInterval or JpmcdsStringToDateInterval, both of which upper-case first and normalise 'Y' to months. It bites hand-constructed TDateInterval values — which is precisely the audience upstream’s own comment names, a few lines above the defect:

This code is left here for people who have set up their own TDateIntervals without calling JpmcdsMakeDateInterval or one of the supplied macros.

Status in the port

Cannot occur. make_date_interval upper-cases and normalises to days or months before any arithmetic, so no non-canonical period type survives to the calculation.

Port: make_date_interval(1,'y') == make_date_interval(1,'Y') -> true
Tests: DateIntervalDifferential.Upstream3_LowercaseYAdvancesQuarterlyNotAnnually
        DateIntervalMake.IsCaseInsensitiveIncludingY
The first asserts the defect still exists upstream, so it fails if a future release fixes it.
UPSTREAM-4

Stack buffer overflow from string input

High · memory safety Fixed · deliberate divergence

lib/src/convert.c:288 · JpmcdsStringToDateInterval

Mechanism

The digit-copy loop has no bounds check against its fixed stack buffer:

#define MAX_DIGITS 32
char numberBuff[MAX_DIGITS];
char *nump = numberBuff;
...
while (isdigit((int)*inp))
    *nump++ = *inp++;          /* unbounded */

Any interval string with more than 31 digits writes past the buffer.

Evidence

ERROR: AddressSanitizer: stack-buffer-overflow
WRITE of size 1 at 0x00016b2e1e60 thread T0
    #0 JpmcdsStringToDateInterval convert.c:289
  This frame has 1 object(s):
    [32, 64) 'numberBuff' (line 275) <== Memory access at offset 64 overflows this variable

Measured boundary:

  digits         upstream               port
  5              accepted               accepted
  10             accepted               accepted
  31             accepted               accepted
  32             overflow               rejected
  40             overflow               rejected
  64             overflow               rejected

Reachability

Interval strings ("1Y", "3M", "6M") are exactly what the shipped Excel add-in reads from user-entered cells, so the input is caller-influenced in the most ordinary deployment of this library.

Status in the port

Fixed, by deliberate divergence. parse_date_interval bounds the digit count and rejects anything longer. This is the only place the port does not reproduce upstream behaviour.

An executable reproducer ships in the repository rather than as prose. It is disabled by default, because it crashes the sanitizer build on purpose:

./build/asan/cdsmodel_differential_tests \
    --gtest_also_run_disabled_tests --gtest_filter='*Upstream4*'
Tests: DateIntervalParse.RejectsDigitRunsThatWouldOverflowUpstreamsBuffer
        DISABLED_Upstream4_LongDigitRunOverflowsStackBuffer (the reproducer)
UPSTREAM-8

A validation guard that validates almost nothing

Low · a guard that does not guard Resolved · guards the real failure

contingentleg.c:90 & :97, feeleg.c:101 & :108 — the same line, four times

Mechanism

if (!JpmcdsZeroPrice(spreadCurve, cl->endDate) > JPMCDS_LOG0_THRESHOLD)
{
    JpmcdsErrMsg("%s: Default hazard rate is not defined at maturity %s!", ...);
    goto done;
}

! binds tighter than >, so this is (!price) > 1e-100 — a 0 or 1 compared against a threshold. True exactly when the price is zero. The intent was plainly !(price > THRESHOLD): reject a survival probability too small to take a logarithm of. The macro is even named JPMCDS_LOG0_THRESHOLD, "Used for avoiding LOG0 error".

Evidence

hazard rate    survival(T)    as-written as-intended JpmcdsContingentLegPV
0.01           0.905          passes    passes    pv=494850
0.5            0.00671        passes    passes    pv=5.63225e+06
5              1.85e-22       passes    passes    pv=5.96421e+06
20             1.17e-87       passes    passes    pv=5.99101e+06
50             4.72e-218      passes    fires     pv=5.9964e+06
80             0              fires     fires     REJECTED
200            0              fires     fires     REJECTED

Why the severity is low, stated carefully

The window where written and intended behaviour differ is survival in (0, 1e-100] — hazard rates above roughly 23 for a ten-year maturity. That is not a credit; it is a number that has underflowed.

And in that window the computation does not misbehave. At a hazard rate of 50 it returns 5.9964e6 against a notional of 1e7 and recovery of 0.4 — that is notional × (1 − R) = 6e6 to four figures, the correct limit for a credit certain to default. The guard was defensive, the defect disabled the defence, and the computation turned out not to need it.

So this is not a demonstrated mispricing, and it is recorded as a guard defect rather than a numerical one — precisely because the tempting headline, "precedence bug on the pricing path", would overstate it.

Status in the port: resolved, by measurement

The port guards the real failure rather than a proxy. It computes, and rejects a result that is not finite. 1e-100 was only ever a stand-in for "the logarithm will misbehave"; with the integral built, that condition is directly testable.

The measurement: down to survival probabilities around 1e-300 the logarithms stay finite and the integral converges on notional × (1 − recovery) — the correct limit for a credit certain to default. Only an exactly zero survival gives log(0) = −inf and a NaN. So the honest guard and upstream's broken one fire on identical inputs, verified from hazard 0.001 to 200 across the boundary where survival crosses from tiny to underflowed.

Upstream's behaviour is therefore preserved while the stated condition is true. Implementing the author's literal intent would have made the port refuse to price cases upstream prices correctly — which is why "fix the contract violation" was the wrong reflex, and why this decision waited for a measurement.

Reproduce: ./build/debug/defect_evidence u8
UPSTREAM-9

An error message formatted with one argument too few

Medium · undefined behaviour on a reject path Cannot occur

stub.c:173, inside JpmcdsStringToStubMethod

Mechanism

One message is declared with two %s conversions:

static char invalidFormatMsg[]  = "%s: Invalid stub method format %s. "
    "Format is LOCATION/TYPE/[LENGTH].\n" ...

The bad-LOCATION branch passes both arguments. The bad-LENGTH branch, twelve lines below it, passes one:

JpmcdsErrMsg (invalidFormatMsg, routine, name);   /* correct   */
JpmcdsErrMsg(invalidFormatMsg, routine);          /* one short */

So vsprintf reaches for a second argument that was never pushed, takes whatever occupies that varargs slot, and dereferences it as a string. Any input whose LENGTH field is present but does not begin with s, S, l or L reaches it — including "f/", where the field is present but empty.

Evidence

AddressSanitizer: stack-buffer-underflow, READ of size 5
  #0 strlen                      <- consuming the second %s
  #3 __vsprintf_chk
  #5 JpmcdsErrMsgV
  #7 JpmcdsStringToStubMethod+0x120

On manifestation, stated carefully

The read is undefined whenever the branch is taken, but whether it faults depends on what the caller left in that varargs slot. Measured on arm64 macOS it faults in a minimal standalone frame, and does not fault inside the differential test binary or inside the evidence tool.

A dedicated reproducer target was written and then deleted, because it stopped faulting once it was a CMake target rather than a scratch file — the frame layout changed and the slot stopped holding a poisoned address. So the evidence here is the source, not a crash. Behaviour that appears in one caller and not another is what undefined behaviour looks like; that is not grounds for calling it benign, and not grounds for claiming a reliable crash either.

A documentation divergence found alongside it

The same message documents the format as LOCATION/TYPE/[LENGTH] — three fields. The parser splits on a single / and reads field two as LENGTH. There is no TYPE field, and a third field is silently ignored: "f/n/l" is read as LENGTH 'n' and rejected without ever reaching the 'l'. The code is the specification; the message describes an interface that was never built.

Status in the port

Cannot occur. parse_stub_method returns nullopt and formats nothing. It also drops upstream's toupper(*locStr) call — whose domain excludes negative values, i.e. any byte above 0x7F where char is signed — in favour of comparing both cases directly.

Two upstream behaviours are kept on purpose: single-character field matching, so "fromage/sausage" still parses as front/short, and the "f"-succeeds / "f/"-fails asymmetry, which comes from upstream distinguishing a missing field from an empty one. Both are observable at a public API.

UPSTREAM-10

Unbounded vsprintf into a 4096-byte stack buffer

Medium · caller-controlled stack overflow Cannot occur · no error log exists

cerror.c:533 — the one function every formatted error message passes through

Mechanism

static int JpmcdsWriteToLog(TBoolean formatted, char *format, va_list parminfo)
{
    char buffer[JPMCDS_ERR_MSG_BUFFER];   /* 4096 */
    ...
    if (formatted)
    {
        vsprintf(buffer, format, parminfo);
    }

vsprintf, not vsnprintf. Of the 452 JpmcdsErrMsg call sites, 67 interpolate a caller-supplied string after the routine name — day count strings, date interval strings, stub strings, calendar and file names. A caller passing roughly 4KB or more of string writes past the end of this buffer with content it chose.

Evidence

Measured threshold, two independent public entry points, messages enabled. The prefix is about 200 characters, so the cliff lands where prefix plus argument reaches 4096:

length   JpmcdsStringToStubMethod      JpmcdsStringToDayCountConv
1000     returns FAILURE               returns FAILURE
3800     returns FAILURE               returns FAILURE
3900     ABORT (fortify check fires)   ABORT (fortify check fires)
4200     ABORT                         ABORT
9000     ABORT                         ABORT

Survives at 3800, dies at 3900, identically from both entry points. On a fortified libc the overflow is detected and the process aborts; on an unfortified build it is a plain stack smash with caller-controlled bytes.

Why Medium and not High

The formatting is only reached once a host has called JpmcdsErrMsgOn. Messages are off by default and nothing in the shipped distribution turns them on — with messages off, a 50,000-character argument is harmless.

So it is latent in the library and live in any host that enabled diagnostics — which is exactly the configuration someone debugging a pricing discrepancy would be running, and the configuration an Excel add-in surfacing error text would want.

How it was found, because the route matters

This is the mechanism that makes UPSTREAM-9 more than a cosmetic slip: the stray pointer U9 produces is dereferenced by this same vsprintf. U9 supplies a bad pointer; U10 is the unbounded write it feeds.

Finding them in that order was luck. U9 was visible by reading stub.c while porting the stub parser. U10 only appeared because U9's reproducer behaved inconsistently, and the question "why does this sometimes fault" led into cerror.c. An inconsistent reproducer turned out to be a more useful signal than a reliable one would have been.

Status in the port

Cannot occur — and not because it was fixed. There is no global error log to format into: a failure is an empty std::optional, and a caller-supplied string is never copied anywhere. The defect is absent structurally rather than patched, which is the fifth time in this port that a defect died from the shape of the code rather than from a correction.

UPSTREAM-11

A negative accrual, returned as SUCCESS

High · a wrong cash amount, reported as success Fixed · documented intent

defaulted.c:68–80, inside JpmcdsDefaultAccrual

The only defect in this register that silently returns the wrong money. Not undefined behaviour, not a crash, not an error path — a settlement amount.

Mechanism

The function locates the coupon period by the trade date and then accrues to the event date:

while (i < fl->nbDates)
{
    if (fl->accStartDates[i] <= tradeDate && tradeDate < fl->accEndDates[i])
    {
        *accrualDays = edd + 1.0 - fl->accStartDates[i];

It guards edd >= startDate, but never edd >= accStartDates[i]. So as soon as the trade date crosses a coupon boundary the event date did not, that subtraction goes negative — and status = SUCCESS is set on the next line.

Evidence

Quarterly from 20 March 2024, credit event 1 August 2024, notional 1e7, coupon 100bp, ACT/360. The event sits in the 20 June – 20 September period, so 43 days are owed. Varying only when the question is asked:

  trade date       upstream   accrual days   amount           port
  event+0          SUCCESS    43             11944.4          43 days
  event+14         SUCCESS    43             11944.4          43 days
  event+45         SUCCESS    43             11944.4          43 days
  event+50         SUCCESS    -49            -13611.1         43 days
  event+90         SUCCESS    -49            -13611.1         43 days
  event+365        SUCCESS    -322           -89444.4         43 days

The flip lands exactly where the trade date passes 20 September.

Scope

event dates across Apr-Dec 2024, settlement lags 0-120 days:
  2250 cases, 1399 (62%) differ from asking on the event date,
  1345 (60%) return a NEGATIVE accrual.

Why High — and why the sign is not the argument

A negative accrual is obviously wrong, and a careful caller might catch it. The real problem is the dependence: the coupon accrued at a credit event cannot depend on when someone asks. Upstream's answer does, and in the window before the sign flips it is wrong without being obviously wrong.

Settlement after a CDS auction routinely lands weeks after the event determination date. A quarterly coupon boundary sits every 13 weeks. The affected regime is not an edge case; it is the ordinary one.

Status in the port

Fixed. One date changed: the period containing the event date is located rather than the one containing the trade date. The period start then precedes the event by construction, the result is always positive, and it no longer varies with the trade date. The arithmetic, the conventions and the trade < event gate are all upstream's, untouched.

A second change follows from the same root cause and is recorded rather than absorbed: upstream fails when the trade date lies past the final accrual end, because no period contains it — even though the event sits inside the schedule and the debt is well defined. Locating by the event date means a late settlement still returns what is owed. Intended, but a divergence rather than a sign fix.

Because this module corrects rather than reproduces, its recorded vectors are the documented intent, each flagged with whether upstream agreed when they were generated: 859 of 1,302 agreed, 443 did not. The differential suite asserts the disagreement still exists, so an upstream fix becomes visible rather than leaving a correction nobody revisits.

UPSTREAM-12

A lunar-month interval computes correctly, then fails

Low · reachable only via a hand-built interval Cannot occur

date_sup.c, inside JpmcdsDateIntervalToYears

Mechanism

case 'U':
    *years = (double)interval->prd *
             (double)JPMCDS_DAYS_PER_LUNAR_MONTH/JPMCDS_DAYS_PER_YEAR;
default:                        /* no break above */
    JpmcdsErrMsg("%s: unknown interval type %c.\n", routine, interval->prd_typ);
    return FAILURE;

Second of its family after UPSTREAM-5.

Evidence

type   rc         years          note
A      SUCCESS    1              annual
M      SUCCESS    0.08333333333  monthly
D      SUCCESS    0.002739726027 daily
U      FAILURE    0.07671232877  LUNAR MONTH
Z      FAILURE    -999           genuinely unknown

28/365 = 0.07671232877  <- what 'U' computes before falling through

The last row is the one that matters. A genuinely unrecognised letter leaves the output untouched at its sentinel; 'U' writes the correct value and then returns FAILURE. The computation ran; only the break is gone.

Reachability, stated precisely

This is low severity for one reason, and the first draft of this entry overstated it before the reachability was measured. JpmcdsMakeDateInterval('U') normalises to 28 days, so an interval built the way callers build one reaches the ACT/365F branch and works. The missing break is reachable only through a hand-constructed TDateInterval.

That is not hypothetical — upstream contemplates it. The switch in JpmcdsDtFwdAny retains code for 'A', 'S' and 'Q' with the comment "left here for people who have set up their own TDateIntervals without calling JpmcdsMakeDateInterval". It extends that courtesy to 'W' and not to 'U', so a hand-built lunar interval is refused by one function and mishandled by the other.

It propagates as far as it can: JpmcdsDateIntervalToFreq and JpmcdsCountDates both consume this function.

Status in the port

Cannot occur. make_date_interval('U') yields {28 × periods, Days}, so no DateInterval ever carries the unit letter the bug keys on, and interval_to_years has two total branches where upstream has eleven partial ones.

The equivalence that makes that safe is checked rather than argued: for every letter the parser accepts, the normalised interval's year fraction is compared bit-for-bit against what upstream computes from an interval built through its own constructor. Normalisation divides numerator and denominator by the same factor — 'Q' with 5 periods becomes 15 months, and 15/12 is exactly 5/4 — so the correctly-rounded quotient is unchanged, across 120 recorded cases.

UPSTREAM-13

A leaked global that disables validation process-wide

Medium · one failed call, permanent effect Cannot occur

lintrp1.inc, expanded as JpmcdsLinInterpLongPoint1Discontinuous

Mechanism

Upstream cannot say "search without checking order" per call, because that choice lives in a mutable global: bSearchCheckOrder_g in bsearch.c, default TRUE, consulted by both JpmcdsBSearchDouble and JpmcdsBSearchLong before validating that their input array is sorted.

The discontinuous interpolator legitimately needs the unchecked search — repeated abscissae are the discontinuities — so it clears the global, checks order itself, searches, and restores it:

checkOrder = JpmcdsBSearchCheckOrder(FALSE);
if (checkOrder)
{
    for (idx = 0; idx < N-1; idx++)
        if (XARRAY(idx) > XARRAY(idx+1))
        {
            JpmcdsErrMsg(...);
            return FAILURE;                     /* leaks */
        }
}
if (SEARCH_ROUTINE_NAME(xDesired, x, xskip, N, &lo, &hi) == FAILURE)
    goto done;                                  /* leaks */
JpmcdsBSearchCheckOrder(checkOrder);            /* only on success */

Both error paths leave before the restore.

Evidence

  baseline:                      JpmcdsBSearchLong(unordered) -> FAILURE (validated)
  one failed call ...            -> FAILURE
  after that single failed call: JpmcdsBSearchLong(unordered) -> SUCCESS  *** VALIDATION IS OFF ***
  current global state:          FALSE (leaked)

Scope

Afterwards, every binary search in the process stops checking that its domain is sorted — including inside the zero curve and the whole CDS pricing path. A binary search over an unsorted array does not fail; it returns a bracket that is simply wrong, and the interpolation built on it is silently wrong too.

Medium rather than high, for reachability rather than consequence: the function has no caller inside the library and no declaration in any public header — but it is an exported symbol and it is in the XLL's surface, so a spreadsheet can reach it.

The clearest statement of the problem is operational: this module's differential suite has to restore the global in TearDown, or one test corrupts every test after it.

Status in the port

Cannot occur. bracket and bracket_checked are two functions and there is no global at all. That was a taste judgement made in the first slice of this port, whose comment read "process-wide state that silently changed the behaviour of every caller". UPSTREAM-13 is that sentence turning out to be literally true — not through explicit toggling, but through a leak.

UPSTREAM-14

Bond metrics return stack garbage before the epoch

Medium · uninitialised read, wrong answer, reports success Cannot occur · port is correct

yearfrac.c — bondDaysDiff / bondEDaysDiff, behind JpmcdsDayCountToMetricFunc

Mechanism

static double bondDaysDiff(double startDate, double endDate)
{
    long days;                                        /* uninitialised */
    (void)JpmcdsDaysDiff((TDate)startDate, (TDate)endDate,
                         JPMCDS_B30_360, &days);
    return ((double)days);                            /* garbage if it failed */
}

The status is discarded. JpmcdsDaysDiff fails for a TDate before the 1601 epoch and does not write its out parameter, so the metric returns whatever was on the stack.

Evidence

DaysDiff(-50  , 100, 30/360) -> FAILURE  days = -123456789 <- OUT PARAM NEVER WRITTEN
DaysDiff(0    , 100, 30/360) -> SUCCESS  days = 100

metric(-50, 100) -> 6101050560          <- uninitialised stack read

interpolate at -50 with the 30/360 metric -> -667794.1351

The curve interpolated is f = {0.01, 0.02}, and JpmcdsLinInterpLongPoint1 reports SUCCESS.

The value is not stable, and that is the point. A second binary built from the same sources gave metric(-50, 100) = 4 and an interpolated −619018.2639. Whatever occupies that stack slot is what the caller gets, so any single figure above is one observation rather than the answer.

Two notes on how it was found

It is an uninitialised read, which AddressSanitizer cannot detect — MemorySanitizer would, and this project does not run one. The sanitizer job is green on it.

And it was found by the golden generator's full cross-product of abscissae against metrics, not by the differential suite, whose sweeps used realistic dates for each metric. A generator that sweeps everything found what targeted sweeps missed.

Status in the port

Cannot occur, and the port additionally diverges by being correct. metric_distance checks the status it is given, so a failure becomes nullopt. In practice the branch rarely fires: std::chrono has no 1601 epoch, so a pre-epoch abscissa is simply a date in 1600 and the 30/360 difference is well defined. The port returns a sensible extrapolation where upstream returns garbage.

The recorded vectors deliberately omit the affected combinations. Recording the output of undefined behaviour would enshrine it — the same rule that kept UPSTREAM-4's buffer overflow out of the vectors.

UPSTREAM-15

A validating constructor that admits unpriceable curves

Medium · a silent NaN where an error belongs Cannot occur

tcurve.c — checkTCurve, reached through JpmcdsMakeTCurve

Mechanism

checkTCurve's stated purpose is "to guarantee we can generate positive discount factors". It checks the day count with JpmcdsDayCountValid, which correctly accepts 30/360 — a thoroughly standard convention — and it accepts an empty curve, since its only size test is fNumItems < 0.

Neither can be priced. JpmcdsZeroPrice routes through JpmcdsConvertCompoundRate, which supports ACT/365F and ACT/360 and rejects everything else explicitly. And JpmcdsZeroPrice returns a bare double, so it has nowhere to report the failure.

Evidence

ACT/365F   construct=accepted  JpmcdsZeroPrice=0.7833167239
30/360     construct=accepted  JpmcdsZeroPrice=nan
30E/360    construct=accepted  JpmcdsZeroPrice=nan
empty      construct=accepted  JpmcdsZeroPrice=nan

So a caller picks a standard day count, a constructor named Make… with an explicit validation pass accepts it, and every discount factor afterwards is NaN. The same problem as UPSTREAM-2 in a different disguise: there is no error channel, so the error becomes a number.

The distinction that matters

Infinity is not part of this finding, and conflating the two would overstate it. A continuous-basis rate of −400 over three years is exp(1200), which overflows to +inf in upstream and in the port alike — both accept the curve and both return the same infinity. That is a value: the answer is enormous. NaN is not a value; here it is an error channel.

Status in the port

Cannot occur. ZeroCurve::create rejects at construction what cannot be priced: a non-empty curve is required, and the day count must be one the conversion supports. That is why create is deliberately stricter than checkTCurve on those two counts, and why zero_price can return a plain double with no NaN sentinel — every curve that exists can be priced.

The guarantee is pinned as a tier-1 property over 810 discount factors drawn from the curves create accepts: never NaN, non-negative, and finite for any rate a market could quote.

And what else was dropped

JpmcdsMakeTCurveNoRateCheck treats a TDate of 0 as an array terminator — "This allows spreadsheet users to select a big range of dates, but use less than the whole range by terminating with a 1 or 0." Measured: five dates with a zero at index 2 produce a curve of two points.

Not reproduced. The port takes a std::span, so the length is explicit and a terminator has nothing to mean — and date 0 is a legitimate date, 1601-01-01, that a span-based caller could reasonably include. The same input is refused outright as out of order rather than silently truncated.

UPSTREAM-16

A failure that leaves the curve modified

Medium · partial mutation on an error path Cannot occur

zcall.c — JpmcdsZCAddGenRate

Mechanism

The function has a short-circuit for the case where the rate is already quoted in the curve's own terms — and then forgets to stop.

if (basis==zc->basis && dayCountConv==zc->dayCountConv)
{
     if (JpmcdsZCAddRate(zc,date,rate) == FAILURE)
         goto done;
}
/* no return -- execution falls through */
if (JpmcdsRateToDiscount(rate, zc->valueDate, date, dayCountConv, basis, &df) == FAILURE)
    goto done;
if (JpmcdsZCAddDiscountFactor(zc,date,df) == FAILURE)
    goto done;

So the matching case adds the point, and then adds it again by a second route.

Why it is usually harmless

The duplicate check inside JpmcdsZCAddRateAndDiscount sees the same date, compares the rate against the stored one within a hardcoded 1e-7, and returns success having done nothing. The second route's rate has survived a round trip through a discount factor, so it lands well inside that window. Wasted work, not a wrong answer.

Why it is not always harmless

A date equal to the curve's value date makes the second route fail — JpmcdsDiscountToRate rejects a zero-length period. The function returns FAILURE, after the first route has already committed the point.

date == valueDate : rc=FAILURE  numItems=1   *** curve MUTATED ***
   orphaned point: date=154497 rate=0.05 discount=1

A caller that discards the curve on failure is unaffected. One that retries, or inspects the error and carries on, now holds a point it never successfully added — and numItems says it is there.

Status in the port

Cannot occur. add_general_rate returns after the matching case, which is what the missing return would have done. That removes the duplicated work as well, and a rate at the value date now simply succeeds — a rate over no time discounts by nothing, which is a perfectly good point. The only reason upstream failed was the redundant second route.

The general guarantee is stronger than the one fix: every route into the builder commits only after all of its conversions have succeeded, so no failure anywhere can leave a point behind. That is asserted as a tier-1 property rather than inferred from the code.

Reproduce: ./build/debug/defect_evidence u16
UPSTREAM-17

An optimisation that changes the answer at its boundary

Medium · an infinity stored in the curve, reported as success Cannot occur

zcall.c — JpmcdsZCComputeDiscount

Mechanism

A fast path for the common case, which its own comment calls "a special optimization":

if (zc->basis == 1              &&
    rate      >= -1.0           &&
    date      >= zc->valueDate  &&
    (zc->dayCountConv == JPMCDS_ACT_365F || zc->dayCountConv == JPMCDS_ACT_360))
{
    *discount = pow(1+rate, (zc->valueDate - date) / ...);
    return SUCCESS;
}

At exactly -1.0 the base is zero and the exponent negative, so pow returns an infinity — while the general path this stands in for rejects the same input, because JpmcdsRateToDiscountYearFrac refuses a base at or below zero.

Evidence

rate         ZCComputeDiscount          JpmcdsRateToDiscount
-0.9999999   1.0923357970930543e+56     1.0923357970930543e+56
-1.0         inf                        FAILURE
-1.5         FAILURE                    FAILURE

And the infinity is not merely returned — it is stored, and then served:

JpmcdsZCAddRate(curve, date, -1.0) -> SUCCESS
  stored: date=157419 rate=-1 discount=inf
  JpmcdsZCDiscountFactor at that date -> SUCCESS  inf

Two code paths for one quantity, disagreeing at the boundary, and the fast one wins because it is tested first. The guard wants rate > -1.0.

The distinction that matters

This is the mirror image of the infinity in UPSTREAM-15, and the difference is the whole point. There, exp(1200) overflowing to +inf is a value — the answer really is enormous, and the port returns the same thing. Here, the general path is on record as calling the same input an error; the fast path answers inf only because it was written without that case in mind.

Status in the port

Cannot occur. The fast path is reproduced — it is not purely an optimisation, since (valueDate - date)/365.0 and -1.0 * ((date - valueDate)/365.0) are the same double only because negation is exact — but it is taken only where it agrees with the general path, so the boundary case falls through and is refused.

Pinned from both sides: one test asserts the two paths return bit-identical factors for every rate inside the boundary, another that nothing infinite can be stored. ZeroCurve::create would refuse rate <= -basis downstream in any case — that was PORT-11 — so the curve is protected twice over.

Reproduce: ./build/debug/defect_evidence u17
UPSTREAM-18

An error that is logged, then reported as success

Medium · a fabricated answer with a success status Cannot occur

zcall.c — JpmcdsZCFwdDiscountFactor

Mechanism

*discount = 1.0;
if (discount1<=0.0)                 /* bad discount factor */
{
    JpmcdsErrMsg("JpmcdsZCFwdDiscountFactor: bad discount at start of fwd\n");
}
else
{
    *discount = discount2 / discount1;
}

return SUCCESS;

There is no missing error channel here. The function returns int, every caller checks it, and the condition is detected well enough to write a message about. The status simply does not match what the function found.

And 1.0 is the worst available stand-in: a forward discount factor of 1.0 means no discounting over this period, so JpmcdsZCForwardRate converts it into a forward rate of exactly zero.

Evidence

Reachable by underflow. Continuous basis, a 30-year point, sweeping the rate:

rate=20   df1=1.70976e-261  fwd=2.06115e-09  fwd rate=4.85165e+08
rate=23   df1=1.31182e-300  fwd=1.02619e-10  fwd rate=9.7448e+09
rate=24   df1=1.20094e-313  fwd=4.11398e-11  fwd rate=2.43073e+10   <- subnormal
rate=25   df1=0             fwd=1            fwd rate=0
rate=30   df1=0             fwd=1            fwd rate=0

The direction of travel

As the input deteriorates the output stops looking wrong. 2.4e10 is visibly nonsense and any sanity check would catch it; 0 is not. The failure mode improves in appearance exactly as the situation gets worse, which is the opposite of what a monitor needs.

The defect is also basis-specific. Annual compounding never reaches it — (1+r)-t decays polynomially in r, so even 10,000% over 30 years gives 6.7e-61, nowhere near underflow. Continuous compounding decays exponentially and crosses the cliff at a rate of about 24.

A 2500% continuous rate is not a market quote. It is what a diverged bootstrap produces — precisely the moment a caller needs the failure reported rather than smoothed over.

Status in the port

Cannot occur. forward_discount_factor returns nullopt where upstream fabricates. The underflow itself is reproduced exactly: the port returns the same zero discount factor, because that part is arithmetic and not a defect. Only the fabricated forward is refused.

Reproduce: ./build/debug/defect_evidence u18
UPSTREAM-19

The guard against a bad discount factor cannot see NaN

Medium · a NaN rate returned as success Cannot occur

zcall.c — JpmcdsZCForwardRate; cfinanci.cpp — JpmcdsDiscountToRate

Mechanism

if (discount<=0.0)                  /* bad discount factor */
{
    JpmcdsErrMsg("JpmcdsZCForwardRate: bad discount for forward\n");
    return FAILURE;
}

NaN <= 0.0 is false. The one check whose entire job is to stop an unusable discount factor is written as the one comparison every NaN passes. The NaN goes into JpmcdsDiscountToRate, which guards the same way, and comes back out as a NaN rate with a SUCCESS status.

Where the NaN comes from, and why that matters

Continuous basis, a 30-year horizon, a large negative rate overflows the discount factor:

rate=-20   df1=5.84877e+260  df2=2.83762e+269  fwd=4.85165e+08  rate=-1
rate=-23   df1=7.62298e+299  df2=inf           fwd=inf          rate=-1
rate=-24   df1=inf           df2=inf           fwd=nan          rate=nan
rate=-100  df1=inf           df2=inf           fwd=nan          rate=nan

Both discount factors are legitimately infinite. That is the same overflow UPSTREAM-15 concluded is a value and not a finding, since the answer really is that large — and the port returns the same infinities. The defect is downstream of it: the ratio of two infinities is indeterminate, and nothing stops the result.

So the lineage is UPSTREAM-15's accepted infinity feeding UPSTREAM-19's blind guard — the same relationship UPSTREAM-9 has with UPSTREAM-10, where one supplies the bad input and the other fails to contain it.

Status in the port

Cannot occur. forward_discount_factor rejects any non-finite result, and discount_to_rate was tightened to !(discount > 0.0) || !std::isfinite(discount) — upstream's guard written so that it means what it was for.

Fixed at the conversion rather than at each caller, because a NaN discount factor is not a rate no matter who asks. The tier-1 property is the general form: across every basis, day count and rate in the sweep, no evaluation returns NaN. Infinity is still permitted, since UPSTREAM-15 settled that it is a value.

A second site: JpmcdsForwardFromZCurve

The same defect is reachable from zr2fwd.c, where there is no guard at all:

forwardDiscount = endDiscount/startDiscount;

if (JpmcdsDiscountToRate(forwardDiscount, startDate, endDate,
                      dayCountConv, basis, rate) == FAILURE)

Strictly less protection than JpmcdsZCFwdDiscountFactor, where at least if (discount1 <= 0.0) is tested — badly (UPSTREAM-18), but tested. Measured, continuous basis over 30 years:

rate   disc(start)     disc(end)       fwd disc   rc        forward rate
0.03   0.406302        0.394294        0.970446   SUCCESS   0.0304545
24     1.20094e-313    4.94066e-324    4.11e-11   SUCCESS   2.43073e+10
25     0               0               nan        SUCCESS   nan
-24    inf             inf             nan        SUCCESS   nan

Both ends of the range produce a NaN rate reported as success: 0/0 where the factors underflow, inf/inf where they overflow.

Recorded here rather than as a separate entry. Same mechanism, same consequence, and the fix was the same one line in discount_to_rate — the port needed no new work to be immune at this site. A separate number would make the register count entry points rather than defects.

Reproduce: ./build/debug/defect_evidence u19
UPSTREAM-20

The precondition the documentation does not mention

Low · reachable only through the public header Cannot occur

cashflow.c — JpmcdsMergeCFL

Mechanism

The header states the contract in one sentence:

Merges two cash flow lists. The input cash flow lists cannot be NULL.

That precondition is real, and it is checked — on both arguments. The other one is not stated and not checked. The algorithm is a single forward pass that advances whichever side carries the earlier date, so it is a merge only if both inputs are already ordered by date.

Evidence

With a = [40000, 20000, 30000] and b = [25000, 15000]:

MergeCFL -> fNumItems=5
    [0] date=25000  amount=10
    [1] date=15000  amount=20
    [2] date=40000  amount=1
    [3] date=20000  amount=2
    [4] date=30000  amount=3

Every element is present, so nothing is lost — but the output is not sorted, and it is not a stable interleaving of the inputs either. It is an artefact of where the comparison happened to stop. A caller who reads the header, satisfies the one documented precondition and passes lists in whatever order they arrived has no way to learn the result is meaningless.

Why the severity is low

Exactly one call site exists in the library — zcswap.c:804, merging a fixed and a floating schedule, both generated in date order. So this is unreachable from inside upstream and reachable only by an external caller of the public header, which is the same tier as UPSTREAM-12.

Status in the port

Cannot occur. merge_cash_flows returns nullopt unless both inputs are ordered. Checking a precondition the documentation forgot is the move ZeroCurve::create makes over checkTCurve (UPSTREAM-15): refuse at the boundary what cannot produce a meaningful answer, so the result type never has to carry a "this is nonsense" value.

Non-decreasing, not strictly increasing — a list may legitimately carry two payments on one date, and upstream's merge passes such a pair through uncoalesced. Both forms represent the same cash flow, so neither is wrong.

And the finding this is not

The first hypothesis in this file was different, and it was wrong. JpmcdsNewEmptyCFL sets fNumItems to the count it was asked for and allocates through JpmcdsMallocSafe, whose allocation line reads:

ptr = malloc(theSize);              /* Don't use calloc due to RS6000. */

On that line alone, a public function named "NewEmpty" returns n cash flows of heap garbage. Four probes said otherwise — a size-matched recycled block, MallocPreScribble=1, and an ASan build all came back zeroed — and the reason is the next branch of the same function:

/* Clear out the memory for safety. */
(void)memset((char *)ptr, (size_t)0, theSize);

The comment about calloc means "we reproduce calloc by hand", not "we skip the zeroing". No defect — and the negative result is worth more than the finding would have been: every NEW and NEW_ARRAY in the library returns zeroed memory, so upstream cannot have an uninitialised-heap read anywhere. The one uninitialised read in this register, UPSTREAM-14, is a stack local — where no allocator intervenes.

One detail does deserve recording. fDate = 0 is not a null in upstream's encoding; TDate 0 is 1601-01-01, a date like any other. A list from JpmcdsNewEmptyCFL(n) that a caller under-fills does not look uninitialised — it looks like n deliberate payments of zero in 1601. Garbage might be caught downstream; that will not be.

Reproduce: ./build/debug/defect_evidence u20
UPSTREAM-21

The error path dereferences a null pointer

Medium · deterministic SIGSEGV, in the error handler Cannot occur

zcall.c — JpmcdsZCAddCashFlowList

Mechanism

Two reads of the last element, neither guarded:

if (date==0L)                       /* add at last c.f. if not set up */
{
    date = cfl->fArray[ cfl->fNumItems-1].fDate;
}
...
done:
    if (status == FAILURE)
        JpmcdsErrMsg("%s: Failed for CFL maturing %s.\n", routine,
                     JpmcdsFormatDate(cfl->fArray[cfl->fNumItems-1].fDate));

JpmcdsNewEmptyCFL(0) — a public constructor — returns fNumItems = 0 with fArray = NULL, so both reads are NULL[-1].

Evidence

empty CFL: fNumItems=0 fArray=0x0
calling with date=0 ...
exit status: 139          (SIGSEGV)

explicit date, empty CFL -> exit status: 139

The second measurement is the one that matters. Given an explicit date the first read is skipped, and the function reaches its own "no cash flows in list beyond ZeroCurve. Therefore, nothing to add." branch — the error is detected, the branch is written, the message is composed — and then done: dereferences the empty list while formatting it.

The diagnostic path for an empty list is the one path that cannot survive an empty list. There is no way for a caller to receive the error this function was written to report.

Status in the port

Cannot occur. An empty span is refused before anything reads from it, and nothing formats a payment that is not there. The live reproducer is a DISABLED_ test — it takes the process with it — the same arrangement UPSTREAM-4 and UPSTREAM-9 use.

Reproduce: ./build/debug/defect_evidence u21 --unsafe
UPSTREAM-22

Success with nothing added

Medium · an instrument reported as bootstrapped that was not Cannot occur

zcall.c — JpmcdsZCAddCashFlowList

Mechanism

When the final payment falls exactly on the curve's last date, every branch declines in turn:

Evidence

A 3-point curve ending 2027-01-01, a list ending on that same date, asked to add a point at 2030-01-01:

rc=SUCCESS   numItems 3 -> 3   point at 2030 present? NO

The caller is told the instrument was bootstrapped. The curve does not contain the date it asked for, and no rate was solved for anything. The next instrument then bootstraps against a curve one point shorter than the caller believes, which is how a silent no-op becomes a wrong curve rather than a missing point.

Status in the port

Cannot occur. add_cash_flow_list returns false when there is nothing uncovered to solve for. If no rate was found, the instrument was not added, and saying so is the only honest answer.

Reproduce: ./build/debug/defect_evidence u22
UPSTREAM-23

A sign test that silently drops curve points

Low · no pricing consequence found, having looked for one Not reproduced

zcall.c — JpmcdsZCAddCFLPoints

Mechanism

if (rate >= 0.0)
{
    dates[n] = d;
    rates[n++] = rate;
}

No else, no message, no status. A cash flow date whose interpolated rate is negative is not added — in a function whose own comment is "Ensure all uncovered cash flow dates in curve. ... This will make sure they can be priced appropriately by the curve."

Evidence

A five-payment zero-coupon bond over a curve at −0.5%, varying only the price:

price=0.97  solved rate +0.0044     dates placed 2 of 5
price=1.00  solved rate −2.2e-13    dates placed 1 of 5
price=1.06  solved rate −0.0083     dates placed 1 of 5
price=1.20  solved rate −0.0257     dates placed 1 of 5

The cliff is at exactly zero. A solved rate of −2e-13 drops four points that a rate of +2e-13 would have kept, so the curve's shape turns on the sign of a number that is, at that magnitude, noise.

Negative zero rates are not exotic — EUR, CHF and JPY curves were negative for most of a decade after 2014 — so this is reachable from ordinary market data rather than from a pathological input.

What it does not do, having tried to show that it does

The expected consequence was a broken bootstrap: points missing means the instrument no longer reprices to its own input. It does not. Measured under linear interpolation and under flat forwards, with 1 of 5 dates placed, the instrument still reprices to within the solver's f-tolerance:

NEGATIVE curve, price>par     dates placed 1/5   input 1.040000 -> 1.0400000000
NEGATIVE curve, deep premium  dates placed 1/5   input 1.080000 -> 1.0800000000

Inserting a point at its own interpolated rate is idempotent for both schemes. Linear interpolation puts the new point exactly on the line; flat forwards is log-linear in the discount factor, which puts it exactly on that curve. Splitting an interval at a point already on the path leaves the path alone.

So the finding is about data, not prices: a caller who inspects the finished curve sees a different number of points depending on the sign of the rates, for no documented reason.

Status in the port

The port reproduces no filter at all — every missing date gets its interpolated rate, which is what the comment describes. The divergence is recorded as data rather than prose: the golden vectors carry the exact dates upstream dropped, and the replay asserts that the port's curve differs from upstream's by exactly those dates and nothing else. Twelve of the sixty recorded bootstraps diverge this way, and that count is asserted too, so a change in upstream's behaviour surfaces as a failure rather than as fewer checks.

Reproduce: ./build/debug/defect_evidence u23
UPSTREAM-24

The roll date is consulted in the opposite case to the one documented

Low · a schedule generated from the wrong end, in a one-day window Reproduced deliberately

datelist.c — JpmcdsNewDateListExtendedRoll

Mechanism

The header states the rule:

If rollDate is non-zero and stubAtEnd is False, then the rollDate is used to generate cash flow dates. First starting from roll-date we see if we can count forward an integral number of intervals to the maturity date. If this is so then we can generate our datelist by counting forward from the rolldate.

The code tests something else:

if (JpmcdsCountDates(startDate, maturityDate, interval, &numIntervals, &extraDays) != SUCCESS)
    goto done;

if (extraDays == 0)
{
    /* We can use the roll date - so we count forward from this day */

startDate to maturity, not rollDate to maturity. The difference inverts the feature:

Evidence

Quarterly, roll 2024-01-15, maturity 2027-01-15 (exactly twelve quarters from the roll), start 2024-02-20 — the case the documentation describes:

roll  -> mat   intervals=12  extraDays=0     INTEGRAL
start -> mat   intervals=11  extraDays=56    has a stub

with the roll date   n=13: 154511 154602 ... 155607
with rollDate = 0    n=13: 154511 154602 ... 155607
=> the roll date CHANGED NOTHING

Reachability, and a claim withdrawn

The library's only call site is cashflow.c:230, which passes startDate as the roll date. The obvious reading is that this makes the mechanism inert: count_dates(roll, start) is trivially integral when the two are equal. Three hand-picked probes agreed, and the first draft of this record said so.

The exhaustive sweep found the counterexample. The roll branch ends in NewDateListExtended(first, maturity, interval, TRUE) — generating forward from the start — where rollDate = 0 generates backward from maturity. Those agree only where month arithmetic does not clamp, and clamping is not invertible: 29 February plus twelve months is 28 February, but 28 February minus twelve months is 28 February, not the 29th.

2024-02-29  2027-02-28  iv=1   DIFFER: first 154556 vs 154555, n=37 vs 37
2024-02-29  2027-02-28  iv=3   DIFFER: first 154556 vs 154555, n=13 vs 13
...
7 of 378 integral-span cases differ (1.9%)

Every one starts on 29 February. So this is reachable from inside upstream — a leap-day start whose maturity falls on the clamped day gets a forward-generated schedule where a back-stub request asked for a backward one. Still low severity, because the window is that narrow and the schedules differ by a day at one end rather than in length. But "inert" was wrong, and only the sweep found it.

Status in the port — reproduced, deliberately

Unlike the date-list set operations, which correct upstream, this module does not. The policy permits a correction where there is no single upstream behaviour to preserve — UPSTREAM-7, where two implementations contradicted each other and the header. That is not the situation here: the code is self-consistent and deterministic, and only the documentation disagrees with it.

A roll date decides coupon dates, coupon dates decide accrual, and accrual decides money. Reinterpreting a roll-date convention on the strength of a comment is not a porting decision. PORT-9 is the standing reminder of what happens when a porter picks a winner between two disagreeing sources; this is the same hazard with the sources swapped.

The behaviour is reproduced and the disagreement is pinned by a test that asserts the roll date is inert in the documented case, effective in the undocumented one, and that every roll == start difference involves a 29 February start.

Reproduce: ./build/debug/defect_evidence u24
UPSTREAM-25

A heap buffer overflow on a one-date schedule

Medium · out of bounds in both directions, plus a latent write Cannot occur

cashflow.c — JpmcdsNewCFLFromDL3

Mechanism

The function detects a stub by comparing the instrument's dates against the grid it was handed:

frontStub = ( startDate    > dates->fArray[0] );
backStub  = ( maturityDate < dates->fArray[numDates-1] );

Neither branch checks that the grid is long enough to have a surrounding period. With numDates == 1 the front branch indexes past the end:

JpmcdsStubPayment(accrualDates->fArray[0],
                  accrualDates->fArray[1],      /* index 1 of a 1-element list */
                  accrualStart,
                  accrualDates->fArray[1],
                  rate, couponDayCountConv,
                  &cfl->fArray[1].fAmount)      /* WRITE past a 1-element array */

and the back branch indexes before it, accrualDates->fArray[numDates-2] being fArray[-1].

Evidence

front stub: ERROR: AddressSanitizer: heap-buffer-overflow on address 0x...0f8
            READ of size 8    #0 JpmcdsNewCFLFromDL3
            allocated by      #2 JpmcdsNewEmptyDateList

back stub:  ERROR: AddressSanitizer: heap-buffer-overflow on address 0x...0e8
            READ of size 8    #0 JpmcdsNewCFLFromDL3

Note the two addresses: …0f8 is past the one-element allocation and …0e8 is before it. Both directions are real.

In the unsanitised build the front case happens to return NULL — the garbage it read as nextCouponDate failed JpmcdsStubPayment's prevCouponDate >= nextCouponDate check. That is luck, not safety. A garbage value on the other side of that comparison lets the function proceed to the out-of-bounds write, which ASan never gets to report because it aborts on the read first.

Reachability

JpmcdsMakeCFL builds its own grid, and JpmcdsNewDateListExtended never returns a single date together with a stub — it anchors the grid on whichever end the stub is not at, so one of the two comparisons is always false. Measured:

stubAtEnd=0: first=154261 last=155722 -> frontStub=1 backStub=0
stubAtEnd=1: first=154547 last=156008 -> frontStub=0 backStub=1

But JpmcdsNewCFLFromDL3 is declared in cashflow.h and takes the grid as an argument, so a caller supplying its own date list reaches it directly. That is why this is medium rather than high: unreachable from inside upstream, reachable from outside it.

Status in the port

Cannot occur. The grid arrives as a std::span, and a grid shorter than two dates is refused when a stub was detected. There is nothing to compute: a stub payment needs the period surrounding it, and a one-date grid has none.

The live reproducer is a DISABLED_ test — ASan aborts the process — the arrangement UPSTREAM-4, UPSTREAM-9 and UPSTREAM-21 already use.

A second finding in the same function, not filed

The long-stub coalescing block runs two branches in sequence, and the first reassigns the pointer the second reads from:

if ( frontStub )
{
    datesCopy->fArray[0] = dates->fArray[0];
    memcpy(&datesCopy->fArray[1], &dates->fArray[2], (numDates - 2) * sizeof(TDate));
    dates = datesCopy;          /* simply overwrite pointer, hiding original */
    --numDates;
}
if (backStub)
{
    memcpy(&datesCopy->fArray[0], &dates->fArray[0], (numDates - 2) * sizeof(TDate));

With both stubs present, dates == datesCopy by the time the second memcpy runs, so source and destination are the same pointer. C11 7.24.1p2 makes copying between overlapping objects undefined, and identical objects overlap.

Not filed as a defect. The result is correct — five grid dates coalesce to three flows, as intended — and no implementation mishandles memcpy(p, p, n). Recorded because a compiler entitled to assume restrict on those parameters would be within its rights to make it stop working.

Worth noting for the harness rather than for upstream: neither AddressSanitizer nor UndefinedBehaviorSanitizer reports it. The project already records that ASan cannot see uninitialised reads; this is a second class it cannot see, in the same function where it caught the overflow above.

Reproduce: ./build/debug/defect_evidence u25 --unsafe
UPSTREAM-26

A substitution table silently disables the convention

Low · the documented purpose, not the code Reproduced; the signature is what the port fixes

zcswdate.c — JpmcdsZCAdjustDate

Mechanism

The function branches on the presence of a list, not its contents:

if (badDayList != NULL)
{
    *adjDate = JpmcdsBad2GoodBadDayList(badDayList, date);
    return SUCCESS;
}
else
{
    if (JpmcdsBusinessDay(date, badDayConv, holidayFile, adjDate) == FAILURE)
        goto done;
}

So when a list is supplied, badDayConv and holidayFile are never consulted — and JpmcdsBad2GoodBadDayList returns its input unchanged for any date the list does not contain. The function is documented as "Adjusts date to fall on a business day, if necesssary". On that path it does not.

Evidence

input                                    adjusted to
Saturday, no list, conv=F                154504   (moved to Monday)
Saturday, in the list, conv=F            154504   (from the list)
another Saturday, no list, conv=F        154511   (moved)
another Saturday, list given, conv=F     154509   <- STILL A SATURDAY

An empty list does it to every date, because the test is on the pointer rather than on count:

no list (NULL),   conv=F -> 154504
EMPTY list,       conv=F -> 154502   <- unchanged, still a Saturday

Status in the port — reproduced, with the signature fixed

The two modes are evidently intended as alternatives: a caller supplies either a complete substitution table or a convention, and a table that omits a bad day is incomplete, which is the caller's business. What is wrong is the documented purpose, not the code.

So the port reproduces the behaviour and fixes the signature instead. zc_adjust_date takes std::optional<std::span<const BadDayPair>>, which says "either a table or the convention" where upstream's two unrelated parameters say "both".

That measurement is also why the parameter is an optional rather than a plain span. "No table" and "a table with nothing in it" are genuinely different inputs with different results, and a span alone would have merged them — silently changing what an empty table means. This is the one case so far where a parameter had to be less convenient to stay faithful.

Reproduce: ./build/debug/defect_evidence u26
UPSTREAM-27

A day-of-month heuristic that suppresses real cycles

Low · a wrong flag in 8% of month-end cases, a date off by one in 2% of those Reproduced deliberately

zcswdate.c — SetPrevDateAndOnCycle

Mechanism

if ((valueMDY.day <= 28) && (origMDY.day <= 28))
{
    /*
     * We assume we can only be on cycle if date is not on or after
     * the 29th of the month.
     */
    JpmcdsCountDates(valueDate, origDate, &interval, &numIntervals, &extraDays);
    *onCycle = (extraDays == 0);
}
else
{
    *onCycle = FALSE;
}

The assumption is false:

day 29: CountDates says extraDays=0   so genuinely ON cycle; heuristic says OFF
day 30: CountDates says extraDays=0   so genuinely ON cycle; heuristic says OFF
day 31: CountDates says extraDays=0   so genuinely ON cycle; heuristic says OFF

Two consequences

The reported flag is wrong for those dates — swept over every month, the days 26 to 31 and four frequencies, the heuristic suppresses 600 of 7,296 genuinely on-cycle combinations.

And because the flag chooses how previous is computed — forward from the value date when on cycle, backward from the maturity when not — the suppression can change the date:

freq=1   2024-02-29 -> 2025-02-28 : on-cycle 154556, off-cycle 154555  DIFFER by 1
freq=2   2024-02-29 -> 2027-02-28 : on-cycle 155468, off-cycle 155467  DIFFER by 1
...
14 of the 600 give a different previous coupon date (2.3%)

Every one has a 29 February value date — the same clamping asymmetry as UPSTREAM-24, where forward from the 29th and backward from the 28th do not meet because month arithmetic is not invertible.

Worth being precise about which answer is which. In the annual case the forward route is valueDate + 0 intervals, the value date itself, which is by definition on the schedule. The backward route gives the day before it — a date the schedule does not contain. So on these fourteen the heuristic does not merely lose precision; it picks the route that returns a date that is not a coupon date.

Status in the port — reproduced, deliberately

Deciding that a swap's previous coupon date should move by a day is a convention question, not a porting one. Same reasoning as UPSTREAM-24, same conclusion.

The heuristic is pinned from both sides: one test asserts that an on_cycle flag of true really does mean a whole number of intervals — checked against count_dates, not against upstream — and another asserts that a false flag does not imply the converse, which is this defect stated as a property.

One thing the port did not need to reproduce: numIntervals is declared uninitialised and read only in the on-cycle branch. That is safe, because the flag can only be true where JpmcdsCountDates has just set it — but the safety is an argument about control flow rather than a property of the code, which is exactly the shape UPSTREAM-14 is. Here the argument happens to hold.

Reproduce: ./build/debug/defect_evidence u27
UPSTREAM-28

A process-wide flag left disabled on the success paths

Medium · validation silently off, process-wide, permanently Cannot occur

interpc.c — JpmcdsInterpRateExact

Mechanism

The function opens by disabling the binary search's order checking, saving the previous value to restore later:

/*
** Since we are using the general interpolation functions, but we
** know that the TCurve should have been constructed properly,
** we will turn off order checking in the binary search routines.
**
** This might well produce a dramatic improvement in all the ALIB
** zero curve analytics!
*/
TBoolean checkOrder = JpmcdsBSearchCheckOrder (FALSE);

and restores it at the done: label:

done:
    /* Re-set the global check order flag. */
    JpmcdsBSearchCheckOrder (checkOrder);

Between those two points sit two return SUCCESS statements — the clamps for a date past the end of the curve and a date before its start:

if (desiredDate > curve->fArray[curveLen-1].fDate)
{
    *rate = curve->fArray[curveLen-1].fRate;
    return SUCCESS;                       /* bypasses done: */
}
else if (desiredDate < curve->fArray[0].fDate)
{
    *rate = curve->fArray[0].fRate;
    return SUCCESS;                       /* bypasses done: */
}

Evidence

after calling with...                        order checking
(initial state)                              ON
a date inside the curve                      ON
a date AFTER the curve (extrapolation)       OFF  <- LEAKED
a date BEFORE the curve (extrapolation)      OFF  <- LEAKED
an empty curve (an error path)                ON

And the consequence, in two calls:

order checking ON : JpmcdsBSearchDouble(unsorted) -> FAILURE
after one extrapolation: same call               -> SUCCESS  <- no longer validated

An unsorted array that the checked search correctly rejected now passes. The precondition those functions exist to verify is simply no longer verified, anywhere in the process, for the rest of its life.

Its relationship to UPSTREAM-13

Same global, same failure mode, inverted reachability. UPSTREAM-13 leaks bSearchCheckOrder_g on two error paths in lintrp1.inc. This leaks it on two success paths, and extrapolating off the end of a curve is ordinary use rather than a fault — a swap maturing beyond the last curve point hits it on every valuation.

Note the last row of the measurement: here the genuine error path reaches done: and restores correctly, the exact opposite of UPSTREAM-13. Two functions share one global and leak it under complementary conditions, so between them there is no state of the program in which the flag can be trusted.

The comment is worth keeping too. The mechanism was introduced as a performance speculation — "This might well produce a dramatic improvement in all the ALIB zero curve analytics!" — and the speculation is what created the leak. The optimisation it describes is to skip a validation; the bug is that it skips it for everyone, forever.

Status in the port

Cannot occur, structurally rather than carefully: there is no global. bracket and bracket_checked are separate functions and the caller picks which to use, which is the decision recorded in bsearch.hpp when UPSTREAM-13 was filed. A flag that does not exist cannot be left in the wrong state.

So one decision has now pre-empted two defects, in two files, found two slices apart. That is the argument for removing mutable global state rather than auditing its users: the second defect needed no new work to be immune to.

The differential test resets the flag in SetUp and TearDown, because the function under test leaks it — without that, test order would decide what the checked searches do for every other test in the binary.

Reproduce: ./build/debug/defect_evidence u28
UPSTREAM-38

Three bytes lowercased however short the token is

High · stack buffer overflow, read and write Cannot occur

convert.c:395 — NStringToMonth, from JpmcdsStringToDate

Mechanism

The month-name helper lowercases a token's first three characters and compares them against three-letter names:

cp[0] = (char) tolower(cp[0]);
cp[1] = (char) tolower(cp[1]);
cp[2] = (char) tolower(cp[2]);   /* convert.c:395 */

No length check precedes them, and they are read-modify-writes, not reads. A one-character token has its NUL at cp[1] — still inside the buffer — and nothing at all at cp[2].

Three facts have to line up for that to leave the buffer, and all three are reachable through the public JpmcdsStringToDate: the input is copied into a 32-byte stack buffer, so a token can end at the buffer's end; the second token only reaches this helper when it fails to parse as an integer, so it must be non-numeric; and the first token must therefore be long enough to push the second to offset 30. A 29-digit run and a one-letter month does it.

ERROR: AddressSanitizer: stack-buffer-overflow
    #0 NStringToMonth convert.c:395
    #1 JpmcdsStringToDate convert.c:119
  [32, 64) 'dateCopy' (line 45)
  <== Memory access at offset 64 overflows this variable

ASan reports a READ because the read inside tolower(cp[2]) happens first; the store that follows is to the same byte.

The precondition, measured where it is safe

Short tokens placed near the start of the buffer, where the third byte is still inside it, are all refused — but refused after the three writes have already happened. Only the three-character token can match, so every call with a token of any other length writes three bytes for nothing.

j-15-2024      refused
ja-15-2024     refused
jan-15-2024    accepted
janu-15-2024   refused

Why the pair is the finding

This is the second stack overflow in convert.c, 225 lines from UPSTREAM-4, and together they say something neither says alone. UPSTREAM-4 is an unbounded copy into a buffer. This one is a bounded copy — the strncpy is correct, the NUL is placed by hand, and truncation is exactly why over-long input is accepted rather than refused — followed by an unchecked read past the result.

The bound on the copy bought nothing, because the overflow is downstream of it. Getting the memcpy right is not the same as being safe.

In the port

Cannot occur. The token is a string_view and to_month_name refuses any size but 3 before reading a character. The lowercasing writes into a local three-byte array, so the port also does not mutate the string it was asked to parse — which upstream does, unannounced, to a char * parameter.

reproducer: DISABLED_Upstream38ShortTokenAtTheBufferEndOverflows  ·  trace: ./build/asan/defect_evidence u38 --unsafe

UPSTREAM-41

The upper-cased copy nobody reads

High · a silently wrong holiday calendar Corrected — the second correction in the project

buscache.c:519 and :574 — JpmcdsHolidayListRead

Mechanism

The function declares a buffer for an upper-cased copy of each line, fills it, and then compares the original:

char       buffer[MAX_BUFFER];    /* line of text from file  */
char       ucBuffer[MAX_BUFFER];  /* upper case line  <- 519 */
...
    COPY_CAPITALIZE(ucBuffer, buffer, MAX_BUFFER-1);       /* 574 */
    if (strncmp (buffer, monString, sizeof(monString)-1) == 0)
        weekends |= JPMCDS_WEEKEND_MONDAY;

ucBuffer is written once and never read — its only two mentions in the file are its declaration and that one assignment. All seven directive comparisons use buffer. So the weekend directives are case-sensitive, while the dead code exists for no purpose other than to make them case-insensitive. The intent is unmistakable and the effect is absent.

Measured

Two holiday files, differing only in the case of the directive:

# SATURDAY_NOT_ALWAYS_HOLIDAY   -> Saturday 2024-03-16 is a business day
# saturday_not_always_holiday   -> Saturday 2024-03-16 is a holiday

Both files load. Neither produces a diagnostic. A user who wrote the directive in lower case gets standard weekends, and every date the model adjusts — every coupon date, every accrual boundary, every settlement — is silently wrong.

This is the shape of defect this register treats most seriously: not a crash, but a confident wrong answer from input nobody would suspect.

Two more things in the same macro, neither filed

toupper on a plain char is undefined for the high-bit bytes — UPSTREAM-35's mechanism, already filed, here executed in code whose result is discarded.

And a predicted off-by-one, refuted. The loop continues while the offset is <= len, so the terminator appears to land one past the end. Tested with a 300-character comment line under ASan: nothing happens. JpmcdsFgets reads at most MAX_BUFFER-1 characters, so the source is never long enough to push the terminator past the last valid index. The macro is unsafe if called with a longer source; at this one call site the caller's bound protects it. Recorded because the prediction was wrong, and the reason — the bound lives in the caller, not the macro — is the useful part.

In the port

Corrected, and the reasoning differs from UPSTREAM-39's. Upstream's behaviour here is unambiguous: buffer is always what gets compared, so there is one behaviour and the standing rule says reproduce it. The dead buffer is evidence of intent, not of a second behaviour.

But reproducing it means reproducing a silently wrong calendar. So a comment that case-insensitively matches a directive but is not exactly it is refused, quoting the line:

line 1: "# saturday_not_always_holiday" looks like the directive
# SATURDAY_NOT_ALWAYS_HOLIDAY but the spelling must match exactly,
including case. Upstream would ignore this line without saying so.

That reproduces nothing silently and accepts nothing upstream rejects. The differential test asserts both sides, so an upstream release that fixes this fails the test and tells us to revisit the refusal rather than letting the divergence become invisible.

reproducer: H3UpstreamIgnoresALowerCaseDirectiveAndWeRefuseIt

UPSTREAM-39

An unparseable year is invented, not refused

High · silent wrong answer from untrusted input Corrected — the only correction in the port

convert.c:124 — JpmcdsStringToDate

Mechanism

The function reads three delimited tokens. The month and the day are parsed with a call whose return value is checked:

if (JpmcdsSscanf(cp,"%ld",&mdy.month) == 0)  /* If not integer try string */
{
    if (NStringToMonth(cp,&mdy.month) == FAILURE)
        goto done;                           /* refused */
}

Eleven lines later, the year is parsed with a function that cannot report failure:

mdy.year = atol(cp);
if (mdy.year > 99 && mdy.year < JPMCDS_TDATE_BASE_YEAR)
    ... out of range ...
if (mdy.year < CROSSOVER_YEAR)
    mdy.year += 2000;

atol returns 0 both for "0" and for text it cannot parse, and stops silently at the first non-digit. Neither case is detectable. So a year of "aaaa" becomes 0, 0 is below the crossover, and the date comes back as the year 2000 — a year nobody wrote down.

03/15/2024     -> 2024-03-15   a real year, for contrast
03/15/aaaa     -> 2000-03-15   no digits at all
15-Mar-twenty  -> 2000-03-15   a spelled-out year
1-1-x2024      -> 2000-01-01   digits present, but not first
03/15/2024XX   -> 2024-03-15   atol stops at the junk
03/15/99bogus  -> 1999-03-15   99 is ABOVE the pivot, so +1900
aa/15/2024     -> refused        an unparseable MONTH
03/aa/2024     -> refused        an unparseable DAY

The last two lines are what make this a defect rather than a convention. An unparseable month is refused. An unparseable day is refused. An unparseable year is invented. One function, one input, three fields, two different policies.

Severity

Higher than the mechanism suggests. A crash gets investigated; a date does not. This takes untrusted text — a holiday file, a regression input, a spreadsheet cell — and returns a date twenty-four years off with no error channel touched. Every downstream accrual, discount factor and par spread is then computed perfectly correctly from a wrong date.

In the port — corrected, and why that is the exception

This is the only place in this port where upstream behaviour was corrected rather than reproduced, so the reasoning matters. The standing rule is: reproduce when the implementation is self-consistent and only the documentation disagrees. Here the code disagrees with itself, eleven lines apart, in one function, about one question. There is no single upstream behaviour to preserve — there are two, and they contradict.

date_from_string refuses any year token containing a non-digit. The divergence is asserted from both sides in one test — upstream accepts, the port refuses — so a change on either side fails. The recorded vectors deliberately exclude these inputs: freezing a known divergence into the file the port is checked against would convert a documented difference into a silent one, which is the worst thing a golden file can do.

reproducer: Upstream39UnparseableYearIsAcceptedUpstreamRefusedHere  ·  trace: ./build/debug/defect_evidence u39

UPSTREAM-40

Digits accumulated into a signed long, unchecked

Low-Medium · undefined behaviour on untrusted input Not applicable — out of the port's scope

lscanf.c:486 — JpmcdsSscanf

Mechanism

JpmcdsSscanf is a hand-written scanf. Its integer conversion accumulates digits with no range check, and signed overflow is undefined behaviour in C — so there is no defined result for a 19-or-more-digit number.

value = value * 10 + (*cp - '0');     /* lscanf.c:486 */
lscanf.c:486:28: runtime error: signed integer overflow:
  1111111111111111111 * 10 cannot be represented in type 'long'

Reached through JpmcdsStringToDate, which hands it the first token of a date string — so the input is untrusted text, and a long digit run is a plausible thing for a spreadsheet cell to hold.

Why it is filed at all

lscanf.c is out of scope for this port: it exists to read holiday files, which the port does with the standard library instead. It is filed because this register's subject is upstream's defects, not the port's surface, and because this one is reachable from an in-scope public function.

It surfaced while measuring UPSTREAM-38 — the same input triggers both, and UBSan reported this one first. The two share an input and nothing else: a different file, a different mechanism, a different fix. Three register entries from one probe, which is what “count defects, not entry points” produces when one entry point really does have three.

In the port

Not applicable — no scanf reimplementation exists. The equivalent arithmetic in date_from_string range-checks before each multiply and returns nullopt instead of wrapping.

trace: ./build/asan/defect_evidence u38 --unsafe  ·  narrative: ./build/debug/defect_evidence u40

UPSTREAM-37

A NULL guard on one path out of four

Medium · store through NULL on three of four exit paths Cannot occur

cxbsearch.c:84 — JpmcdsBinarySearchLong

Mechanism

The function returns three values through pointers, and its main path treats two of them as optional:

if (loBound != NULL)
{
    while (lo >= 0 && ELEMENT(lo) >= xDesired)
        --lo;
    ...
}

if (hiBound != NULL)
{
    ...
}

That guard is the documentation. Nothing in the header says NULL is acceptable; the code saying if (loBound != NULL) is the only statement on the subject, and it says yes. Measured: an in-range search with NULL for both optional outputs returns SUCCESS and fills exact correctly.

The function then has three early returns that write through the same pointers with no guard at all:

if (xDesired < ELEMENT(0))
{
    *exact   = -1;
    *loBound = -1;
    *hiBound = 0;
    return SUCCESS;
}
else if (xDesired > ELEMENT(arraySize-1))   /* same, unguarded */
...
if (arraySize == 1)                         /* same, unguarded */
cxbsearch.c:84:9: runtime error: store to null pointer of type 'long'
ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000
SUMMARY: AddressSanitizer: SEGV cxbsearch.c:84 in JpmcdsBinarySearchLong

Why this one is worse than a missing check

Most of this register is missing checks. This is an inconsistent one, forty lines apart in a single function, and the distinction matters.

A missing check is a precondition: it can be documented, and a caller who violates it has made a mistake. A check on one path and not another is an invitation the code does not honour — the guarded path teaches the caller that NULL is fine, and three other paths punish them for believing it. The caller did nothing wrong, and there is no document they could have read that would have saved them, because the only statement about NULL in the whole function is the one that says it is allowed.

Reachability

Both in-library callers pass non-NULL for all three outputs — cxzerocurve.c:103 and feeleg.c:569, each searching for today's date. So this is reachable only through the public header, which is also the only place anyone would read the guard and conclude NULL was allowed. That is the fourth time in this register that the externally-reachable surface is the unvalidated one, after UPSTREAM-25, 30 and 36.

In the port

Cannot occur. match_range returns a value:

struct MatchRange {
  std::size_t first = 0;
  std::size_t count = 0;
};

No output pointers, so nothing to guard on any path and nowhere for the inconsistency to live.

The collapse from three outputs to one range is not cosmetic. Upstream documents the relationship between its three values — "hiBound-loBound-1 should give the number of exact matches in all cases, and everything in the range [loBound+1, hiBound-1] inclusive should be an exact match" — and that invariant is the answer. Returning it makes the arithmetic a tautology instead of a promise each caller re-derives, and the sentinels go with it: loBound == -1 and hiBound == arraySize are not "absent", they are one position past each end and load-bearing for the subtraction.

Two more things measured here, neither filed

The parameter comment is wrong. It says hiBound is -1 when no greater value exists; the function comment twenty lines above says arraySize, and the code says arraySize. Measured: seeking 99 in {10,20,20,30,40} gives hiBound == 5. Two comments in one file contradicting each other, with the code agreeing with one.

The order check never fires. There is a branch reporting "x array not in increasing order", reached when the arraySize + 1 iteration cap expires. I wrote a test asserting at least one unsorted array would be refused by it. The test failed: across an exhaustive sweep of every unsorted array of length 2 to 4 over the alphabet 0..3, not one was refused. The cap is roughly exponentially generous — a runaway backstop, not a detector. Disorder produces a confident wrong answer, which is exactly what the function's own documentation promises, so the branch is dead code rather than a broken check. Recorded because it reads like a safety net and is not one.

Reproduce: ./build/debug/defect_evidence u37  ·  trace: ./build/asan/defect_evidence u37 --unsafe
UPSTREAM-36

The fourth unguarded fArray[fNumItems-1]

Medium · null-derived read at a public entry point Cannot occur

linterpc.c:65 — JpmcdsLinInterpCurve

Mechanism

The function clamps each requested date into the old curve's range to avoid extrapolating — the intent is right and the comment says so:

for (idx = 0; idx < desiredDates->fNumItems; idx++)
{
    modDates[idx] = MIN(desiredDates->fArray[idx],
                        oldCurve->fArray[oldCurve->fNumItems-1].fDate);
    modDates[idx] = MAX(modDates[idx],
                        oldCurve->fArray[0].fDate);

Neither end is guarded, and JpmcdsNewTCurve accepts a count of zero — only a negative one is refused — leaving fArray NULL. So the two lines are NULL[-1] and NULL[0]:

linterpc.c:65:25: runtime error: applying non-zero offset
                  18446744073709551600 to null pointer
ERROR: AddressSanitizer: SEGV on unknown address 0xfffffffffffffff0
SUMMARY: AddressSanitizer: SEGV linterpc.c:65 in JpmcdsLinInterpCurve

And a zero-point curve is not a hypothetical shape — zerocurve.c builds one as its first act: JpmcdsNewTCurve(valueDate, 0, (double) 1L, JPMCDS_ACT_365F).

The pattern, which is the point of this entry

At four occurrences, fArray[fNumItems-1] without a guard stops being four accidents:

entryfileshape
UPSTREAM-21zcall.cread, NULL[-1], measured SIGSEGV
UPSTREAM-29schedule.cthe zero-period list that enables one
UPSTREAM-32zcswutil.cread-modify-write, NULL[-1]
UPSTREAM-36linterpc.cread, NULL[-1] and NULL[0]

Four different sites in four different files reached for the same idiom. In each one the author knew their own count was positive — and in each one that knowledge lived nowhere a compiler or a later reader could check it. That is what the absence of a non-empty container type costs, billed four times.

It is worth being precise about what the port did here. It did not add four guards. It made one type non-empty, in the zero_curve slice, long before three of these four were found — and the cost of that decision showed up exactly once, as two overloads in the zerocurve slice. Four defects retired for two overloads is the best trade in this register.

Reachability

JpmcdsLinInterpCurve has no caller inside the library. It appears exactly once outside its own file, as TCurveInterpFunc JpmcdsLinInterpCurve; in interp.h — a declaration against a function-pointer typedef, not a call. The same situation as UPSTREAM-30: an exported function whose only possible callers are external, which is exactly who gets no argument checking.

In the port

Cannot occur. ZeroCurve is non-empty by construction, so points().front() and points().back() are total functions and the clamp has nothing to check.

Reproduce: ./build/debug/defect_evidence u36  ·  trace: ./build/asan/defect_evidence u36 --unsafe
UPSTREAM-35

toupper on a plain char, which C does not permit

Low · undefined behaviour, no consequence demonstrated Cannot occur

zerocurve.c — JpmcdsBuildIRZeroCurve

Mechanism

#define JpmcdsSWAPNAME   'S'
#define JpmcdsMONEYNAME  'M'
...
    char    instr;
...
    instr = toupper(instrNames[i]);
    if (instr != JpmcdsMONEYNAME && instr != JpmcdsSWAPNAME)

instrNames is a char *. C §7.4 requires toupper's argument to be "representable as an unsigned char" or to equal EOF. On every platform this port builds on, plain char is signed, so a byte with the high bit set arrives as a negative number that is neither.

byteas charpermitted by C?
0x4D ('M')77yes
0x7F127yes
0x80−128no — undefined behaviour
0xE9−23no — undefined behaviour
0xFF−1yes

Note the last row. 0xFF as a signed char is -1, which equals EOF — so of the 128 high-bit bytes, exactly one is legal, by collision. That is the kind of accident that lets this class of bug survive review: the obvious test case is the last byte, and the last byte is fine.

Reachability and consequence

The call happens before the instrument check rejects the character, so the undefined behaviour is already done by the time the function reports a problem. No consequence is demonstrated, and the reasons are worth separating:

There is a second, independent reason not to write it this way, with nothing to do with signedness: toupper consults the locale. Under a locale where 's' does not uppercase to 'S', the parse changes. A function deciding whether a benchmark is a swap should not depend on LC_CTYPE.

In the port

Cannot occur, twice over.

switch (code) {
case 'M': case 'm': return InstrumentKind::MoneyMarket;
case 'S': case 's': return InstrumentKind::Swap;
default:            return std::nullopt;
}

No toupper, so no argument contract to violate and no locale to consult. And InstrumentKind is an enum, so an InstrumentQuote cannot carry an unparsed letter at all — the parse happens once, at the boundary, and what crosses it is a value.

A tier-1 test walks all 256 byte values and requires exactly four to be accepted. That is the test upstream's version could not have: with toupper in the path, 128 of those inputs are undefined behaviour and the test would be asserting things about a program with no defined meaning.

Reproduce: ./build/debug/defect_evidence u35
UPSTREAM-34

A validator that reports a NULL pointer and then dereferences it

Medium · null dereference inside the code that detected the null Cannot occur

gtozc.c:345 & gtozc.c:464 — two validators, one mechanism

Mechanism

Both static validators in gtozc.c accumulate failures rather than returning at the first one:

int   status = SUCCESS;     /* Until proven a failure */

if(zeroCurve == NULL)
{
    JpmcdsErrMsg("%s: ZeroCurve is NULL\n", routine);
    status = FAILURE;            /* and no return */
}

if (numRates < 0) { ...; status = FAILURE; }
if (JpmcdsDayCountValid(routine,dayCountConv)==FAILURE) { ...; status = FAILURE; }

for (i=0 ;i<numRates ;i++ )
{
   ...
   if (dateArr[i] <= zeroCurve->fBaseDate)

That style is good design — it reports every problem with the input instead of only the earliest, and this report has praised the same pattern elsewhere, in streamcf.c's CheckFixedStreamDetails.

The defect is narrower than the style. One of the accumulated checks is a precondition for a later one. The NULL test sets a flag and carries on; the loop then reads through the pointer.

Two sites, one mechanism, one fix

CheckZCSwapsInputs has the identical shape and is worse — its dereference is not inside a loop whose count could be zero:

if(JpmcdsIsBusinessDay(zeroCurve->fBaseDate, holidayFile, &isBusDay)==FAILURE)
sitefunctionthe dereference
gtozc.c:345CheckZCCashInputsdateArr[i] <= zeroCurve->fBaseDate
gtozc.c:464CheckZCSwapsInputsJpmcdsIsBusinessDay(zeroCurve->fBaseDate, ...)

One edit — an early return once the curve is known NULL — fixes both, so this is one defect at two sites rather than two defects: the counting rule UPSTREAM-19 established.

What is and is not reachable

A zero instrument count short-circuits before any validation runs:

if (numRates == 0)    /* nothing to add */
{
   tcCash = JpmcdsCopyCurve (zeroCurve);
   return tcCash;
}

and JpmcdsCopyCurve tolerates a NULL, so JpmcdsZCCash(NULL, …, 0, …) returns NULL cleanly — measured. Any positive count reaches the validator, and both sanitizers report it:

gtozc.c:345:37: runtime error: member access within null pointer
                of type 'TCurve'
ERROR: AddressSanitizer: SEGV on unknown address 0x000000000010
SUMMARY: AddressSanitizer: SEGV gtozc.c:345 in CheckZCCashInputs

0x10 is the offset of fBaseDate within TCurve, read from a null base.

In the port

Cannot occur. Both functions take const ZeroCurve &, so the input does not exist — the third defect in this register retired by a reference rather than a check.

The useful lesson is not "return early", which would throw away a good pattern. stream_cash_flows.hpp's is_well_formed accumulates in exactly the same style and is safe, because every check it performs is independent of the others. The rule is:

An accumulating validator is safe only when no check guards another.

Where one check is a precondition for a later one, it has to return — and then it stops being an accumulating validator for that input, which is the honest trade. Upstream wanted both properties and got neither.

Reproduce: ./build/debug/defect_evidence u34  ·  trace: ./build/asan/defect_evidence u34 --unsafe
UPSTREAM-33

The root finder is pointed at the wrong curve point

Low · misleading failure, no wrong number demonstrated Cannot occur

zcswap.c — JpmcdsZCValueFixFltSwap

Mechanism

The function adds a placeholder point for the benchmark it is about to solve:

if (JpmcdsZCAddRate(zc, maxDate, rate) == FAILURE)
    goto done;

and then hands the root finder the address of the last slot:

if (JpmcdsRootFindBrent(JpmcdsObjFuncPVtheSwap, &funcParams,
                     LOWER_BOUND, UPPER_BOUND, MAX_ITERATIONS, rate,
                     INITIAL_X_STEP, INITIAL_F_DERIV,
                     X_TOLERANCE, F_TOLERANCE,
                     &zc->rate[zc->numItems-1]) == FAILURE)

That is the point just added only if it is the latest date in the curve. JpmcdsZCAddRateAndDiscount does not append unconditionally — it inserts in sorted position:

if (zc->numItems==0 || zc->date[zc->numItems-1]<date)
{
    zc->date[zc->numItems] = date;      /* insert at end */
    ...
}
else
{
    int i = zc->numItems - 1;           /* loops backwards, until before date */

So for a benchmark whose maxDate falls inside the existing curve, the solver varies a different, already-solved point, and the point it was supposed to solve keeps its placeholder. Demonstrated — a curve with points at 2026 and 2035, then AddRate(2027, 0.045):

    [0] 20260115  rate 0.0250
    [1] 20270115  rate 0.0450
    [2] 20350115  rate 0.0400   <-- the slot the solver writes

Consequence, measured with controls

A sweep of 1,400 combinations with the benchmark inside the existing curve: every one fails. Varying a distant zero rate barely moves a shorter swap's present value, so Brent cannot bracket a root and the function reports "Root finder failed".

Positive controls were essential, because "it always fails" is also what a broken fixture looks like:

caseresult
control: no far point, 5y benchmarkSUCCESS
control: far point 2026, 5y benchmarkSUCCESS
control: far point 2027, 8y benchmarkSUCCESS
INSIDE: far point 2035, 5y benchmarkFAILURE
INSIDE: far point 2030, 5y benchmarkFAILURE
INSIDE: far point 2029, 4y benchmarkFAILURE

I tried and failed to produce a silently wrong curve. Across the whole sweep there was no case where the solve converged while varying the wrong point. The observable consequence is a misleading diagnostic: the caller is told the root finder failed when the real problem is that the benchmark is not the longest instrument so far. That is why this is filed low — the same reasoning as UPSTREAM-23, where a pricing consequence was looked for and not found, and the register said so.

Reachability

JpmcdsZCAddSwaps has an else branch that calls JpmcdsZCAddSwap for benchmarks not beyond the curve's end — exactly the triggering condition — and passes discZC through. JpmcdsZCValueFixFltSwap is also exported in its own right. A benchmark strip that extends monotonically past the stub curve never hits it; one that overlaps an existing curve does.

In the port

Cannot occur. The added point is looked up by date and solved for by index:

if (!curve.add_rate(max_date, rate)) {
  return false;
}
const std::optional<std::size_t> solved_index = curve.find_exact(max_date);

so the solve targets what it added whatever the insertion order. A tier-1 test asserts the port solves exactly the input upstream cannot, and that the pre-existing far point keeps the rate it had.

A second benefit, not the point of the fix: the port sets the rate through ZeroCurveBuilder::set_rate, which recomputes the cached discount factor, so the rate/discount invariant cannot drift. Upstream mutates fArray[last].fRate in its snapshot and recomputes the discount in a separate call against the live curve — two places holding the same quantity, kept in step by hand.

Reproduce: ./build/debug/defect_evidence u33
UPSTREAM-32

The bizarre rate got a guard; the bizarre maturity did not

Medium · read-modify-write through a null-derived pointer Cannot occur

zcswutil.c:96 — JpmcdsZCGetSwapCFL · reachable from zcswap.c:475

Mechanism

The function opens by special-casing a degenerate input, and says so:

/* Bizarre rate==0.0 case
 */
if (rate==0.0)
{
    cfl = JpmcdsNewEmptyCFL(1);        /* simply cash flow of 1.0 at date */
    if (cfl == NULL)
        goto done;
    cfl->fArray[0].fAmount = 1;
    ...
    return cfl;
}

That path is carefully done. Even the return cfl rather than a jump to done: is deliberate — status is still FAILURE there, so the shared exit would free the list and return NULL. Somebody thought about it.

The other degenerate input gets nothing. With matDate == valueDate:

stepresult
JpmcdsNewDateList(v, v, 6M)1 date
JpmcdsNewPayDates(v, v, 6M)0 — it drops the first element and decrements the count
JpmcdsNewEmptyCFL(0)fNumItems == 0, fArray == NULL
the coupon loopdoes not run

and then, three statements from the end:

cfl->fArray[cfl->fNumItems-1].fAmount += 1.0;   /* add principal */

which is NULL[-1].fAmount += 1.0. Note that this is a read-modify-write, not merely a read as in UPSTREAM-21 — the += loads and stores.

JpmcdsNewPayDates is the step that makes it possible, and the emptying is not an accident of allocation:

/* Now remove startDate, and move all dates back by one.
 */
for (idx=0; idx < payDates->fNumItems-1; idx++)
{
    payDates->fArray[idx] = payDates->fArray[idx+1];
}
payDates->fNumItems--;

With one date the loop body never executes and the count goes to zero. Excluding the value date from a list of payment dates is correct; the case where it is the only date is not considered.

Both sanitizers, two diagnostics

zcswutil.c:96:4: runtime error: applying non-zero offset
                 18446744073709551600 to null pointer
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior zcswutil.c:96:4

==22701==ERROR: AddressSanitizer: SEGV on unknown address 0xfffffffffffffff8
SUMMARY: AddressSanitizer: SEGV zcswutil.c:96 in JpmcdsZCGetSwapCFL

The two numbers are the same bug from two distances. 18446744073709551600 is -16 as an unsigned 64-bit value, and sizeof TCashFlow is 16 — one element backwards. 0xfffffffffffffff8 is -8, the offset of .fAmount within that element, the address actually touched.

The opposite situation from UPSTREAM-31, filed one slice earlier: there the harness could see nothing at all; here two tools independently report it.

Reachability

cfl = JpmcdsZCGetSwapCFL(zc->valueDate,
                         matDate, isEndStub,
                         rate,
                        &ivl,
                         fixDayCountConv,

There is no comparison between matDate and zc->valueDate anywhere in zcswap.c. A swap benchmark maturing on the curve's own value date is sufficient — the same trigger as UPSTREAM-29, arriving at a different defect in a different file. The zero-rate path is immune, which is the shape of the whole finding: the input somebody wrote a comment about is handled, and the one two statements later is not.

In the port

Cannot occur. swap_cash_flows refuses when the coupon-date list is empty, and the guard is on the outcome rather than on maturity == value_date. That is UPSTREAM-29's lesson from two slices ago, and it applies here for a fresh reason: the substitution table and the bad-day adjustment both run between the date generation and the flow construction, and fix_bad_dates can collapse two dates onto one.

swap_coupon_dates is not changed — it still returns the empty list, because that is upstream's answer and the date generation is faithful. The refusal belongs where the empty list becomes a problem.

Reproduce: ./build/debug/defect_evidence u32  ·  traces: ./build/asan/defect_evidence u32 --unsafe
UPSTREAM-31

An output written after the error label, from a variable never set

Low · undefined behaviour, value discarded Cannot occur

streamcf.c — GetFloatStubRate

Mechanism

int           status = FAILURE;     /* Until proven successful */
double        rate;                 /* never assigned here */
...
switch (swapType)
{
  case JPMCDS_SINGLE_REFIX:
    if (JpmcdsForwardFromZCurve(..., &rate) == FAILURE)
        goto done;
    break;

  default:
    JpmcdsErrMsg("%s: unknown swap type. Can't calculate stub rate.\n", routine);
    goto done;
}

status = SUCCESS;

 done:
   if (status == FAILURE)
       JpmcdsErrMsg("%s: Failed to calculate back stub rate.\n", routine);

    *stubRate = rate;               /* runs on EVERY path */

    return status;

The output write sits after the label, so it executes on every path — and on the failure paths rate was never assigned. Reading an indeterminate double is undefined behaviour whatever the caller then does with it.

The same shape as schedule.c's error: label, which is also reached on success. There the shared exit block was harmless; here it writes an output.

The precondition, measured

The read is only indeterminate if JpmcdsForwardFromZCurve leaves its output alone when it fails. It does — all three of its failure paths goto done without touching *rate. Confirmed by sweeping 200 forward computations with a sentinel in the output, so an unwritten result is visible:

outcomecount
ordinary success160
NaN returned as SUCCESS (UPSTREAM-19, second site)39
FAILURE returned1
…of those, output left untouched1

The failure window is narrow: it needs startDiscount > 0 with endDiscount exactly 0, so the forward discount is 0 and JpmcdsDiscountToRate's discount <= 0 guard fires. One rung further out both discounts underflow, giving 0/0, and then the guard cannot see the NaN and returns it as SUCCESS — which is UPSTREAM-19 again, quantified here at 39 of 200.

Reachability

A back-stub schedule whose final accrual period lands in that window hands GetBackStub exactly such a period:

schedule: 323 periods, stubLocation 1 (BACK_STUB)
stub period accrues 15 Jan 2185 -> 15 Jun 2185
forward on that period: FAILURE, output LEFT UNTOUCHED

The default: branch is a second site of the same write, and there rate is never assigned on any path. It is unreachable, for a reason worth recording: TSwapType has one enumerator, so in C its compatible type is unsigned, (TSwapType)(-1) is 4294967295, and the one-sided guard if (swapType > JPMCDS_SINGLE_REFIX) — where that constant is 0 — catches negatives by accident. In C++ clang gives the same enum a signed type, so a C++ translation unit and the C library sharing schedule.h disagree about it.

Why this one could not have been caught

Every other memory finding on this page was caught by a sanitizer. This one cannot be, and the reasons compound:

So this is the first concrete instance of a blind spot that had been a stated limitation with no example: an uninitialised stack read, in a cross-translation-unit shape. Found by reading, then confirmed by measuring the precondition rather than asserting it.

Consequence

None observable. GetFrontStub and GetBackStub both test the status before touching the value, so the indeterminate double is written and then discarded. Nothing wrong reaches a price. The read is undefined behaviour all the same, and a compiler is entitled to assume it does not happen.

In the port

Cannot occur. detail::stub_payment returns std::optional<double> rather than writing through an out-pointer, so a failure path has no output to write and the shape is unavailable. This is the general argument for returning values instead of filling them in: a function that returns cannot write a result it did not compute.

Reproduce: ./build/debug/defect_evidence u31
UPSTREAM-29

A schedule the library returns and its own validator rejects

Medium · invalid schedule reported SUCCESS; out-of-bounds read downstream Cannot occur

schedule.c — JpmcdsNewCouponDatesSwap · consequence in zcswap.c:725, 743, 744

Mechanism

The argument check opens with four lines that disagree with each other:

if (startDate > matDate)
{
    JpmcdsErrMsg("%s: maturity date (%s) is on or before start date (%s)\n", ...

The condition says after; the message says on or before. Equality is accepted, and the message is the only statement of intent anywhere, so the gap is invisible unless you read both halves.

Equality produces one unadjusted period of zero length. The empty-accrual-period removal loop — added for exactly this case, with the comment “Thanks to Neill Penney for the solution” — drops it and decrements the count:

if ( adjStreamSched->fArray[i].accrueStartDate !=
     adjStreamSched->fArray[i].accrueEndDate )
{
    streamSched->fArray[j] = adjStreamSched->fArray[i];
    j++;
}
else
{
   if ( i==0 )
   {
      ...
      streamSched->fNumItems--;

With one period there is nothing left. The consistency check that follows compares j against fNumItems — both zero, so it passes — retCode = SUCCESS, and a non-NULL list comes back. That list is rejected by the library's own validator for the same type:

if (schedule->fNumItems < 1)
{
    JpmcdsErrMsg("%s: schedule must have at least one coupon period"
              " but has only %d.\n", ...
    return FAILURE;

So the constructor and the validator disagree about the same value, and nothing in the library says which one is right.

Not confined to the degenerate input

The obvious reading is that this needs startDate == matDate, a zero-tenor swap no sane caller builds. It does not. Any span whose every accrual period collapses under bad-day adjustment arrives at the same place, and a weekend does it:

inputperiodsstubLocationvalidator
start == maturity, front stub0NO_STUBFAILURE
start == maturity, back stub0BACK_STUBFAILURE
2024-03-16 → 2024-03-17 (Sat → Sun), FOLLOW0NO_STUBFAILURE

Both dates in the third row adjust forward to Monday the 18th, so the single period has accrueStartDate == accrueEndDate and is removed. A one-day span over a weekend is not obviously invalid input, which is why the port's guard tests the outcome rather than the input.

The stubLocation column is a second finding inside the first. At i == 0 the removal maps FRONT_STUB to NO_STUB but leaves BACK_STUB alone — correctly, since dropping the front period does not remove a stub at the back. With no periods left at all, the schedule still reports one.

Why it matters

zcswap.c consumes the schedule without validating it:

   (floatDL->fArray[floatDL->fNumItems-1].resetDate,          /* 725 */
maxDate = MAX(indexMatDate, floatDL->fArray[floatDL->fNumItems-1].payDate);
minDate = MIN(indexMatDate, floatDL->fArray[floatDL->fNumItems-1].payDate);

No emptiness check, and no call to JpmcdsCouponDateListCheck on either schedule it builds. With fNumItems == 0 all three are fArray[-1]. The reachability is ordinary: zcswap.c passes zc->valueDate as the start date, so a benchmark instrument maturing on the curve's own value date is enough. streamcf.c:1066 does validate, and is safe.

Under ASan:

ERROR: AddressSanitizer: heap-use-after-free
  ... freed by thread T0 here:
      JpmcdsFreeCouponDateList schedule.c:631
      JpmcdsNewCouponDatesSwap schedule.c:345

Reported as use-after-free rather than as an underflow because the 40 bytes immediately before streamSched->fArray are adjStreamSched->fArray, the scratch list the function frees on its way out — including on the success path, since the error: label sits after retCode = SUCCESS and is a cleanup label rather than an error one. Both labels are accurate. The fault is the negative index; which block it lands in is the allocator's choice.

In the port

Cannot occur. coupon_schedule returns std::nullopt when the removal leaves no periods, so CouponSchedule::periods is non-empty by construction and is_well_formed — the port's validator — is true of every schedule the port builds. The guard is on the outcome, not on start == maturity, because the weekend case shows the input test is the wrong test.

This is one of the cases the port's policy says to correct rather than reproduce: there is no single upstream behaviour to preserve when the constructor and the validator contradict each other about the same value. It is pinned without the oracle — the zero-period cases are recorded in the tier-1 vectors as accepted with zero periods, and the replay asserts the port declines exactly those four.

Reproduce: ./build/debug/defect_evidence u29  ·  trace: ./build/asan/defect_evidence u29 --unsafe
UPSTREAM-30

A buffer sized from one span and filled from another

Medium · heap buffer overflow Cannot occur

schedule.c:761 — JpmcdsGenerateUnadjDates

Mechanism

The function sizes its scratch array from the span it was asked about:

if (JpmcdsCountDates(startDate, matDate, couponInterval, &numPeriods, &dummyInt)==FAILURE)
    goto done;
numPeriods = numPeriods + 3;
dateArr = NEW_ARRAY(TDate,numPeriods);

and then steps the generating loop from somewhere else entirely:

if (firstRollDate > 0)
{
    beginDate = firstRollDate;
    endDate   = matDate;
    ...
    dateArr[nDates++] = unadjustedDate;        /* line 761 */

startDate..matDate sized the array; firstRollDate..matDate fills it. A roll date before startDate makes the second span the longer one, and the + 3 of slack is not a bound on the difference. The lastRollDate branch has the mirror problem with a roll date after matDate. Measured, at a one-month interval:

spanbydates
sizing: 2024-01-01 → 2024-07-011M~9 slots allocated
stepping: 1990-01-01 → 2024-07-011M~415 written
ERROR: AddressSanitizer: heap-buffer-overflow
SUMMARY: AddressSanitizer: heap-buffer-overflow
  schedule.c:761 in JpmcdsGenerateUnadjDates

Reachability, and why it is still a defect

JpmcdsNewCouponDatesSwap bounds both roll dates before calling:

if (firstRollDate < startDate) { ... return FAILURE; }
if (firstRollDate > matDate)   { ... return FAILURE; }

and within [startDate, matDate] the stepped span is always a sub-span of the sizing span, so the library's own path is safe. That is the whole of the protection: a check in the caller, which the callee neither performs nor documents as a precondition.

JpmcdsGenerateUnadjDates is declared in the public schedule.h and has no caller inside the library at all. It is not an internal helper that happens to be exported; it is an exported function whose only possible callers are external ones, and those are exactly the callers that get no argument checking. In-library safety says how bad this is, not whether it exists — the same conclusion UPSTREAM-25 reached, where reasoning from in-library reachability to function safety nearly dropped a confirmed heap overflow.

In the port

Cannot occur, twice over. generate_unadjusted_dates accumulates into a std::vector, so there is no array to size and no sizing to get wrong. And the bound upstream applies in its caller is applied here as well, in the function that needs it, so the public entry point is as safe as the internal one. The overflowing upstream call is kept as a DISABLED_ test: recorded, never executed, because running it is undefined behaviour and a vector derived from it would be a committed file produced by UB.

Reproduce: ./build/debug/defect_evidence u30  ·  trace: ./build/asan/defect_evidence u30 --unsafe
UPSTREAM-7

Date list truncation is ignored when fewer than two dates survive

High · silently wrong Fixed · documented intent

lib/src/dtlist.c:592 & lib/src/cxdatelist.c:220 — two implementations

Mechanism

Both scan backwards for the truncation point:

truncatePt = -1;                       /* dtlist.c */
for (i = numItems - 1; i > 0; i--)     /* index 0 is never tested */
{
    if (dateList->fArray[i] < truncationDate) { truncatePt = i; break; }
    if (inclusive && dateList->fArray[i] == truncationDate) { truncatePt = i; break; }
}
size = truncatePt + 1;

The condition is i > 0 rather than i >= 0, so the scan can fail to find any qualifying element. When it does, the sentinel survives — and the two files chose different sentinels, so they fail in opposite directions.

The consequence is wider than element 0, which an earlier version of this report understated. The scan finds nothing whenever fewer than two dates should survive, so dtlist.c returns an empty list while cxdatelist.c ignores the truncation entirely.

Evidence

  input / cut                want           dtlist.c         cxdatelist.c
                                            (sentinel -1)    (sentinel n-1)
  [1,2] @2                   [1]            []               [1,2]
  [10,30] @30                [10]           []               [10,30]
  [5] @9                     [5]            []               [5]
  [9,10] @9 inclusive        [9]            []               [9,10]
  [1,2,3] @3                 [1,2]          [1,2]            [1,2]
  keep-before                  want         cxdatelist.c
  [5,6,7] @3                   []           [5,6,7]      <- ignored entirely
  [5,6,7] @5                   []           [5,6,7]
  [5,6,7] @6                   [5]          [5,6,7]
  [5,6,7] @7                   [5,6]        [5,6]        correct
  [5,6,7] @9                   [5,6,7]      [5,6,7]      correct

  keep-after also fails when the answer is empty:
  [5,6,7] @9 keep-after        []           [5,6,7]

Over a 600-case sweep across six lists, every cut position and both directions, upstream disagrees with the documented intent on 234 cases — 39%. Both are correct whenever two or more dates survive, which is the common case and the reason this has gone unnoticed.

Reachability

The cxdatelist.c variant is called from timeline.c, which builds the integration timeline for the fee and contingent legs — so it sits on the CDS pricing path.

Price impact: measured, and it is none. timeline.c is the only caller on the pricing path, and it cannot reach the defect. Both of its truncations run after the start and end dates have been merged into the list, and the contract requires end > start, so at least two distinct dates always survive — precisely the regime where upstream's truncation is correct.

Confirmed over 96 integration windows plus 8 deliberately minimal two-date timelines, every one matching the corrected port exactly. Note the form of that answer: the sweep says the defect did not bite in the cases tried, while the structural argument says it cannot bite at all.

Status in the port

Fixed. The port implements the documented intent. This was the first finding where "preserve upstream behaviour" was not available — there are two upstream behaviours and they contradict each other as well as their own header — and it prompted the project to write down a policy for when a port corrects rather than reproduces. Recorded vectors for this module hold the intended answers plus a flag for whether upstream agreed, so the correction stays visible instead of becoming invisible. The price impact is owed a measurement when timeline.c is ported.

Reproduce: ./build/debug/defect_evidence u7
UPSTREAM-6

Business-day adjustment never returns

High · liveness Cannot occur in the port

lib/src/busday.c · getNextBusDate

Mechanism

The walker steps one day at a time with no iteration bound:

aHoliday = TRUE;
do
{   /* Check if it's a holiday first. */
    ...
        if (JPMCDS_IS_WEEKEND (curDate, hl->weekends))
             curDate += direction;
        else
             aHoliday = FALSE;
    ...
}
while ( aHoliday == TRUE );

If the calendar's weekend set covers all seven days, aHoliday never becomes FALSE and the loop never exits. Such a calendar is accepted: JpmcdsHolidayListNewGeneral(NULL, 0x7F) returns a valid list, because verifyHolidayList has no opinion on the weekend mask.

Evidence

calendar with weekends=0x7F constructed: accepted
calling JpmcdsHolidayListBusinessDay with FOLLOW...
--- killed after 5s ---

Reachability

Needs all seven weekend bits set, for which upstream provides no named constant — a caller would have to OR them or compute the mask. So it is a robustness failure rather than a likely production path. But accepted input that never returns is the kind of defect that takes a pricing service down rather than returning a wrong number. As it spins, curDate += direction would eventually overflow TDate as well; the hang simply arrives first.

Status in the port

Cannot occur. roll_to_business_day returns nullopt when any calendar has no business weekday, and otherwise bounds its loop at 7 × (holidays + 2) — a ceiling derived from the fact that stored holidays are always business weekdays and reaching the next one costs at most seven days.

Construction stays permissive, matching upstream, because the predicates are well defined for such a calendar: everything is a non-business day. Calendar::allows_business_days() exposes the condition.

Only half of this is differentially testable. A test asserts upstream still accepts the calendar, and fails if a future release rejects it — but it cannot assert the hang, because the test would never finish.

Tests: BadDayDifferential.Upstream6_AllWeekendCalendarIsAcceptedByUpstream
        BadDayAdjust.AllWeekendCalendarDeclinesInsteadOfLooping
        BadDayAdjust.TerminatesWithOnlyOneBusinessWeekdayAndManyHolidays
UPSTREAM-1

Month validated after it indexes a 13-element table

Low · UB on a reject path Cannot occur in the port

lib/src/dateconv.c:657 · JpmcdsMDYToDate

Mechanism

The day-range check indexes the month-length table before the month-range check has validated month:

/* Make sure day is in range. */
if (day >= 1 && day <= 28)
   /*EMPTY*/;
else if (day < 1 ||
    (isLeap ? day > leapDays[month] : day > (days[month])))   /* month unvalidated */
{ ... return FAILURE; }

/* Make sure month and year are in range. */
if (month < 1 || month > JPMCDS_MONTHS_PER_YEAR || ...)       /* too late */
{ ... return FAILURE; }

days[] and leapDays[] hold 13 elements, so month == 13 reads one past the end.

Evidence

ERROR: AddressSanitizer: global-buffer-overflow
READ of size 4 at 0x000102977db4 thread T0
    #0 JpmcdsMDYToDate dateconv.c:658
0x000102977db4 is located 0 bytes after global variable 'leapDays' ... of size 52

Reachability

All three conditions must hold:

The same validation logic appears in JpmcdsNormalizeMDY with the ordering correct: it normalises month into 1–12 before indexing. One defect, written twice, right in one copy.

Status in the port

Cannot occur. make_date range-checks before constructing anything, and days_in_month takes a std::chrono::year_month, so a 13th month cannot be represented in a value that reaches a table.

Tests: DateDifferential.MakeDateMatchesUpstreamIncludingRejections
        DateMonth.DaysInMonthIsTypeSafeWhereUpstreamWasNot
The sweep covers months 0–12 only: there is no defined behaviour at 13 to compare against.
UPSTREAM-2

JPMCDS_DEFAULT and FAILURE are both -1

Design · no caller broken today Cannot occur in the port

lib/include/isda/cgeneral.h:56 and :64

Mechanism

#define FAILURE        -1
#define JPMCDS_DEFAULT -1

A day count code of -1 means both “the default convention” and “this call failed”. The same pattern appears in JpmcdsDate, which returns FAILURE as a TDate.

Evidence

  JPMCDS_DEFAULT = -1
  FAILURE        = -1
  equal?         = YES

Upstream parse of "Default": rc=SUCCESS, code=-1
Upstream JpmcdsDate(1600,1,1) (an invalid date): -1

A caller holding a long cannot distinguish the two.

Status in the port

Cannot occur. Success and value are separate channels:

Port parse of "Default": has_value=true, value=-1
Port make_date(1600,1,1):  has_value=false

-1 is an ordinary value in the port, not a signal. This is the reason the port returns std::optional throughout rather than reserving values inside the result space.

Test: DayCountStringParse.NonCalculableKeywordsParseButAreNotConventions
UPSTREAM-5

Days never format as weeks

Cosmetic · output still correct Reproduced deliberately

lib/src/convert.c · JpmcdsFormatDateInterval

Mechanism

The 'D' case computes a week form and then falls through into default:, which overwrites both variables:

case 'D':
    if (interval->prd % JPMCDS_DAYS_PER_WEEK == 0)
    {
        periodType = 'W';                     /* computed... */
        numPeriods = interval->prd/JPMCDS_DAYS_PER_WEEK;
    }
    ...
    /* no break */
default:
    periodType = interval->prd_typ;           /* ...then discarded */
    numPeriods = interval->prd;

The 'M' case directly above it does have its break, so month collapsing works.

Evidence

  stored     upstream       port       intended
  12M        1A             1A         same
  18M        3S             3S         same
  6M         1S             1S         same
  7D         7D             7D         1W
  14D        14D            14D        2W
  28D        28D            28D        4W

Status in the port

Reproduced deliberately. This is observable output; abbreviating "14D" to "2W" would change behaviour for every caller that formats an interval. The port reproduces the behaviour and does not implement the unreachable intent.

Tests: DateIntervalDifferential.Upstream5_DaysNeverFormatAsWeeks
        DateIntervalFormat.DaysNeverCollapseToWeeks

Also noted — why the library cannot be used concurrently

Not defects in the sense above, but the reason the library is single-threaded in practice. The port holds no mutable global state.

Location State
buscache.c:62 THoliday *cache = NULL; — no static, so it has external linkage and is exported from the archive as _cache. A process-wide holiday cache with no locking.
cerror.c Eight statics including a FILE * log handle and a callback pointer
bsearch.c:19 bSearchCheckOrder_g, a global flag that silently switched every binary search in the process between checked and unchecked
yearfrac.c:172 static char privDccString[33], a function-local scratch buffer in the convention-string parser
convert.c static char format[2][16] with a toggling index, so JpmcdsFormatDateInterval’s result is invalidated by the second subsequent call

bSearchCheckOrder_g is already gone — the caller chooses bracket or bracket_checked. The holiday cache becomes a value the caller owns when the calendar layer lands.

Method

The upstream C is compiled untouched into a static library and linked into the same test binary as the port. Tests call both implementations side by side and compare in-process, so the oracle is not a recorded value that can go stale — it is the original code, executing.

All of it runs under AddressSanitizer and UndefinedBehaviorSanitizer. That pairing is what surfaced UPSTREAM-1 and UPSTREAM-4: neither changes the library’s return value, so neither is visible from output alone.

Configuration Tests Notes
With a local oracle 158 Tier 1 + live differential + byte-exact end-to-end example
Without an oracle (CI) 106 Replaying 9,831 recorded reference cases
ASan + UBSan 158 Clean