================================================================================ CCDciel - BUG AND BAD-PRACTICE REPORT ================================================================================ Source reviewed : ccdciel-master.zip, src/ only (143 units, ~114,700 lines) Forms (.lfm) : not included, so no form/component-level checks were possible Method : static reading + pattern scanning. The code was NOT compiled (no FPC in the analysis environment), so nothing below is a compiler diagnostic; every item was verified by reading the source at the quoted line numbers. Line numbers : refer to the files as shipped in the archive. Severity key [CRIT] memory corruption, data corruption, or crash [HIGH] wrong results, resource exhaustion, security exposure [MED] wrong behaviour under specific but realistic conditions [LOW] robustness, maintainability, latent risk ================================================================================ 1. [CRIT] Double free + corrupted list entry in the polar alignment dialog ================================================================================ File : pu_polaralign2.pas Lines: 181-184, 215-232, 233-236 Tf_polaralign2.FormShow builds the "GotoPosition" combo box. At line 181 it creates the first TAltAzPosition, sets the four sentinel values to -1 (lines 182-183) and adds it as the "custom position" entry at index 0. In the "near equator, NORTHERN hemisphere" branch the next statement is: 215 if ObsLatitude>0 then begin 216 {North, preference for south horizon} 217 GetAE(-4,0,1,altaz); <-- altaz is STILL the object from 181 218 GetAE(-0.5,-40,2,altaz); 219 GotoPosition.items.AddObject(rsMeasureES, altaz); 220 altaz:=TAltAzPosition.Create; <-- the Create belongs BEFORE line 217 There is no TAltAzPosition.Create before line 217. Two things follow: a) GetAE writes through azp.az1/alt1/az2/alt2, so the -1 sentinels of the "custom position" entry are overwritten with real alt/az values. The custom-position logic (PanelCustomPosition.Visible, the -1 defaults) no longer behaves as designed. b) The SAME pointer is now stored at index 0 and at index 1 of GotoPosition.Items. The cleanup loop that runs at the top of every FormShow: 178 for i:=0 to GotoPosition.items.Count-1 do 179 GotoPosition.items.Objects[i].free; then calls Free twice on one object. TObject.Free only checks Self<>nil and the reference is never nil'd, so the second call operates on freed memory: heap corruption or an access violation the second time the dialog is opened. Proof that this is an editing accident, not intent: the mirrored SOUTHERN branch has the Create twice in a row - 233 else begin 234 {South, preference for north horizon} 235 altaz:=TAltAzPosition.Create; 236 altaz:=TAltAzPosition.Create; <-- object from 235 leaks immediately 237 GetAE(-4,0,1,altaz); The Create was moved out of the north branch and pasted twice into the south one. Affected users: any observer with 0 < latitude <= 30 (north branch, the crash) and -30 <= latitude < 0 (south branch, the leak). Fix: delete line 236, and insert "altaz:=TAltAzPosition.Create;" before line 217. Consider also giving the list ownership of its objects, or nil'ing Objects[i] after Free, so a repeat of this mistake fails loudly. ================================================================================ 2. [CRIT] Wrong buffer flushed when writing 32-bit float FITS ================================================================================ File : cu_fits.pas Lines: 2603-2623 (TFits.WriteFitsImage) The BITPIX=-32 branch fills and flushes "dm32" throughout the pixel loop: 2612 if not first then FStream.Write(dm32,sizeof(dm32)); 2613 FillByte(dm32,sizeof(dm32),0); ... 2619 dm32[npix]:=single(NtoBE(longword(xs))); but the final partial-block flush writes the wrong array: 2623 if npix>0 then FStream.Write(d32,sizeof(d32)); <-- should be dm32 Compare the three integer branches, which all flush their own buffer: line 2566 Write(d8,...) after filling d8 line 2585 Write(d16,...) after filling d16 line 2604 Write(d32,...) after filling d32 Because d32 and dm32 are both 2880 bytes there is no range error and no crash. The effect is silent data corruption: the LAST 2880-byte data record (up to 720 pixels) of EVERY 32-bit-float FITS file written by CCDciel contains whatever is in d32 - stale big-endian integer data from a previous save, or zeros. npix is always in 1..720 at that point, so the bug fires on every float save, regardless of image dimensions. Fix: change line 2623 to Write(dm32,sizeof(dm32)). Related, same branch, line 2619: dm32[npix]:=single(NtoBE(longword(xs))); This relies on FPC treating longword() and single() as bit reinterpretation rather than value conversion. That holds for same-size variable typecasts but is fragile on an expression and is not guaranteed across compiler versions or modes. Prefer an explicit variant record or an "absolute" alias: var fv: single; iv: longword absolute fv; ... fv := (Fimage[k,ii,j]-bzero)/bscale; dm32[npix] := single(NtoBE(iv)); {or store iv into a longword array} ================================================================================ 3. [HIGH] InvertF64 corrupts roughly half of all double-precision pixels ================================================================================ File : u_utils.pas Lines: 220-231 (InvertF64), used by cu_fits.pas:1130 for BITPIX=-64 images temp:=4294967296 * ((P[0] shl 24) or (P[1] shl 16) or (P[2] shl 8) or (P[3])) + ((P[4] shl 24) or (P[5] shl 16) or (P[6] shl 8) or (P[7])); P[] is PByteArray, so each element is a Byte. In FPC, "Byte shl 24" is promoted to a SIGNED 32-bit LongInt. Therefore: - The low group ((P[4] shl 24) or ...) is NEGATIVE whenever P[4] >= $80. - The high group ((P[0] shl 24) or ...) is NEGATIVE whenever P[0] >= $80. Intended value : (UInt32(hi) shl 32) or UInt32(lo) Actual value : Int64(hi) * 2^32 + Int64(lo) The high group happens to survive: a negative hi is (hi_unsigned - 2^32), and multiplying by 2^32 wraps modulo 2^64 back to the correct bits. The LOW group does not. When lo is negative the result is (hi_unsigned - 1)*2^32 + lo_unsigned - i.e. the high 32 bits of the double are decremented by one. That flips bit 32 of the 52-bit mantissa, a relative error of about 2^-20 (~1e-6). P[4] >= $80 for roughly half of arbitrary pixel data, so about half the pixels of every BITPIX=-64 FITS image read by CCDciel carry ~1e-6 relative noise. The image looks correct; photometry and statistics are quietly degraded. Fix: replace the whole hand-rolled swap with the RTL primitive, which the same file already uses elsewhere (cu_fits.pas:1257, 1287, 2379): function InvertF64(X: Int64): Double; var i: Int64; begin i := BEtoN(X); Move(i, Result, 8); end; Same for InvertF32 with BEtoN(LongWord). -------------------------------------------------------------------------------- 3b. [MED] InvertF32/InvertF64 zero out legitimate large finite values -------------------------------------------------------------------------------- File : u_utils.pas, lines 213 and 225 if (P[0]=$7F)or(P[0]=$FF) then result:=0 // IEEE-754 NaN P[0] is the most significant big-endian byte. For a single, top byte $7F covers exponents $FE-$FF: everything from about 1.7e38 upward, of which only $7F80_0000 and above is Inf/NaN. Values in $7F00_0000..$7F7F_FFFF are perfectly valid finite floats and are silently replaced by zero. Same for $FF (negative). For doubles, top byte $7F covers everything from about 9e307 up. A correct NaN/Inf test is (P[0] and $7F)=$7F and ((P[1] and $80)=$80) for singles, or simply IsNaN/IsInfinite on the decoded value. ================================================================================ 4. [HIGH] Use-after-free on the TCP server objects ================================================================================ Files: cu_tcpserver.pas (lines 126, 270), pu_main.pas (4440, 5521, 8219, Tf_main.StopServer, Tf_main.MenuStatusClick) cu_tcpserver.pas:122 constructor TTCPDaemon.Create; cu_tcpserver.pas:126 FreeOnTerminate := True; cu_tcpserver.pas:267 constructor TTCPThrd.Create(Hsock: TSocket); cu_tcpserver.pas:270 FreeOnTerminate := True; Both thread classes destroy themselves when they finish, but the owner keeps the pointers and never nils them: * pu_main keeps TCPDaemon (and TCPDaemon4) as fields and dereferences them: StopServer: if (TCPDaemon = nil) or TCPDaemon.Finished then exit; TCPDaemon.TCPThrd[i].sock ... TCPDaemon.stoping := True; MenuStatusClick: if (TCPDaemon<>nil)and(not TCPDaemon.Finished) line 4440: if (TCPDaemon<>nil) then StopServer; Reading TCPDaemon.Finished IS the use-after-free. The nil guard cannot help because the variable is never set to nil. * TTCPDaemon.TCPThrd[1..Maxclient] holds client threads that free themselves. The array slots are never cleared, and both the accept loop (cu_tcpserver.pas:214-221) and StopServer read .Fsock / .sock / .terminated through them. The accept loop is usually saved by short-circuit evaluation - ThrdActive[i] is cleared in the worker's finally block before the object dies - but that is luck, not design, and the ordering is not guaranteed. Fix: set FreeOnTerminate := False for both classes and free them explicitly from the owner after WaitFor; or keep FreeOnTerminate and nil the reference from TThread.OnTerminate (synchronised to the owning thread). Do not mix the two. Related, same area: * ThrdActive[] is written from the worker thread (via FTerminate(id), called from TTCPThrd.Execute's finally) and read from the daemon thread with no synchronisation. * RestartServer (pu_main) does StopServer; wait(2); StartServer. The old daemon may still hold the listening socket, so the new bind can fail while the old daemon object is orphaned. ================================================================================ 5. [HIGH] Integer overflow bypasses the FITS image-size guard ================================================================================ File : cu_fits.pas Lines: 39 (declaration), 2412 (the check) 39 bitpix,naxis,naxis1,naxis2,naxis3 : integer; ... 2412 if (FFitsInfo.naxis1*FFitsInfo.naxis2)>(maxl*maxl) then 2413 raise exception.Create('Image too big! ...'); naxis1 and naxis2 are 32-bit Integers and the multiplication is done in 32 bits. A header claiming NAXIS1=100000, NAXIS2=100000 gives 1e10, which wraps to a small (possibly negative) value, passes the guard, and falls through to SetLength(Fimage, n_plane, Fheight, Fwidth) with the unvalidated dimensions. Header values arrive from an untrusted file and are parsed with bare strtoint (cu_fits.pas:2187-2191), so a corrupt or hostile FITS reaches this path directly. Fix: if (Int64(naxis1)*Int64(naxis2)) > (Int64(maxl)*maxl) then ... Also reject negative or zero NAXISn explicitly. -------------------------------------------------------------------------------- 5b. [MED] 32-bit stream offsets limit FITS files to 2 GB -------------------------------------------------------------------------------- File : cu_fits.pas, TReadFits.Execute 1081 streamstart, startline, endline, xs, ys: integer; 1103 streamstart:=fits.fhdr_end+round(xs*startline*abs(fits.FFitsInfo.bitpix/8)); 1121 fits.FStream.Position:=streamstart+streaminc*sizeof(d64); streamstart is Integer, and streaminc*sizeof(d64) is Integer*Integer. Both overflow past 2^31. A 20000x20000 float64 image - which the maxl=20000 guard explicitly permits - is 3.2 GB, so the guard allows files this code cannot address. The result is a truncated offset and garbage pixels, not an error. Fix: declare streamstart (and the offset expression) as Int64. ================================================================================ 6. [HIGH] Unsafe thread join in TFits.ReadFitsImage ================================================================================ File : cu_fits.pas, lines 2449-2477 2450 timeout:=60; 2451 timelimit := now + timeout / secperday; 2452 repeat 2453 sleep(100); 2454 working := False; 2455 for i := 0 to tc - 1 do 2456 working := working or thread[i].working; 2457 timingout := (now > timelimit); 2458 until (not working) or timingout; If the 60-second timeout fires while workers are still running, execution falls straight through to code that assumes they have stopped: * lines 2460-2468 read thread[i].dmin/dmax/sum/sum2/ni/hist while the workers are still writing them - a data race producing wrong statistics. * line 2471 DoneCriticalSection(ReadFitsCS) destroys a critical section that a worker may be inside (TReadFits.Execute enters it every 360/720/2880 pixels). That is undefined behaviour. * lines 2472-2474 Free the still-running threads. 60 s is not generous: a multi-gigabyte float image on a slow or network disk reaches it routinely. Fix: join properly. With FreeOnTerminate=False (which is already the case), call thread[i].WaitFor before touching any result field, and drop the timeout - or keep a watchdog that aborts the whole operation rather than continuing. Also in the same routine: * line 2408 checks "if FFitsInfo.naxis1=0 then exit" but never checks naxis2. With NAXIS2=0, Fheight=0, no worker loop body runs, ni stays 0, and line 2479 Fmean:=sum/ni divides by zero. * line 2480 Fsigma:=sqrt((sum2/ni)-(Fmean*Fmean)) uses the cancellation-prone form. On a near-uniform frame (bias, flat, saturated) the argument can go slightly negative through rounding and sqrt raises EInvalidOp or returns NaN. Use max(0, ...) at minimum, or accumulate with Welford's algorithm. * InitCriticalSection at 2441 and DoneCriticalSection at 2471 are not exception-safe; any raise in between leaks the critical section. ================================================================================ 7. [HIGH] Memory leaks on error paths ================================================================================ 7a. cu_fits.pas:1891 TFits.LoadFromFile 1898 mem:=TMemoryStream.Create; 1901 i:=UnpackFits(fn,mem,rmsg); 1902 if i<>0 then begin 1903 ClearImage; 1904 msg('FITS decompression error ...'); 1905 exit; <-- mem never freed ... 1909 mem.LoadFromFile(fn); <-- can raise; mem never freed Note that on the success path ownership passes to SetStream (line 1913), so the leak only occurs on the two failure paths - which is exactly why it has gone unnoticed. Wrap in try/except and free mem before re-raising or exiting. 7b. cu_fits.pas:1860 TSaveFits.Execute The thread frees mem on the success path (line 1878) but the except handler (1880-1886) does not. Every failed save - disk full, read-only directory, permission error, network share dropped - orphans a full image buffer. Because FreeOnTerminate is true the thread object disappears and the stream is unreachable. On a long unattended sequence with a failing disk this grows without bound. 7c. cu_fits.pas:1804 TFits.SaveToFile, synchronous path mem.SaveToFile(fn) at lines 1840/1848 can raise; mem.Free at line 1851 is not in a finally. Same leak, main thread. 7d. pu_main.pas:15554 LoadRawFile and :15602 LoadPictureFile Both create RawStream/PictStream AND FitsStream, but the finally block frees only the first one. FitsStream is normally adopted by "fits.Stream:=FitsStream" (TFits.SetStream takes ownership), so the success path is fine - but: * the "if FitsStream.size<2880" branch skips the assignment entirely; * any exception before the assignment skips it too. Add FitsStream to the finally with a flag, or restructure so ownership transfer is the last statement in the try. 7e. pu_main.pas:15669 CCDCIELMessageHandler The first line is "if AppClose then exit;". Messages posted with PtrInt(strnew(PChar(...))) (cu_astrometry_engine.pas:596, 665, 678, 747, 760, 820, 832, 842, 848; cu_fits.pas:1874, 1885, 3446, 3467) are then never StrDispose'd. Minor in absolute terms, but it is the only place those allocations can be released. ================================================================================ 8. [MED] Shared fixed temp filename races between threads ================================================================================ File : cu_fits.pas, lines 1839 and 1866 tmpf:=slash(TmpDir)+'tmppack.fits'; The identical hard-coded name is used by the synchronous SaveToFile path and by TSaveFits.Execute running in a background thread. Two concurrent saves - or an async save overlapping a sync one, which the Async parameter exists to allow - write to the same file and then compress whichever version won the race. The output .fz can contain another exposure's data. Fix: derive a unique name (GetTempFileName, or append the thread id / a counter), and delete it when done - the current code never removes it either. ================================================================================ 9. [MED] Credential storage defects ================================================================================ File : u_utils.pas (EncryptStr/DecryptStr/hextostr), u_global.pas:377 Used : pu_devicesetup.pas:1687-1739+ for all ASCOM Alpaca/REST user+password 9a. hextostr silently returns the ciphertext as plaintext u_utils.pas: k := strtointdef('$' + str[2*i+1] + str[2*i+2], -1); if k > 0 then Result := Result + char(k) else begin Result := str; // if not numeric default to the input string break; end; The guard is "k > 0", not "k >= 0". A legitimate $00 byte in the ciphertext - which RotateBits can and does produce - aborts decoding and returns the raw hex STRING as if it were the decoded value. The user then authenticates with a hex blob instead of their password and gets an unexplained 401. Change to k >= 0, and distinguish "invalid hex" (should be an error) from "byte 0". 9b. DecryptStr destroys leading/trailing spaces EncryptStr pads with 15 spaces when encoding; DecryptStr undoes this with a blanket trim(). Any password that legitimately begins or ends with a space is silently corrupted. Use a length prefix or an explicit terminator instead. 9c. The key is a compile-time constant u_global.pas:377 encryptpwd='m=Nrv"wE+W^RA?$b:]w3$B?3";~OG9\7...' Everyone running CCDciel has the same key, so this is obfuscation against casual inspection of the config file, not encryption. That may be an accepted trade-off, but the function names EncryptStr/DecryptStr promise more than they deliver. At minimum rename them (ObfuscateStr/DeobfuscateStr) and document the threat model; better, use DPAPI / libsecret / Keychain. ================================================================================ 10. [MED] TCP/HTTP server hardening ================================================================================ File : cu_tcpserver.pas 10a. Unbounded Content-Length (line 512 ProcessPost / 306-330 Execute) if Pos('CONTENT-LENGTH:',UpperCase(buf))=1 then begin delete(buf,1,15); cl:=StrToIntDef(trim(buf),0); end; ... if cl>0 then Fbody:=RecvBufferStr(cl,500); No upper bound. "Content-Length: 2000000000" forces a 2 GB allocation from an unauthenticated client. Clamp to a sane maximum and reject the rest. 10b. Unbounded body read when Content-Length is 0 else if cl=0 then begin repeat Fbody:=Fbody+RecvPacket(500); until LastError<>0; end; Reads until the peer errors out, with O(n^2) string concatenation. Both a memory and a CPU DoS. Use a size cap and a TStringStream / TMemoryStream. 10c. No authentication anywhere The raw command channel and the HTTP GET/POST channel both dispatch into TCPcmd / TCPjsoncmd, which drive the mount, camera and sequencer. There is no token, no password, no origin check. If the server is bound to a routable address this is unauthenticated remote control of the observatory. Recommend: default to loopback, and require a shared secret for anything that is not read-only. (There is an isLocalIP helper in u_utils.pas that is not used here.) 10d. Fatal socket errors do not stop the daemon (lines 180-202) After CreateSocket/bind/listen the code only calls Synchronize(@ShowError) and then falls through into "repeat ... until False". If bind fails - the common "port already in use" after a failed RestartServer - the thread spins forever calling Accept on an unbound socket. Exit the Execute method on a fatal error instead. 10e. Property name collision (line 78-98) TTCPThrd exposes "onTerminate" of type TIntProc, which hides the inherited TThread.OnTerminate: TNotifyEvent. A future reader (or a future maintainer adding standard TThread cleanup) will assume the inherited semantics. Rename to onSlotFree or similar. 10f. Blanket "except end" at the end of TTCPThrd.Execute (line 374) Any unexpected failure in a client thread vanishes without a log entry. ================================================================================ 11. [MED] 171 silently swallowed exceptions ================================================================================ A scan of the implementation sections found 171 except blocks whose body is empty or is "on E: Exception do ;". They are concentrated in the device drivers, e.g.: cu_ascomcamera.pas:475-484 try FBinX:=V.BinX; except end; try FBinY:=V.BinY; except end; cu_ascomrestweather.pas:403-480 (twelve consecutive empty handlers) cu_ascommount.pas:773, 787, 1217 cu_ascomrestmount.pas:740, 750, 1115 cu_ascomrestcamera.pas:1019, 1069, 1305, 1354 For genuinely optional ASCOM/Alpaca properties this is defensible - the spec does allow a driver to throw PropertyNotImplemented. But as written: * the target variable silently keeps its previous value, so a transient comms failure is indistinguishable from "property not supported" and stale data is presented as live; * there is no trace at any log level, so a user reporting "the temperature stopped updating" leaves nothing to diagnose; * a real fault (device unplugged, driver crashed) is absorbed along with the benign case. Suggested pattern - keep the tolerance, lose the silence: function TryGetDouble(const name: string; out v: double): boolean; begin Result := false; try v := ...; Result := true; except on E: Exception do begin if not FNotImplemented[name] then begin FNotImplemented[name] := true; // log once, not every timer tick msg(name + ': ' + E.Message, 9); end; end; end; end; Then the caller can distinguish "never supported" from "stopped working". ================================================================================ 12. [LOW] Angle normalisation loses precision ================================================================================ File : u_utils.pas function Rmod(x,y:Double):Double; begin Rmod := x - Int(x/y) * y ; end; function to360(x:Extended):Extended; begin result:=rmod(x+3600000000,360); end; function to180(x:Extended):Extended; begin result:=rmod(x+3600000000,360); if result>180 then result:=result-360; end; The +3,600,000,000 offset exists because Int() truncates toward zero, so Rmod returns a negative result for negative x. The consequence is that the subtraction inside Rmod cancels two numbers of magnitude 3.6e9 to produce a result of magnitude <360: about ten significant digits are lost. On x86_64 Windows FPC maps Extended to Double (64-bit), so the absolute error is approximately 3.6e9 * 2.2e-16 ~= 8e-7 degrees ~= 3 milliarcseconds. That is below most guiding tolerances but is not nothing for polar alignment and plate-solve residuals, and it is entirely avoidable: function to360(x: double): double; begin Result := FMod(x, 360); // Math unit, sign of x if Result < 0 then Result := Result + 360; end; The magic constant also silently fails for |x| > 3.6e9. ================================================================================ 13. [LOW] Unguarded conversions when parsing FITS headers ================================================================================ File : cu_fits.pas, TFits.GetFitsInfo, lines 2187-2205+ if (keyword='BITPIX') then bitpix:=strtoint(buf); if (keyword='NAXIS') then naxis:=strtoint(buf); if (keyword='BZERO') then bzero:=strtofloat(buf); ... Bare strtoint/strtofloat on values taken from a file. A truncated, hand-edited or non-conforming header raises EConvertError from inside GetFitsInfo. The caller chain LoadFromFile -> LoadStream -> GetFitsInfo has no handler (SetStream has one, but LoadStream is called outside it), so the exception surfaces as a raw error dialog during an unattended sequence. Use StrToIntDef / StrToFloatDef with sentinel defaults and mark the header invalid, as the code already does for NAXIS1 at line 593. (Locale is handled correctly - pu_main.pas:1525 forces DefaultFormatSettings.DecimalSeparator:='.' and 1540 sets Application.UpdateFormatSettings:=False - so this is purely about malformed input.) ================================================================================ 14. [LOW] SafeFileName does not make a filename safe ================================================================================ File : u_utils.pas result:=StringReplace(fn,'*','',[rfReplaceAll]); result:=StringReplace(result,'/','',[rfReplaceAll]); result:=StringReplace(result,'\','',[rfReplaceAll]); result:=StringReplace(result,':','',[rfReplaceAll]); Path traversal is blocked (both separators are removed), but the following still pass through and cause a failed file creation on Windows: ? " < > | and control characters #0..#31 trailing '.' or ' ' reserved device names: CON PRN AUX NUL COM1..COM9 LPT1..LPT9 an empty result (a name consisting only of stripped characters) Object names reach this function from user input and from planetarium/SIMBAD lookups, so odd characters are realistic. Add the missing characters, reject or rename reserved words, trim trailing dots/spaces, and substitute a default when the result is empty. ================================================================================ 15. [LOW] Assorted smaller items ================================================================================ 15a. u_utils.pas IsNumber is not reentrant var dummy_ext : extended; // unit-level global, line ~198 function IsNumber(n : string): boolean; begin result:=TextToFloat(PChar(n),Dummy_ext); end; Two threads calling IsNumber concurrently write the same global. Make it a local variable; there is no reason for it to be shared. 15b. u_utils.pas quicksort is declared "inline" but is recursive FPC cannot inline a recursive routine, so the directive is ignored (and may produce a hint). Worth removing to avoid the misleading claim. The nested "sort" also has no recursion-depth guard; the median-of-three pivot it uses makes pathological input unlikely but not impossible. 15c. u_utils.pas SortFilterListInc contains two dead statements list.Move(j, j-1); list[j] := tmpname; // no-op TFilterExp(list.Objects[j]).ExpFact := tmpexp; // no-op TStringList.Move already moves both the string and its object, so after the Move both assignments write back exactly the values that are already there. They are harmless but signal that the author was unsure what Move does; a future edit based on that misunderstanding would be a real bug. It is also an O(n^2) bubble sort where TStringList.CustomSort would do. 15d. cu_fits.pas SaveToFile mutates the header as a side effect Lines 1810-1827 rewrite BITPIX/BSCALE/BZERO and set FStreamValid:=false when saving a stack as float. A method named SaveToFile permanently changes the in-memory object. If the user saves and then continues to work with the same TFits, the header no longer describes the data. 15e. cu_fits.pas Delete-then-Insert idiom depends on undocumented behaviour i:=FHeader.Indexof('BITPIX'); if i>=0 then FHeader.Delete(i); FHeader.Insert(i,'BITPIX',FFitsInfo.bitpix,''); When the keyword is absent, i is -1 and Insert(-1,...) falls into its "add key at end" branch (cu_fits.pas:937-942), appending the card AFTER the END record - producing a non-conforming FITS header. Everywhere else the code correctly writes Insert(FHeader.Indexof('END'), ...). Note also that Insert already replaces an existing key in place (lines 917-925), so the preceding Delete is redundant. Same pattern at lines 4176-4183. 15f. cu_fits.pas 8-bit write scaling (line 2562) x:=max(min(round(((Fimage[k,ii,j]/255)-bzero)/bscale),MAXBYTE),0); Fimage is scaled 0..65535. Dividing by 255 gives 0..257, so everything above 65025 clips to 255. The correct divisor for 16->8 bit is 257 (65535/257 = 255 exactly). 15g. u_utils.pas GetThreadCount undercounts on large Windows machines for i := 0 to 31 do ... ProcessAffinityMask and Mask Only 32 affinity bits and only the current processor group are examined. On a >32-thread or multi-group machine the count is wrong (and the value feeds MaxThreadCount, which is capped at 16 anyway, so the impact is small). 15h. u_utils.pas AirMass wraps a pure arithmetic expression in try/except Since h>0 is already guaranteed by the enclosing if, the denominator (165 + 47*h**1.1) cannot be zero and the handler is unreachable. Dead code that suggests an unclear invariant. ================================================================================ END OF BUG REPORT ================================================================================