-
Notifications
You must be signed in to change notification settings - Fork 121
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Static code check findings -- Possible memory leak in realloc #202
Comments
laszloh
added a commit
to laszloh/ESPuino
that referenced
this issue
Mar 4, 2023
Fixes finding biologist79#202 and adds missing guards against NULL returns from malloc and friends Also adds missing calls to "free" before return statements.
Merged
laszloh
added a commit
to laszloh/ESPuino
that referenced
this issue
Mar 7, 2023
Fixes finding biologist79#202 and adds missing guards against NULL returns from malloc and friends Also adds missing calls to "free" before return statements.
laszloh
added a commit
to laszloh/ESPuino
that referenced
this issue
Mar 7, 2023
Fixes finding biologist79#202 and adds missing guards against NULL returns from malloc and friends Also adds missing calls to "free" before return statements.
biologist79
pushed a commit
that referenced
this issue
Mar 10, 2023
commit 7b1c48c Author: Laszlo Hegedüs <laszlo.hegedues@gmail.com> Date: Fri Mar 10 18:36:58 2023 +0100 Always free playlist memory when SdCard_ReturnPlaylist is called commit 96d22be Author: Laszlo Hegedüs <laszlo.hegedues@gmail.com> Date: Fri Mar 10 18:30:13 2023 +0100 Fix heap corruption due to insufficent memory allocation Here we need brackets to force the correct memory size calculation (point before line calculations) commit 410db7d Author: Laszlo Hegedüs <laszlo.hegedues@gmail.com> Date: Fri Mar 10 18:27:59 2023 +0100 Harmonize return value of SdCard_ReturnPlaylist Return nullptr on error and a pointer to the first element of the arra on success. commit 3ffabde Author: Laszlo Hegedüs <laszlo.hegedues@gmail.com> Date: Fri Mar 10 18:24:30 2023 +0100 Correct the name of the "sort" function to randomize commit cab1aa5 Author: Laszlo Hegedüs <laszlo.hegedues@gmail.com> Date: Fri Mar 3 15:40:58 2023 +0100 Add missing free Add missing free to return statements and also free the allocated char* array after releasing all strings form it. commit be26f5a Author: Laszlo Hegedüs <laszlo.hegedues@gmail.com> Date: Fri Mar 3 15:27:38 2023 +0100 Do not duplicate string before xQueueSend xQueueSend creates a copy of the data in it's internal memory. So there is no need to duplicate the data beforehand. commit 14cd93b Author: Laszlo Hegedüs <laszlo.hegedues@gmail.com> Date: Fri Mar 3 15:23:19 2023 +0100 Correct realloc usage and add missing guards Fixes finding #202 and adds missing guards against NULL returns from malloc and friends Also adds missing calls to "free" before return statements. commit d371177 Author: Laszlo Hegedüs <laszlo.hegedues@gmail.com> Date: Fri Mar 3 15:20:27 2023 +0100 Use heap & globals memory region for static buffers Reduce the number of heap allocations (and with this heap fragmentation) by allocaing static lenght buffers on the stack or global memory regions instead of the heap.
laszloh
added a commit
to laszloh/ESPuino
that referenced
this issue
Mar 15, 2023
Fixes finding biologist79#202 and adds missing guards against NULL returns from malloc and friends Also adds missing calls to "free" before return statements.
flofricke
added a commit
to flofricke/ESPuino
that referenced
this issue
Dec 10, 2023
* Use heap & globals memory region for static buffers Reduce the number of heap allocations (and with this heap fragmentation) by allocaing static lenght buffers on the stack or global memory regions instead of the heap. * Correct realloc usage and add missing guards Fixes finding biologist79#202 and adds missing guards against NULL returns from malloc and friends Also adds missing calls to "free" before return statements. * Do not duplicate string before xQueueSend xQueueSend creates a copy of the data in it's internal memory. So there is no need to duplicate the data beforehand. * Add missing free Add missing free to return statements and also free the allocated char* array after releasing all strings form it. * Correct the name of the "sort" function to randomize * Harmonize return value of SdCard_ReturnPlaylist Return nullptr on error and a pointer to the first element of the arra on success. * Fix heap corruption due to insufficent memory allocation Here we need brackets to force the correct memory size calculation (point before line calculations) * Always free playlist memory when SdCard_ReturnPlaylist is called * Add fallback text AP setup Add text to AP setup in case javascript does not work (f.e. older WebView implementations / captive portals) * Fix captive portal By hijacking DNS request made by Android and responding with our AP setup page, we can force the phone into captive portal mode. This will automatically redirect the user to the setup page as soon as he connects to the access point. * Fix for playing files via Web-UI for Arduino >=2.0.5 * Led.cpp: Separate and rework playlist progress animation * Led.cpp: Separate and rework battery measurement animation * Led.cpp: Separate and rework volume animation * Led.cpp: Separate and rework track progress animation * Led.cpp: Simplify animation function calls * Led.cpp: Separate and rework shutdown/boot animation * Led.cpp: Separate and rework error/ok and voltage warning animations * Led.cpp: Separate and rework webstram and pause animations * Led.cpp: Separate and rework idle animation * Led.cpp: Separate and rework rewind and busy animation * Led.cpp: Separate and rework speech animation * Led.cpp: Fix idle animation after playlist finished * Led.cpp: Constify startNewAnimation parameter * Bugfix: Corrupted files after HTTP-upload Bugfix: playlistcache was invalid after "Rename" * set default environment to arduino2 on dev-branch * feature: command-execution on control-site of webserver * Led.cpp: Add some comments * Led.cpp: Cleanup animation functions and add more comments * Led.cpp: Fix warnings for unused or uninitialized variables * pause some tasks for speedup & smoother HTTP upload allow multiselect delete of files in contextmenu, not only the one focused * Fix for stuck LED-Shutdown animation This commit fixes both parts of the Bug raised in the [forum](https://forum.espuino.de/t/bug-in-verbindung-mit-dem-led-ring-und-multibutton/1825?u=laszloh) * Fix errorous indicator in case no audio is playing * Change rotary encoder to delta mode Instead of calculating the audio volume with the position of the rotary encoder, just use it in a delta mode by resetting the counter after each read so it starts by zero. This allows us to just send the delta to the volume handler. * Make compile for ESP32-S3 See discussion https://forum.espuino.de/t/esp32-s3-wie-kompilieren/1865/2 Thanks to @tuniii ! * Change volume animation to triggered mode Make it so, that the volume animation can be triggered and always trigger it, even if we have reached min or max value. This fixes the feature request https://forum.espuino.de/t/verhalten-der-lautstaerke-anzeige-auf-dem-led-ring/1842/8 * Lost feature „PLAY_LAST_RFID_AFTER_REBOOT“ for webstreaming (local m3u file) reactivated. * Move global platformio flags to env Move all platformio flags which affect every target to the global env section. Exception ito this is `board_build.partitions` which defaults to 4mb partition. Every target with a different partition layout is responsible to overwrite the flag with their own partition layout. * Add global build flags Move the common build flags to the global env and make sure all other targets import the global flags when they extend it. * Transition to c++17 Enable c++17 features. For a feature summary see https://github.com/AnthonyCalandra/modern-cpp-features * make compile again for 6.1.0 & 3.5.0 fix some warnings * build.yml: Trigger workflow for all branches We want to do CI builds for all branches. This allows us for example to check CI results on feature branches before merging. * Add printf wrapper for Logging Add the function Log_Printf implementation proposed by fschrempf which wraps vsnprintf around Log_Println. This function uses a static buffer of 201 byte (which is enough for most log messages) so it does not put additional pressure on the callers stack. * Add missing translations Use translation system instead of defining the string hardcoded in the source code * Move instances which used Log_Buffer previously to the Printf wrapper Change all occurences of snprintf(Log_buffer ...) + Log_Println to use Log_Printf. * Add the string formating characters to LogMessages Moving the string formating allows the translations to change the position of the embedded variables thus allowing for language dependent changes. * Remove unused Log_Buffer * Fix remaining string trunctation warnings Reworked Web_DeleteCachefile to get a folder instead of a file path. This makes the function smaller and easier * Fix comparison warning * allow to escape from bluetooth mode with an unknown card, switch back to normal mode https://forum.espuino.de/t/neustartschleife-nach-gescheitertem-anschluss-eines-bluetoothkopfhoerers/1886/16 * re-pin BT library: prevent i2s_write if i2s not started * Enforcing uniform codestyle * fix duplicated ids for command-execution * Fix HallEfectSensor compilation errors Fix compilation errors introduced by the transition to Log_Printf. * Move to CRGBArray and CRGBSets Change over to CRGBArray from native arrays and add an rgb set for the indicator. Update LEDs on request from the animation functions. Rename settings variable to enable easy independent led animation modes. Use c++17 "if constexpr()" feature to force compile time optimization of const expression branches * Restrict value ranges to guard array access * Update Readme * Removing HAL for ESPmuse (stale development) * Bugfixes: - fix crash playing a .Mp3/.mP3 files (make file extension really case-insensitive) - fix reading M3U playlist with comment lines ("#EXTINF") - fix mem-leak in loop openNextFile(), close to free file object - add own icon for playlists in Web-ui - add all audio formats supported by the ESP32-audioI2S library (.opus, .pls, .asx) - Stop playing before explorer contextmenu DELETE (can crash if deleted file is playing currently) * free mem after usage (x_strdup) * changes as suggested by @laszloh - thank's for reviewing! - file.close() not needed - always stop playback if deleting file from web-ui * Fix for SOC + code-style * speedup playlist generation & file listing by factor > 20 see discussion https://forum.espuino.de/t/beschleunigte-verzeichnisauflistung-bei-sehr-vielen-mp3s/1348 this PR is a cleanup from https://github.com/tueddy/ESPuino/tree/speedup_files @laszloh thanks for reviewing! * update fileValid() from master * Prepare for Arduino 2.0.8 * Add latest changes from dev * Add missing define for Arduino >= 2.0.8 * changes from review, thank's to @laszloh! * HallEffectSensor files: Source beautified with CLang format * Configure button with active HIGH. TTP223 capacitive touch switches (FinnBox) have their output active at HIGH level by default. Although this could be changed via onboard jumpers, it is much better to change this via software, otherwise the onboard LEDs will lit permanently while the touch is inactive! This will unnecessarily drain the battery. The INPUT_PULLUP PINs are also defined as high-impedance inputs for additional battery protection. * Adding missing parenthesis * Move message formatting into LogMessages Move formatted messages from MQTT and Web into the new format. * Remove usage of pgmspace.h header Remove all Makros and PROGMEM references from the source code. The ESP32 has a memory mapped Flash, so there is no reason to use the Makros. The pgmspace.h is for backward compability to be able to use AVR Arduino libraries. * disable Bluetooth feature by default until IRAM resource problems are solved * Arduino 2.0.8, PlatformIO package 6.2.0 re-enable bluetooth & make compile with all features * (re-)allow to compile without any RFID-reader (biologist79#235) * allow to compile without any RFID-reader refactor task pause/resume functions * add mssing taskhandle * check if we have RFID-reader enabled * Add support for control LEDs to be connected at the end of the NeoPixel Ring (biologist79#198) Thank's for contribution @mzanetti * .editorconfig: Add maximum line length of 100 for markdown files Note, that `max_line_length` is currently not supported in VSCode, but will hopefully be so in the future. * README.md: Improve formatting Fix the format style like spacing after headlines, etc. using VSCode auto format. Also set a maximum line length of 100 characters for easier handling of the file. No content changes included. * README.md: Improve style, language and content This contains a few small improvements for the README: * spelling/grammar/typo fixes * show screenshots in grid layout * use styled notes/warnings * merge redundant MQTT sections into one * Finalisation of README * Bluetooth.cpp: Fix logging crash in sink mode (biologist79#238) In sink mode a2dp_source is NULL which causes a crash when the state change callbacks are called. To fix this pass the correct pointer to the sink or source object via the callback state variable and use a cast to BluetoothA2DPCommon for accessing the to_str() method. * Add support for saving multiple wifi networks (biologist79#221) * Add support for saving multiple wifi networks * The new code scans available networks * Tries connecting to each known network, starting at the strongest one * Up to 10 SSIDs are saved in NVS * SSIDs can be added and removed --------- Co-authored-by: szenglein <szenglein> * disable WiFi.useStaticBuffers() spelling for Arduino 2.0.9 WiFi.useStaticBuffers() does not seem to bring any advantage just more memory use, so leave it outcommented at this moment * Arduino 2.0.9, PlatformIO package 6.3.0 revert pinned RC522-libraries (_FlashStringHelper bug is solved with Arduino 2.0.9 * Show Arduino version at startup & in web-info * BTSource: fix Stack canary watchpoint triggered (BtAppT) see bugreport: pschatzmann/ESP32-A2DP#422 * This developer branch has stricter compiler rules, fix some of (mostly harmless) warnings * migration from single-wifi setup: Initialize "use_static_ip" * fix error in log: [E][Preferences.cpp:96] remove(): nvs_erase_key fail: "xxx" * fix compiler warnings if MQTT_ENABLE is not defined * Wifi fixes (biologist79#240) * use uint32 to save IPAddress to NVS * fix (default) hostname in AP * fix deleting last remaining network * remove wifi printf logging --------- Co-authored-by: szenglein <szenglein> * Wifi: Log BSSID in scan and connection success * Reduce floating the log with redundant RSSI-messages: Log RSSI value only if it has changed by > 3 dBm * fix build error "Build all boards: All jobs have failed" due to last commit * improve neopixel display in Bluetooth speaker mode (BT-Sink) (biologist79#239) - BT-Sink disconnected: Show blue-violet (same as in BT-source mode) - BT-Sink connected: switch to blue - start audio: show neopixel in webstream mode but with blue leds - show volume change same as in other modes * Update README.md Reduce code lines, @laszloh thanks for reviewing! * impove get device name from NVS * FastLED 3.6.0, PlatformIO package 6.3.1 * update changelog.md * remove support for Arduino 1.0.6 & playlist cache (biologist79#243) * List available WiFi's in accesspoint view (biologist79#242) * List available WiFi's in accesspoint view * "bssid" hidden field removed * update changelog * Use bssid to connect to best WIFI and added option to always perform a WIFI-scan biologist79#241 Thank's to @Joe91 ! * Removal of upgrade-warning (2yrs should be enough) * introduce new playmode 'RANDOM_SUBDIRECTORY_OF_DIRECTORY_ALL_TRACKS_OF_DIR_RANDOM' which picks a random subdirectory from a given directory and do ALL_TRACKS_OF_DIR_RANDOM (biologist79#245) * Bluetooth configuration tab in web-interface (biologist79#244) * Bluetooth configuration tab in web-interface * spelling correction * Spelling corrections #2 * update revision & changelog * CMD_TOGGLE_WIFI_STATUS: Escape from BT-mode, WiFi cannot coexist with BT and can cause a crash * Web-UI improvements (biologist79#247) * webui improvements - log/info with bootstrap modal dialog - restart: auto redirect/reload - firmware update: show upload progress - firmware update: show detailed message on update error - Confirmation dialog for deleting saved WiFi * make /restart as POST replace $.get() with async fetch * Stricter hostname validation (biologist79#246). Thank's to @SZenglein !! * Move ScanWiFiOnStart to global wifiConfig (biologist79#248) bugfix for biologist79@a14386f#r118421830 * update PlatformIO package to 6.3.2 * web-upload improvement (biologist79#249) mprove speed and reliablility by using a new buffer system, bigger and defined chunk-sizes and larger write-cache. * Refactor web: Move dependant html-code from web.cpp to management.htm (biologist79#250) * refactor dependant html-code from web.cpp to management.html see https://forum.espuino.de/t/rfc-migration-zu-neuer-weboberflaeche/2013 * hide disabled tabs using CSS * update revision & changelog * CMD_TELL_IP_ADDRESS: IP as text (replace thousand separator with word "point") * Some spelling corrections, thanks to @SciLor ! * Update PN5180 library to fix compilation with DCORE_DEBUG_LEVEL=5 * fix volume jumping at startup when initVolume <> factory default (3u) fix log message for maxVolumeSet * Allow to compile without SD-card (webplayer only) - fix typo - update changelog * New ftp server by peterus (biologist79#254) - supports several connections (and also filesystems) - supports native utf-8 (no charset selection anymore) - much more stable and also faster - default-configuration of Filezilla works (no modification of the settings is needed anymore) Thank's @Joe91 for contribution! * update changelog & revisiob * update readme * Fix regression, SD-card was not working in SPI mode * Show received timestamp of NTP request in log * NTP: Allow to configure the timezone in settings.h fix .IRAM linking error from previous commit * Refactor shutdown procedure, add new command CMD_RESTARTSYSTEM * Show overall playtime total in web-ui * delete extensions.json (to add again) * re-add extensions.json * formatTimeToStr(): Fix wrong "minutes" * New command CMD_TELL_CURRENT_TIME for announcing the current time * Update third-party libriaries * increase stacksize for audio-task (audio-streams with SSL) see discussion: https://forum.espuino.de/t/dev-branch-reboot-beim-start-mancher-webstreams/2088 * Restart system: avoid peripheral power down while restarting * bugfix M3U-playlist + PREVIOUSTRACK, thank's to @niko! see https://forum.espuino.de/t/dev-branch/1835/270 * Web-UI: Replace the template processor (biologist79#253) * remove template-processor * fix showing values (slider, maxLength) * separate JSON settings into sections (neopixel, battery) Make "Reset" values to factory settings working * bugfix saving inactivityTime & always loading defaults * fix compiling with both BATTERY_MEASURE_ENABLE & HALLEFFECT_SENSOR_ENABLE enabled * set to LOGLEVEL_ERROR if saving settings failed * Enabled property not needed: if feature is disabled do not provide the JSON object * rename JSON variables for better readability * wifi global settings * changes suggested by @SZenglein review: - refactor server-side hostname validation to Wlan.cpp - rename JSON "neopixel" -> "led" - rename getSettings() -> requestSettings() - bugfix MQTT max-length - bugfix save "scan_wifi_on_start" - sync with latest DEV * load SSIDs via websocket, avoid two extra HTTP requests * Support for .oga audio files (Ogg Vorbis Audio container) spelling correction fix warning about unused variable * LOG message for starting mDNS service * Configurable volumecurve (biologist79#256) In settings.h 0 = square 1 = logarithmic (niko-at) * Refactor "/info" (biologist79#257) refactor /info endpoint to make backend/frontend more independant * update changelog & revision * set VOLUMECURVE 0 as default. VOLUMECURVE = 1 is for more flatten curve with lower volumes * better LOG message for PAUSEPLAY: show "pause" & "resume" remove LOG message for building the filelist, it's fast enough now * check & avoid excessive "PING" calls from web-ui see bug discussion https://forum.espuino.de/t/tts-bugs-und-ein-mini-fix/2119 * Web-ui improvements * spelling correction * Web-ui: Change /restart endpoint to POST refresh button for info & log modal audio playtime statistics: show very first start date * unify endpoints for accesspoint.html/management.html (biologist79#258) * spelling corrections * bugfix get/set LedBrightness * invoke "/rfid" endpoint (biologist79#260) * invoke "/rfid" endpoint * list rfid tags to JSON directly avoid using SD card - Web_DumpNvsToSd() * stop playback before delete nvs assignment * Show nvs rfid assignments in web-ui & allow to delete single tags * Regression: start an initial WiFi scan on startup, fix redirect to captive portal * remove now unneeded log message "backupRecoveryWebsite" * Arduino as component (biologist79#261) * arduino as component. start with a clean history again * increase default-clock-speed * a few less compiler warnings * disable "arduino as comp" by default * add debug-options * disable WPA3 by default because of connection-issues * update changelog & revision * bugfix_same_rfid_twice init (biologist79#262) * Fix some log messages, update FTP & A2DP libraries * avoid buffer-overflow in NVS import with invalid files check for NO_PLAYLIST for writing NVS entry * Handle unicode characters in NVS backup, write UTF-8 BOM in backup.txt * Optimize Arduino as component (Disable BLE, BT-HFP & SPI ethernet) * disable #CONFIG_FMB_COMM_MODE_TCP_EN (Modbus TCP) * enable "Arduino as component" by default fix compiler warning spell check * New define NO_SDCARD, enable to start without any SD card, e.g. for a webplayer only. * update to latest libraries * fix build for EN language * Show free heap before & after creating new playlist Avoid log message "NVS entry not found" * Enhanced logging: Show Loglevel * bugfix PortExpander: beginTransmission() / endTransmission() must be balanced * PlatformIO package 6.4.0 (Arduino Version remains 2.0.11) LPCD, RFID_IRQ on port-expander: fix compiler warning portTICK_RATE_MS is deprecated, use portTICK_PERIOD_MS instead (espressif/esp-idf#51) Cppcheck: Fix some warnings/hints * revert pio package update back to 6.3.2 * setuptools missing? * Now as single line * PlatformIO package 6.4.0 * Discontinuation of branch Arduino1 * Revert "Discontinuation of branch Arduino1" This reverts commit 788a8e1. * Add clang format configuration file * VSCode: Set default tab width to 4 in settings.json This is to match the clang-format settings specified in .clang-format. * Exclude settings header files from clang code formatting * Run auto formatter (clang-format) on all files in src dir * Rework build action and also let it run on PRs Rename build workflow and make it faster. Both checks shall run on PRs. * Prepare config files for ignoring commits in 'git blame' Content for the .git-blame-ignore-revs will be added later when the upstream commit hashes to list are fixed. * README.md: Add information about code formatting * Populate ignore revs for git blame * update changelog & revision small bugfix formatting the playtime * .editorconfig: Fix tab width and remove duplicate setting from VSCode settings.json (biologist79#265) The new formatting defined in .clang-format uses a tab width of 4. Fix this in .editorconfig and remove the setting in settings.json. We don't need it there. * Fix folder upload with special chars * Web-ui: Fix overlapping info/log after pressing refresh button * LPCD: wakeup check for ISO-14443 cards also with IRQ connected to port-expander Bugfix for showing wrong loglevel * Adjustments according clang styleguide * Documentation update * Update README.md * Update README: ESPuino@Arduino2 needs PSRAM * Fix a nullptr access after trying to replay an invalid filename (biologist79#271) --------- Co-authored-by: Laszlo Hegedüs <laszlo.hegedues@gmail.com> Co-authored-by: biologist79 <57354741+biologist79@users.noreply.github.com> Co-authored-by: tueddy <kaffee> Co-authored-by: Joe91 <1015.5@gmx.de> Co-authored-by: Frieder Schrempf <frieder@fris.de> Co-authored-by: NIKO-AT <NIKO-AT@users.noreply.github.com> Co-authored-by: biologist79 <devel@espuino.de> Co-authored-by: tueddy <d.carstensen@pixelplanet.de> Co-authored-by: Dirk Carstensen <11274319+tueddy@users.noreply.github.com> Co-authored-by: Michael Zanetti <michael_zanetti@gmx.net> Co-authored-by: Frieder Schrempf <34034373+fschrempf@users.noreply.github.com> Co-authored-by: SZenglein <13049685+SZenglein@users.noreply.github.com> Co-authored-by: h4kun4m4t4t4 <fwoidich@hotmail.de> Co-authored-by: xoza <xoza@dfsntb.lan> Co-authored-by: Olaf Rempel <razzor@kopf-tisch.de>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
cppcheck (static code analysis tool) found 3 findings with rating high/error:
The problem stems from the working of realloc. If it fails, the original memory block is not modified and it returns NULL. The code here copies the pointer directly into the "old" pointer, so if realloc returns NULL the reference to the original memory address is lost and it can not be freed any more on an error.
To use realloc safely, a temporary variable has to be used. F.e. like this:
edit:
We also seem to have a similar leak-problem at:
ESPuino/src/AudioPlayer.cpp
Line 871 in f4f1e29
Here we malloc into filename, but SdCard_pickRandomSubdirectory can return NULL if something goes wrong. Then filename can not be freed any more.
The text was updated successfully, but these errors were encountered: