la_mojo: fix memory leaks and heap corruption #7
Merged
ClaudeAI
merged 1 commits from fix/la_mojo-memory-leaks into master 22 hours ago
Loading…
Reference in new issue
There is no content yet.
Delete Branch 'fix/la_mojo-memory-leaks'
Deleting a branch is permanent. It CANNOT be undone. Continue?
Summary
Fixes the memory leaks and heap corruption found while analyzing
Projects/la_mojo(Debug86configuration). The full analysis report is attached to this PR as a comment.Leaks that grew continuously
protocol.cpp): when the pool of unused packets overflowed, it removed the oldest packet without freeing it and freed the newest one while it was still pooled. Once the pool was full, every packet a handler didn't use leaked, for example traffic for other sensors on a shared bus. Fixed the overflow, free the pool in the destructor andgetPackage(), and usememmovefor the overlapping buffer shifts.Query(): the result loop now runs only whilesqlite3_step()returnsSQLITE_ROW. Before, it looped untilSQLITE_DONEand allocated rows forever onSQLITE_BUSYor errors. Added a 2-second busy timeout, closed handles after a failed open, and fixedescapeBinary()writing into uninitialized memory.basicThread/basicDualThread: threads that ended on their own were never joined, so their stacks leaked on every stream drop or restart. Now every thread is joined exactly once, or detached when it stops itself, andpthread_createerrors are checked correctly.curlRequest: the header list is now freed, uninitialized members are initialized, andcurlRequestsManagerdeletes requests it can't queue.streamHandler: frames left in the encoder queue are freed on destruction.Heap corruption
kernelModuleFactory: a module that failed to start was deleted twice.mojoRemoteClient:basicRing::push()returns an element ID, which can be 0, not a bool. The checks now compare with-1. Also fixed leaks inpacketExtractorand the destructor.utilizeBasicEvent: event payloads are allocated withmalloc, so they're now released withfree.videoAVLIBSource: fixed a scaler-context double free and the order of a NULL check.trim(): usesmemmovefor an overlapping copy.Smaller leaks
Duplicate query in
dropSession, LRF upload data, report-backupper and fly-hunter settings, the Kafka consumer handle, and the BVMS unique ID.Testing
.cppfile compiles with theDebug86flags, and warning counts are unchanged.streamHandler.cppwas checked with a stub live555 header because live555 isn't packaged in the check environment.wiringx, live555, the databases and the hardware weren't available. Please run it on the target before merging.Behavior changes to watch
Suggested verification
Run the new build next to the old one for about an hour and compare
VmRSSandVmSizein/proc/<pid>/status, or run it underheaptrackor an AddressSanitizer build.Generated with Claude Code
https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
Memory leak analysis report
la_mojo – memory leak analysis
Scope: the 106 source files the
Debug86configuration ofProjects/la_mojo/makefilebuilds (≈81k lines, all underlib/).Method: static review of allocation/ownership paths plus cppcheck. Nothing was built or run, so every finding below comes from reading the code; sizes and rates are estimates.
Paths are relative to
dr_frucht/lib/.A. Leaks that grow continuously (most likely cause of the "huge" growth)
A1. Protocol parser package pool: one leaked packet per unconsumed packet, forever
data/protocol/protocol.cpp:230-240(and the thread variant at:326-336)Nothing in la_mojo ever reads
m_vPackagePool(getPackage()has no callers), so once 32 packets are pooled every further unconsumed packet leaks aprotocolPackageplus its data buffer.Who returns
falsefrompacketHandler()(= "not consumed"):device2DSensor::packetHandler(App/common/deviceNode2D.cpp:3343) for every packet whose device ID is not its own. With several sensors on one serial bus / ETH2UART gateway, every sensor's parser receives the other sensors' traffic, so this runs at full sensor data rate.protocolBVMS::packetHandlerfor any non-200 response,protocolPTZ_VISCAfor empty packets.Fix: unconsumed packets are not used anywhere, so free them immediately:
(If you want to keep the pool, free the element you erase:
protocolPackage *old = m_vPackagePool.front(); m_vPackagePool.erase(begin); dataEraser(old->m_pData); free(old);.)Also:
getPackage()(:416) frees the struct but notm_pData, and~protocolParser()never frees the pool.Related corruption:
memcpy(m_pParserBuffer, m_pParserBuffer + n, …)at:204, :218, :308, :324copies overlapping memory → must bememmove.A2. Video encoder queue is not drained when a stream handler is deleted
App/common/streamHandler.cpp:725(producerpushFrame) / destructor:137(Corrected: the first version of this report called the queue unbounded.
streamHandler.h:176definesEVE_ENABLE_DROP_OUTPUT_FPS, which caps it at about 11 frames.)Every decoded frame is copied into a
mallocedENCODING_BUFFERand pushed tom_qEncodingQueue. When a stream stalls or its encoder thread stops,kernelModuleEmbedVideodeletes and re-creates the handler (kernelModuleEmbedVideo.cpp:1804-1813,:1874-1887), but neithercloseAll()nor the destructor frees the frames still waiting in the queue: up to about 11 full frames (raw BGR in this build, a few MB) per re-creation. With a camera that keeps dropping, this adds up.Fix: in the destructor, after the encoder thread is joined, pop and free everything left in the queue.
Note: in
streamHandler.hthe guard is#ifndef MEKOROT_PROJECT__(two underscores) while the makefile definesMEKOROT_PROJECT_(one), so video output is compiled in for every configuration – probably not intended. Also,kernelModuleEmbedVideo.h:11definesEVE_WORK_WITH_MEDIAMTX, so this build uses the OpenCV output path and the built-in MJPEG web server code is not compiled.A3. SQLite
Query()allocates forever on BUSY / ERRORdata/sqlite/sqlite_class.cpp:292If
sqlite3_stepreturnsSQLITE_BUSY(another connection/process holds the lock – three DB files, non-persistent connections, other processes such as the web UI) orSQLITE_ERROR/SQLITE_MISUSE, it never returnsSQLITE_DONE; the loop spins forever allocating a newAssoc(with all column strings) per iteration → RAM explodes within seconds while the thread hangs.Fix:
while ((rc = sqlite3_step(query)) == SQLITE_ROW) { ... }and handlerc != SQLITE_DONEas an error; setsqlite3_busy_timeout(m_pDBLink, 2000)after each open.Also
escapeBinary()(:389,:396)strncats into uninitialisedmallocbuffers → heap corruption; andSQLITE_NULLcolumns re-use the previous column's value.A4. Threads that end on their own are never joined (stack leak per restart)
components/base/basicThread.cpp:85(same pattern inbasicDualThread.cppwaitThreadAEnd/BEnd)When a thread finishes by itself (status
TH_EXIT),waitThreadEnd()returns withoutpthread_join, so the thread's stack (8 MB virtual by default) and descriptor are never released. This happens on every video stream drop (videoAVLIBSource,videoLIVE555Source,streamHandlerencoder all setTH_ENDEDon error and are then deleted/re-created), every failed module/node start, etc.On a 32-bit Raspberry Pi build (
RASPI_HARDWARE) a few hundred reconnects exhaust the address space.Fix: keep a
bool m_bJoinableset ininit(); inwaitThreadEnd()alwayspthread_joinif joinable (after waiting forTH_EXIT), then clear it. Alsopthread_createreturns an error number, not-1– check!= 0.A5. Every HTTP request leaks its header list
data/curl/curlRequest.cpp:137-140, 212-215; destructor:69m_HeaderList(2–5curl_slistnodes with duplicated strings) is never freed. Every ONVIF/Bosch/BVMS/REST request leaks it.Fix:
curl_slist_free_all(m_HeaderList);in the destructor.Also: the
(Host, Path)constructor never initialisesm_pPostData(destructor then frees a garbage pointer), andm_cContentTypeis uninitialised whencntType == NULL.curlRequestsManager::accomplish()failure leaks the request in all callers (get,post,ponvif.cpp:2377,bosch_rcp.cpp:833,kernelModuleBosch.cpp:87).A6. Modem manager leaks the phonebook list every 5 s
App/common/kernelModuleModemManager.cpp:70–listPhonebook()returns anewedDBC_INT_LISTthat is never deleted.validate()→reloadSettings()runs every module-factory cycle (5 s) while the modem is idle. Fix:delete pList;at the end.A7. Pending-node list grows every second
App/common/deviceNodeFactory.cpp:441–m_nPendingNodes.push_back(id)on every failed node creation; nothing ever removes entries. A node that keeps failing adds an entry every factory cycle (1 s). Fix: only push if not already present, and erase on success.A8. Remote-server command queue has no limit
App/mojo/mojoRemoteClient.cpp:1169–mojoKernel::dispatchEventforwards every event toaddEvent(), which mallocs a record intom_qCMD. Transactions are sent one at a time with an ACK round-trip, so if the event rate is higher than that throughput (many sensors, slow link) the queue grows without bound until the next reconnect flush. Consider a cap / filtering event types (EVT_SCAN,EVT_FLIP…).B. Heap corruption (can look like leaks, causes random crashes)
App/common/kernelModuleFactory.cpp:263-282startService()fails the module is deleted in theswitchand again bydelete(tVal)→ double delete. The module stays "new" in the DB, so this repeats every 5 s. Remove the seconddelete.App/mojo/mojoRemoteClient.cpp:266, 966, 1191vsbasicRing::push()push()returns a global running ID (starts at 0, wraps), not success.if (push(x))treats ID 0 as failure and frees a record that is still queued → use-after-free;if (!push(x))frees on ID 0. Compare with!= -1everywhere.components/base/basicEvent.cpputilizeBasicEventTARGET_DATAandFH_*payloads aremalloced by producers (prepareTargetData,prepareSimData, …) but released withdelete– allocator mismatch (ASan/valgrind will flag every target). Usefreeconsistently.data/sqlite/sqlite_class.cpp:389, 396strncaton uninitialised malloc memory (see A3).data/protocol/protocol.cpp:204, 218, 308, 324memcpy(see A1).data/media/video/videoAVLIBSource.cpp:245sws_freeContextwithout setting the pointer to NULL; a second_close()(destructor) frees it again.C. Smaller / one-off leaks
App/mojo/mojoRemoteClient.cpp:131-149packetExtractortPackbut nottPack->m_pData(alsomallochappens before the size check).App/mojo/mojoRemoteClient.cpp:57destructordelete(*idx)on amallocedVTR_HELPER; thenewedmojoVideoTransferHelperinside is never deleted.App/common/kernelModuleEmbedVideo.cpp:1580-1597(stopService/uninit, also:205-213,:224-232)pthread_cancelwithoutpthread_join,WEB_HANDLER+CTXnever freed, sockets/pipes not closed. Not compiled in this build (EVE_WORK_WITH_MEDIAMTXis defined), so not fixed.App/common/SQLite_dataBinder.cpp:965dropSessionm_pDataReports->Query(tQBuf);– result discarded.App/common/deviceNode2D.cpp:3065getLRFUploadData()result never freed (per uploaded file).App/common/kernelModuleReportBackupper.cpp:20getReportBackupData()result never freed.App/common/kernelModuleFlyHunter.cpp:46getFlyHunterData()result never freed;m_pProtocoloverwritten on restart.data/protocol/protocolKAFKA.cpp:561m_pConsumeris never deleted in the destructor (librdkafka handle with its own threads/buffers).data/protocol/protocolBVMS.cpp:39MD5String()result leaked on everybuildUniqID().D. Recommended next steps
Debug86with-fsanitize=address -fno-omit-frame-pointer(add toCOMPILEandLINK), run for 10–15 minutes with real sensors/cameras attached, stop cleanly (SIGINT) and read the LeakSanitizer report; orheaptrack ./mojo_d(Debian packageheaptrack) – it shows allocations that are still growing, which is better for long-running daemons than valgrind's end-of-run report;VmRSSandVmSizein/proc/<pid>/status, plusls /proc/<pid>/task | wc -l: growing VmSize with a constant thread count points to A4.malloc/freeownership of DB getter results withstd::unique_ptr(or return by value), and bound every producer/consumer queue.cd74a030af.