diff --git a/cores/esp8266/Esp.cpp b/cores/esp8266/Esp.cpp index 80d969e40..1b4d3ee43 100644 --- a/cores/esp8266/Esp.cpp +++ b/cores/esp8266/Esp.cpp @@ -740,17 +740,17 @@ String EspClass::getSketchMD5() } uint32_t lengthLeft = getSketchSize(); const size_t bufSize = 512; - std::unique_ptr buf(new uint8_t[bufSize]); + std::unique_ptr buf(new (std::nothrow) uint8_t[bufSize]); uint32_t offset = 0; if(!buf.get()) { - return String(); + return emptyString; } MD5Builder md5; md5.begin(); while( lengthLeft > 0) { size_t readBytes = (lengthLeft < bufSize) ? lengthLeft : bufSize; if (!flashRead(offset, reinterpret_cast(buf.get()), (readBytes + 3) & ~3)) { - return String(); + return emptyString; } md5.add(buf.get(), readBytes); lengthLeft -= readBytes; diff --git a/cores/esp8266/FunctionalInterrupt.cpp b/cores/esp8266/FunctionalInterrupt.cpp index 665d8043b..f35b315e9 100644 --- a/cores/esp8266/FunctionalInterrupt.cpp +++ b/cores/esp8266/FunctionalInterrupt.cpp @@ -7,7 +7,7 @@ typedef void (*voidFuncPtr)(void); typedef void (*voidFuncPtrArg)(void*); // Helper functions for Functional interrupt routines -extern "C" void __attachInterruptFunctionalArg(uint8_t pin, voidFuncPtr userFunc, void*fp, int mode, bool functional); +extern "C" bool __attachInterruptFunctionalArg(uint8_t pin, voidFuncPtr userFunc, void*fp, int mode, bool functional); void ICACHE_RAM_ATTR interruptFunctional(void* arg) @@ -34,32 +34,52 @@ extern "C" } } -void attachInterrupt(uint8_t pin, std::function intRoutine, int mode) +bool attachInterrupt(uint8_t pin, std::function intRoutine, int mode) { // use the local interrupt routine which takes the ArgStructure as argument InterruptInfo* ii = nullptr; - FunctionInfo* fi = new FunctionInfo; + FunctionInfo* fi = new (std::nothrow) FunctionInfo; + if (fi == nullptr) + return false; fi->reqFunction = intRoutine; - ArgStructure* as = new ArgStructure; + ArgStructure* as = new (std::nothrow) ArgStructure; + if (as == nullptr) + { + delete(fi); + return false; + } as->interruptInfo = ii; as->functionInfo = fi; - __attachInterruptFunctionalArg(pin, (voidFuncPtr)interruptFunctional, as, mode, true); + return __attachInterruptFunctionalArg(pin, (voidFuncPtr)interruptFunctional, as, mode, true); } -void attachScheduledInterrupt(uint8_t pin, std::function scheduledIntRoutine, int mode) +bool attachScheduledInterrupt(uint8_t pin, std::function scheduledIntRoutine, int mode) { - InterruptInfo* ii = new InterruptInfo; + InterruptInfo* ii = new (std::nothrow) InterruptInfo; + if (ii == nullptr) + return false; FunctionInfo* fi = new FunctionInfo; + if (fi == nullptr) + { + delete ii; + return false; + } fi->reqScheduledFunction = scheduledIntRoutine; - ArgStructure* as = new ArgStructure; + ArgStructure* as = new (std::nothrow) ArgStructure; + if (as == nullptr) + { + delete ii; + delete fi; + return false; + } as->interruptInfo = ii; as->functionInfo = fi; - __attachInterruptFunctionalArg(pin, (voidFuncPtr)interruptFunctional, as, mode, true); + return __attachInterruptFunctionalArg(pin, (voidFuncPtr)interruptFunctional, as, mode, true); } diff --git a/cores/esp8266/Print.cpp b/cores/esp8266/Print.cpp index d93293ee8..b0e2e31a1 100644 --- a/cores/esp8266/Print.cpp +++ b/cores/esp8266/Print.cpp @@ -63,7 +63,7 @@ size_t Print::printf(const char *format, ...) { size_t len = vsnprintf(temp, sizeof(temp), format, arg); va_end(arg); if (len > sizeof(temp) - 1) { - buffer = new char[len + 1]; + buffer = new (std::nothrow) char[len + 1]; if (!buffer) { return 0; } @@ -86,7 +86,7 @@ size_t Print::printf_P(PGM_P format, ...) { size_t len = vsnprintf_P(temp, sizeof(temp), format, arg); va_end(arg); if (len > sizeof(temp) - 1) { - buffer = new char[len + 1]; + buffer = new (std::nothrow) char[len + 1]; if (!buffer) { return 0; } diff --git a/cores/esp8266/Updater.cpp b/cores/esp8266/Updater.cpp index 03bc5c3f8..472a1417a 100644 --- a/cores/esp8266/Updater.cpp +++ b/cores/esp8266/Updater.cpp @@ -180,7 +180,7 @@ bool UpdaterClass::begin(size_t size, int command, int ledPin, uint8_t ledOn) { } else { _bufferSize = 256; } - _buffer = new uint8_t[_bufferSize]; + _buffer = new (std::nothrow) uint8_t[_bufferSize]; _command = command; #ifdef DEBUG_UPDATER diff --git a/cores/esp8266/cbuf.cpp b/cores/esp8266/cbuf.cpp index e655ca6fc..5f394f9df 100644 --- a/cores/esp8266/cbuf.cpp +++ b/cores/esp8266/cbuf.cpp @@ -43,7 +43,7 @@ size_t cbuf::resize(size_t newSize) { return _size; } - char *newbuf = new char[newSize]; + char *newbuf = new (std::nothrow) char[newSize]; char *oldbuf = _buf; if(!newbuf) { diff --git a/cores/esp8266/core_esp8266_features.h b/cores/esp8266/core_esp8266_features.h index 6d6edf030..cc4cd3977 100644 --- a/cores/esp8266/core_esp8266_features.h +++ b/cores/esp8266/core_esp8266_features.h @@ -36,35 +36,6 @@ #include // size_t #include -#ifdef __cplusplus - -namespace arduino -{ - extern "C++" - template - T* new0 (size_t n, TConstructorArgs... TconstructorArgs) - { - // n==0: single allocation, otherwise it is an array - size_t offset = n? sizeof(size_t): 0; - size_t arraysize = n? n: 1; - T* ptr = (T*)malloc(offset + (arraysize * sizeof(T))); - if (ptr) - { - if (n) - *(size_t*)(ptr) = n; - for (size_t i = 0; i < arraysize; i++) - new (ptr + offset + i * sizeof(T)) T(TconstructorArgs...); - return ptr + offset; - } - return nullptr; - } -} - -#define arduino_new(Type, ...) arduino::new0(0, ##__VA_ARGS__) -#define arduino_newarray(Type, n, ...) arduino::new0(n, ##__VA_ARGS__) - -#endif // __cplusplus - #ifndef __STRINGIFY #define __STRINGIFY(a) #a #endif diff --git a/doc/reference.rst b/doc/reference.rst index 9551d9d03..2ae8ca5cd 100644 --- a/doc/reference.rst +++ b/doc/reference.rst @@ -323,36 +323,3 @@ C++ This assures correct behavior, including handling of all subobjects, which guarantees stability. History: `#6269 `__ `#6309 `__ `#6312 `__ - -- New optional allocator ``arduino_new`` - - A new optional global allocator is introduced with a different semantic: - - - never throws exceptions on oom - - - never calls constructors on oom - - - returns nullptr on oom - - It is similar to arduino ``new`` semantic without side effects - (except when parent constructors, or member constructors use ``new``). - - Syntax is slightly different, the following shows the different usages: - - .. code:: cpp - - // with new: - - SomeClass* sc = new SomeClass(arg1, arg2, ...); - delete sc; - - SomeClass* scs = new SomeClass[42]; - delete [] scs; - - // with arduino_new: - - SomeClass* sc = arduino_new(SomeClass, arg1, arg2, ...); - delete sc; - - SomeClass* scs = arduino_newarray(SomeClass, 42); - delete [] scs; diff --git a/libraries/ArduinoOTA/ArduinoOTA.cpp b/libraries/ArduinoOTA/ArduinoOTA.cpp index 64e8397a2..2a7bd235f 100644 --- a/libraries/ArduinoOTA/ArduinoOTA.cpp +++ b/libraries/ArduinoOTA/ArduinoOTA.cpp @@ -106,7 +106,7 @@ void ArduinoOTAClass::setRebootOnSuccess(bool reboot){ _rebootOnSuccess = reboot; } -void ArduinoOTAClass::begin(bool useMDNS) { +bool ArduinoOTAClass::begin(bool useMDNS) { if (_initialized) return; @@ -126,11 +126,13 @@ void ArduinoOTAClass::begin(bool useMDNS) { _udp_ota = 0; } - _udp_ota = new UdpContext; + _udp_ota = new (std::nothrow) UdpContext; + if (_udp_ota == nullptr) + return false; _udp_ota->ref(); if(!_udp_ota->listen(IP_ADDR_ANY, _port)) - return; + return false; _udp_ota->onRx(std::bind(&ArduinoOTAClass::_onRx, this)); #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_MDNS) @@ -149,6 +151,7 @@ void ArduinoOTAClass::begin(bool useMDNS) { #ifdef OTA_DEBUG OTA_DEBUG.printf("OTA server at: %s.local:%u\n", _hostname.c_str(), _port); #endif + return true; } int ArduinoOTAClass::parseInt(){ diff --git a/libraries/DNSServer/src/DNSServer.cpp b/libraries/DNSServer/src/DNSServer.cpp index 2113ae0f5..8d7b3dfb0 100644 --- a/libraries/DNSServer/src/DNSServer.cpp +++ b/libraries/DNSServer/src/DNSServer.cpp @@ -178,8 +178,7 @@ void DNSServer::processNextRequest() return; std::unique_ptr buffer(new (std::nothrow) uint8_t[currentPacketSize]); - - if (buffer == NULL) + if (buffer == nullptr) return; _udp.read(buffer.get(), currentPacketSize); diff --git a/libraries/EEPROM/EEPROM.cpp b/libraries/EEPROM/EEPROM.cpp index 90bbf8ca5..c0cedb835 100644 --- a/libraries/EEPROM/EEPROM.cpp +++ b/libraries/EEPROM/EEPROM.cpp @@ -64,9 +64,12 @@ void EEPROMClass::begin(size_t size) { //In case begin() is called a 2nd+ time, don't reallocate if size is the same if(_data && size != _size) { delete[] _data; - _data = new uint8_t[size]; + _data = new (std::nothrow) uint8_t[size]; } else if(!_data) { - _data = new uint8_t[size]; + _data = new (std::nothrow) uint8_t[size]; + } + if (_data == nullptr) { + return; } _size = size; diff --git a/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino b/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino index 2d6f49592..7940ec7f8 100644 --- a/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino +++ b/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino @@ -41,7 +41,10 @@ void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { - std::unique_ptrclient(new BearSSL::WiFiClientSecure); + std::unique_ptrclient(new (std::nothrow) BearSSL::WiFiClientSecure); + if (client == nullptr) { + return; + } client->setFingerprint(fingerprint); diff --git a/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino b/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino index a69b9e35c..9d92b0c83 100644 --- a/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino +++ b/libraries/ESP8266HTTPClient/examples/StreamHttpsClient/StreamHttpsClient.ino @@ -38,7 +38,10 @@ void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { - std::unique_ptr client(new BearSSL::WiFiClientSecure); + std::unique_ptr client(new (std::nothrow) BearSSL::WiFiClientSecure); + if (client == nullptr) { + return; + } bool mfln = client->probeMaxFragmentLength("tls.mbed.org", 443, 1024); Serial.printf("\nConnecting to https://tls.mbed.org\n"); diff --git a/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp b/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp index 74bc3be17..84770ee5c 100644 --- a/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp +++ b/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp @@ -37,7 +37,7 @@ public: virtual std::unique_ptr create() { - return std::unique_ptr(new WiFiClient()); + return std::unique_ptr(new (std::nothrow) WiFiClient()); } virtual bool verify(WiFiClient& client, const char* host) @@ -59,8 +59,9 @@ public: std::unique_ptr create() override { - BearSSL::WiFiClientSecure *client = new BearSSL::WiFiClientSecure(); - client->setFingerprint(_fingerprint); + BearSSL::WiFiClientSecure *client = new (std::nothrow) BearSSL::WiFiClientSecure(); + if (client != nullptr) + client->setFingerprint(_fingerprint); return std::unique_ptr(client); } @@ -182,7 +183,7 @@ bool HTTPClient::begin(String url, const uint8_t httpsFingerprint[20]) if (!beginInternal(url, "https")) { return false; } - _transportTraits = TransportTraitsPtr(new BearSSLTraits(httpsFingerprint)); + _transportTraits = TransportTraitsPtr(new (std::nothrow) BearSSLTraits(httpsFingerprint)); if(!_transportTraits) { DEBUG_HTTPCLIENT("[HTTP-Client][begin] could not create transport traits\n"); return false; @@ -212,8 +213,8 @@ bool HTTPClient::begin(String url) if (!beginInternal(url, "http")) { return false; } - _transportTraits = TransportTraitsPtr(new TransportTraits()); - return true; + _transportTraits = TransportTraitsPtr(new (std::nothrow) TransportTraits()); + return _transportTraits != nullptr; } @@ -290,9 +291,9 @@ bool HTTPClient::begin(String host, uint16_t port, String uri) _host = host; _port = port; _uri = uri; - _transportTraits = TransportTraitsPtr(new TransportTraits()); + _transportTraits = TransportTraitsPtr(new (std::nothrow) TransportTraits()); DEBUG_HTTPCLIENT("[HTTP-Client][begin] host: %s port: %d uri: %s\n", host.c_str(), port, uri.c_str()); - return true; + return _transportTraits != nullptr; } @@ -309,13 +310,13 @@ bool HTTPClient::begin(String host, uint16_t port, String uri, const uint8_t htt _port = port; _uri = uri; - _transportTraits = TransportTraitsPtr(new BearSSLTraits(httpsFingerprint)); + _transportTraits = TransportTraitsPtr(new (std::nothrow) BearSSLTraits(httpsFingerprint)); DEBUG_HTTPCLIENT("[HTTP-Client][begin] host: %s port: %d url: %s BearSSL-httpsFingerprint:", host.c_str(), port, uri.c_str()); for (size_t i=0; i < 20; i++) { DEBUG_HTTPCLIENT(" %02x", httpsFingerprint[i]); } DEBUG_HTTPCLIENT("\n"); - return true; + return _transportTraits != nullptr; } diff --git a/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino b/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino index a2514e171..dd19e5623 100644 --- a/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino +++ b/libraries/ESP8266HTTPUpdateServer/examples/SecureBearSSLUpdater/SecureBearSSLUpdater.ino @@ -106,7 +106,7 @@ void setup() MDNS.begin(host); - httpServer.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey)); + httpServer.getServer().setRSACert(new (std::nothrow) BearSSL::X509List(serverCert), new (std::nothrow) BearSSL::PrivateKey(serverKey)); httpUpdater.setup(&httpServer, update_path, update_username, update_password); httpServer.begin(); diff --git a/libraries/ESP8266LLMNR/ESP8266LLMNR.cpp b/libraries/ESP8266LLMNR/ESP8266LLMNR.cpp index ac8582c57..f69367033 100644 --- a/libraries/ESP8266LLMNR/ESP8266LLMNR.cpp +++ b/libraries/ESP8266LLMNR/ESP8266LLMNR.cpp @@ -116,7 +116,9 @@ bool LLMNRResponder::_restart() { if (igmp_joingroup(IP4_ADDR_ANY4, llmnr) != ERR_OK) return false; - _conn = new UdpContext; + _conn = new (std::nothrow) UdpContext; + if (!_conn) + return false; _conn->ref(); if (!_conn->listen(IP_ADDR_ANY, LLMNR_PORT)) diff --git a/libraries/ESP8266SSDP/ESP8266SSDP.cpp b/libraries/ESP8266SSDP/ESP8266SSDP.cpp index 93121ffc8..e0b5a5d64 100644 --- a/libraries/ESP8266SSDP/ESP8266SSDP.cpp +++ b/libraries/ESP8266SSDP/ESP8266SSDP.cpp @@ -175,7 +175,10 @@ bool SSDPClass::begin() { assert(NULL == _server); - _server = new UdpContext; + _server = new (std::nothrow) UdpContext; + if (_server == nullptr) { + return false; + } _server->ref(); IPAddress local = WiFi.localIP(); @@ -508,7 +511,9 @@ void SSDPClass::_onTimerStatic(SSDPClass* self) { void SSDPClass::_startTimer() { _stopTimer(); - _timer = new SSDPTimer(); + _timer = new (std::nothrow) SSDPTimer(); + if (_timer == nullptr) + return; ETSTimer* tm = &(_timer->timer); const int interval = 1000; os_timer_disarm(tm); diff --git a/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino b/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino index 4b786dc1a..c6c0d5563 100644 --- a/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino +++ b/libraries/ESP8266WebServer/examples/HelloServerBearSSL/HelloServerBearSSL.ino @@ -128,7 +128,7 @@ void setup(void){ Serial.println("MDNS responder started"); } - server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey)); + server.getServer().setRSACert(new (std::nothrow) BearSSL::X509List(serverCert), new (std::nothrow) BearSSL::PrivateKey(serverKey)); server.on("/", handleRoot); diff --git a/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino b/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino index c2ceaca53..0671b122e 100644 --- a/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino +++ b/libraries/ESP8266WebServer/examples/HttpHashCredAuth/HttpHashCredAuth.ino @@ -111,7 +111,7 @@ void setup() { ESP.restart(); } - server.getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey)); + server.getServer().setRSACert(new (std::nothrow) BearSSL::X509List(serverCert), new (std::nothrow) BearSSL::PrivateKey(serverKey)); server.on("/",showcredentialpage); //for this simple example, just show a simple page for changing credentials at the root server.on("/" + change_creds,handlecredentialchange); //handles submission of credentials from the client server.onNotFound(redirect); diff --git a/libraries/ESP8266WebServer/src/ESP8266WebServer-impl.h b/libraries/ESP8266WebServer/src/ESP8266WebServer-impl.h index 218fd168a..b85899610 100644 --- a/libraries/ESP8266WebServer/src/ESP8266WebServer-impl.h +++ b/libraries/ESP8266WebServer/src/ESP8266WebServer-impl.h @@ -126,12 +126,12 @@ bool ESP8266WebServerTemplate::authenticate(const char * username, c authReq = authReq.substring(6); authReq.trim(); char toencodeLen = strlen(username)+strlen(password)+1; - char *toencode = new char[toencodeLen + 1]; + char *toencode = new (std::nothrow) char[toencodeLen + 1]; if(toencode == NULL){ authReq = ""; return false; } - char *encoded = new char[base64_encode_expected_len(toencodeLen)+1]; + char *encoded = new (std::nothrow) char[base64_encode_expected_len(toencodeLen)+1]; if(encoded == NULL){ authReq = ""; delete[] toencode; @@ -266,7 +266,7 @@ void ESP8266WebServerTemplate::on(const Uri &uri, HTTPMethod method, template void ESP8266WebServerTemplate::on(const Uri &uri, HTTPMethod method, ESP8266WebServerTemplate::THandlerFunction fn, ESP8266WebServerTemplate::THandlerFunction ufn) { - _addRequestHandler(new FunctionRequestHandler(fn, ufn, uri, method)); + _addRequestHandler(new (std::nothrow) FunctionRequestHandler(fn, ufn, uri, method)); } template @@ -288,7 +288,7 @@ void ESP8266WebServerTemplate::_addRequestHandler(RequestHandlerType template void ESP8266WebServerTemplate::serveStatic(const char* uri, FS& fs, const char* path, const char* cache_header) { - _addRequestHandler(new StaticRequestHandler(fs, path, uri, cache_header)); + _addRequestHandler(new (std::nothrow) StaticRequestHandler(fs, path, uri, cache_header)); } template @@ -645,7 +645,9 @@ void ESP8266WebServerTemplate::collectHeaders(const char* headerKeys _headerKeysCount = headerKeysCount + 1; if (_currentHeaders) delete[]_currentHeaders; - _currentHeaders = new RequestArgument[_headerKeysCount]; + _currentHeaders = new (std::nothrow) RequestArgument[_headerKeysCount]; + if (_currentHeaders == nullptr) + return; _currentHeaders[0].key = FPSTR(AUTHORIZATION_HEADER); for (int i = 1; i < _headerKeysCount; i++){ _currentHeaders[i].key = headerKeys[i-1]; diff --git a/libraries/ESP8266WebServer/src/Parsing-impl.h b/libraries/ESP8266WebServer/src/Parsing-impl.h index 4bb6db887..3eb170b44 100644 --- a/libraries/ESP8266WebServer/src/Parsing-impl.h +++ b/libraries/ESP8266WebServer/src/Parsing-impl.h @@ -283,7 +283,9 @@ void ESP8266WebServerTemplate::_parseArguments(const String& data) { _currentArgCount = _parseArgumentsPrivate(data, nullArgHandler()); // allocate one more, this is needed because {"plain": plainBuf} is always added - _currentArgs = new RequestArgument[_currentArgCount + 1]; + _currentArgs = new (std::nothrow) RequestArgument[_currentArgCount + 1]; + if (_currentArgs == nullptr) + return; (void)_parseArgumentsPrivate(data, storeArgHandler()); } @@ -370,7 +372,11 @@ bool ESP8266WebServerTemplate::_parseForm(ClientType& client, const //start reading the form if (line == ("--"+boundary)){ if(_postArgs) delete[] _postArgs; - _postArgs = new RequestArgument[WEBSERVER_MAX_POST_ARGS]; + _postArgs = new (std::nothrow) RequestArgument[WEBSERVER_MAX_POST_ARGS]; + if (_postArgs == nullptr) { + DBGWS("Parse form: oom\n"); + return false; + } _postArgsLen = 0; while(1){ String argName; @@ -428,7 +434,11 @@ bool ESP8266WebServerTemplate::_parseForm(ClientType& client, const break; } } else { - _currentUpload.reset(new HTTPUpload()); + _currentUpload.reset(new (std::nothrow) HTTPUpload()); + if (_currentUpload == nullptr) { + DBGWS("Parse form: oom\n"); + return false; + } _currentUpload->status = UPLOAD_FILE_START; _currentUpload->name = argName; _currentUpload->filename = argFilename; @@ -521,7 +531,9 @@ readfile: arg.value = _currentArgs[iarg].value; } if (_currentArgs) delete[] _currentArgs; - _currentArgs = new RequestArgument[_postArgsLen]; + _currentArgs = new (std::nothrow) RequestArgument[_postArgsLen]; + if (_currentArgs == nullptr) + return false; for (iarg = 0; iarg < _postArgsLen; iarg++){ RequestArgument& arg = _currentArgs[iarg]; arg.key = _postArgs[iarg].key; diff --git a/libraries/ESP8266WebServer/src/Uri.h b/libraries/ESP8266WebServer/src/Uri.h index 95f5c8936..6b0fa998b 100644 --- a/libraries/ESP8266WebServer/src/Uri.h +++ b/libraries/ESP8266WebServer/src/Uri.h @@ -16,7 +16,7 @@ class Uri { virtual ~Uri() {} virtual Uri* clone() const { - return new Uri(_uri); + return new (std::nothrow) Uri(_uri); }; virtual bool canHandle(const String &requestUri, __attribute__((unused)) std::vector &pathArgs) { diff --git a/libraries/ESP8266WebServer/src/uri/UriBraces.h b/libraries/ESP8266WebServer/src/uri/UriBraces.h index 29652efc7..fa32d6be9 100644 --- a/libraries/ESP8266WebServer/src/uri/UriBraces.h +++ b/libraries/ESP8266WebServer/src/uri/UriBraces.h @@ -10,7 +10,7 @@ class UriBraces : public Uri { explicit UriBraces(const String &uri) : Uri(uri) {}; Uri* clone() const override final { - return new UriBraces(_uri); + return new (std::nothrow) UriBraces(_uri); }; bool canHandle(const String &requestUri, std::vector &pathArgs) override final { diff --git a/libraries/ESP8266WebServer/src/uri/UriGlob.h b/libraries/ESP8266WebServer/src/uri/UriGlob.h index 1e222cbab..8cab6e6bc 100644 --- a/libraries/ESP8266WebServer/src/uri/UriGlob.h +++ b/libraries/ESP8266WebServer/src/uri/UriGlob.h @@ -11,7 +11,7 @@ class UriGlob : public Uri { explicit UriGlob(const String &uri) : Uri(uri) {}; Uri* clone() const override final { - return new UriGlob(_uri); + return new (std::nothrow) UriGlob(_uri); }; bool canHandle(const String &requestUri, __attribute__((unused)) std::vector &pathArgs) override final { diff --git a/libraries/ESP8266WebServer/src/uri/UriRegex.h b/libraries/ESP8266WebServer/src/uri/UriRegex.h index eef1b516d..47128eb3a 100644 --- a/libraries/ESP8266WebServer/src/uri/UriRegex.h +++ b/libraries/ESP8266WebServer/src/uri/UriRegex.h @@ -25,7 +25,7 @@ class UriRegex : public Uri { } Uri* clone() const override final { - return new UriRegex(_uri); + return new (std::nothrow) UriRegex(_uri); }; bool canHandle(const String &requestUri, std::vector &pathArgs) override final { diff --git a/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino b/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino index a599a0395..fac012404 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino @@ -145,7 +145,7 @@ void setup() { return; // Can't connect to anything w/o certs! } - BearSSL::WiFiClientSecure *bear = new BearSSL::WiFiClientSecure(); + BearSSL::WiFiClientSecure *bear = new (std::nothrow) BearSSL::WiFiClientSecure(); // Integrate the cert store with this connection bear->setCertStore(&certStore); Serial.printf("Attempting to fetch https://github.com/...\n"); @@ -164,7 +164,7 @@ void loop() { site.replace(String("\n"), emptyString); Serial.printf("https://%s/\n", site.c_str()); - BearSSL::WiFiClientSecure *bear = new BearSSL::WiFiClientSecure(); + BearSSL::WiFiClientSecure *bear = new (std::nothrow) BearSSL::WiFiClientSecure(); // Integrate the cert store with this connection bear->setCertStore(&certStore); fetchURL(bear, site.c_str(), 443, "/"); diff --git a/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino b/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino index d27382284..24249ffb5 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_Server/BearSSL_Server.ino @@ -161,8 +161,8 @@ void setup() { Serial.println(WiFi.localIP()); // Attach the server private cert/key combo - BearSSL::X509List *serverCertList = new BearSSL::X509List(server_cert); - BearSSL::PrivateKey *serverPrivKey = new BearSSL::PrivateKey(server_private_key); + BearSSL::X509List *serverCertList = new (std::nothrow) BearSSL::X509List(server_cert); + BearSSL::PrivateKey *serverPrivKey = new (std::nothrow) BearSSL::PrivateKey(server_private_key); #ifndef USE_EC server.setRSACert(serverCertList, serverPrivKey); #else diff --git a/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino b/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino index a50f11528..48dc6aba9 100644 --- a/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino +++ b/libraries/ESP8266WiFi/examples/BearSSL_ServerClientCert/BearSSL_ServerClientCert.ino @@ -202,12 +202,12 @@ void setup() { setClock(); // Required for X.509 validation // Attach the server private cert/key combo - BearSSL::X509List *serverCertList = new BearSSL::X509List(server_cert); - BearSSL::PrivateKey *serverPrivKey = new BearSSL::PrivateKey(server_private_key); + BearSSL::X509List *serverCertList = new (std::nothrow) BearSSL::X509List(server_cert); + BearSSL::PrivateKey *serverPrivKey = new (std::nothrow) BearSSL::PrivateKey(server_private_key); server.setRSACert(serverCertList, serverPrivKey); // Require a certificate validated by the trusted CA - BearSSL::X509List *serverTrustedCA = new BearSSL::X509List(ca_cert); + BearSSL::X509List *serverTrustedCA = new (std::nothrow) BearSSL::X509List(ca_cert); server.setClientTrustAnchor(serverTrustedCA); // Actually start accepting connections diff --git a/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino b/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino index 9102af12d..bf547665e 100644 --- a/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino +++ b/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino @@ -85,7 +85,7 @@ void setup() { Serial.swap(); // Hardware serial is now on RX:GPIO13 TX:GPIO15 // use SoftwareSerial on regular RX(3)/TX(1) for logging - logger = new SoftwareSerial(3, 1); + logger = new (std::nothrow) SoftwareSerial(3, 1); logger->begin(BAUD_LOGGER); logger->enableIntTx(false); logger->println("\n\nUsing SoftwareSerial for logging"); diff --git a/libraries/ESP8266WiFi/src/BearSSLHelpers.cpp b/libraries/ESP8266WiFi/src/BearSSLHelpers.cpp index b3d1b60c2..6ffcca08d 100644 --- a/libraries/ESP8266WiFi/src/BearSSLHelpers.cpp +++ b/libraries/ESP8266WiFi/src/BearSSLHelpers.cpp @@ -109,7 +109,7 @@ namespace brssl { } static bool certificate_to_trust_anchor_inner(br_x509_trust_anchor *ta, const br_x509_certificate *xc) { - std::unique_ptr dc(new br_x509_decoder_context); // auto-delete on exit + std::unique_ptr dc(new (std::nothrow) br_x509_decoder_context); // auto-delete on exit std::vector vdn; br_x509_pkey *pk; @@ -244,7 +244,7 @@ namespace brssl { // blobs may be returned. pem_object *decode_pem(const void *src, size_t len, size_t *num) { std::vector pem_list; - std::unique_ptr pc(new br_pem_decoder_context); // auto-delete on exit + std::unique_ptr pc(new (std::nothrow) br_pem_decoder_context); // auto-delete on exit if (!pc.get()) { return nullptr; } @@ -405,7 +405,7 @@ namespace brssl { } static public_key *decode_public_key(const unsigned char *buff, size_t len) { - std::unique_ptr dc(new br_pkey_decoder_context); // auto-delete on exit + std::unique_ptr dc(new (std::nothrow) br_pkey_decoder_context); // auto-delete on exit if (!dc.get()) { return nullptr; } @@ -477,7 +477,7 @@ namespace brssl { } static private_key *decode_private_key(const unsigned char *buff, size_t len) { - std::unique_ptr dc(new br_skey_decoder_context); // auto-delete on exit + std::unique_ptr dc(new (std::nothrow) br_skey_decoder_context); // auto-delete on exit if (!dc.get()) { return nullptr; } diff --git a/libraries/ESP8266WiFi/src/CertStoreBearSSL.cpp b/libraries/ESP8266WiFi/src/CertStoreBearSSL.cpp index 905efde2b..9f3e0ac80 100644 --- a/libraries/ESP8266WiFi/src/CertStoreBearSSL.cpp +++ b/libraries/ESP8266WiFi/src/CertStoreBearSSL.cpp @@ -50,9 +50,13 @@ CertStore::CertInfo CertStore::_preprocessCert(uint32_t length, uint32_t offset, memset(&ci, 0, sizeof(ci)); // Process it using SHA256, same as the hashed_dn - br_x509_decoder_context *ctx = new br_x509_decoder_context; - br_sha256_context *sha256 = new br_sha256_context; + br_x509_decoder_context *ctx = new (std::nothrow) br_x509_decoder_context; + br_sha256_context *sha256 = new (std::nothrow) br_sha256_context; if (!ctx || !sha256) { + if (ctx) + delete ctx; + if (sha256) + delete sha256; DEBUG_BSSL("CertStore::_preprocessCert: OOM\n"); return ci; } @@ -202,7 +206,7 @@ const br_x509_trust_anchor *CertStore::findHashedTA(void *ctx, void *hashed_dn, return nullptr; } data.close(); - cs->_x509 = new X509List(der, ci.length); + cs->_x509 = new (std::nothrow) X509List(der, ci.length); free(der); if (!cs->_x509) { DEBUG_BSSL("CertStore::findHashedTA: OOM\n"); diff --git a/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp b/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp index 65878a3d5..0eb588983 100644 --- a/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp +++ b/libraries/ESP8266WiFi/src/ESP8266WiFiScan.cpp @@ -308,7 +308,10 @@ void ESP8266WiFiScanClass::_scanDone(void* result, int status) { if(i == 0) { ESP8266WiFiScanClass::_scanResult = 0; } else { - bss_info* copied_info = new bss_info[i]; + bss_info* copied_info = new (std::nothrow) bss_info[i]; + if (copied_info == nullptr) { + return; + } i = 0; for(bss_info* it = head; it; it = STAILQ_NEXT(it, next), ++i) { memcpy(copied_info + i, it, sizeof(bss_info)); diff --git a/libraries/ESP8266WiFi/src/WiFiClient.cpp b/libraries/ESP8266WiFi/src/WiFiClient.cpp index 1663a29ec..136016b07 100644 --- a/libraries/ESP8266WiFi/src/WiFiClient.cpp +++ b/libraries/ESP8266WiFi/src/WiFiClient.cpp @@ -153,7 +153,10 @@ int WiFiClient::connect(IPAddress ip, uint16_t port) pcb->local_port = _localPort++; } - _client = new ClientContext(pcb, nullptr, nullptr); + _client = new (std::nothrow) ClientContext(pcb, nullptr, nullptr); + if (_client == nullptr) { + return 0; + } _client->ref(); _client->setTimeout(_timeout); int res = _client->connect(ip, port); diff --git a/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp b/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp index c94ac79e0..281612f7e 100644 --- a/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp +++ b/libraries/ESP8266WiFi/src/WiFiClientSecureBearSSL.cpp @@ -977,7 +977,7 @@ extern "C" { // Set custom list of ciphers bool WiFiClientSecure::setCiphers(const uint16_t *cipherAry, int cipherCount) { _cipher_list = nullptr; - _cipher_list = std::shared_ptr(new uint16_t[cipherCount], std::default_delete()); + _cipher_list = std::shared_ptr(new (std::nothrow) uint16_t[cipherCount], std::default_delete()); if (!_cipher_list.get()) { DEBUG_BSSL("setCiphers: list empty\n"); return false; @@ -1067,8 +1067,8 @@ bool WiFiClientSecure::_connectSSL(const char* hostName) { _sc = std::make_shared(); _eng = &_sc->eng; // Allocation/deallocation taken care of by the _sc shared_ptr - _iobuf_in = std::shared_ptr(new unsigned char[_iobuf_in_size], std::default_delete()); - _iobuf_out = std::shared_ptr(new unsigned char[_iobuf_out_size], std::default_delete()); + _iobuf_in = std::shared_ptr(new (std::nothrow) unsigned char[_iobuf_in_size], std::default_delete()); + _iobuf_out = std::shared_ptr(new (std::nothrow) unsigned char[_iobuf_out_size], std::default_delete()); if (!_sc || !_iobuf_in || !_iobuf_out) { _freeSSL(); // Frees _sc, _iobuf* @@ -1183,8 +1183,8 @@ bool WiFiClientSecure::_connectSSLServerRSA(const X509List *chain, _oom_err = false; _sc_svr = std::make_shared(); _eng = &_sc_svr->eng; // Allocation/deallocation taken care of by the _sc shared_ptr - _iobuf_in = std::shared_ptr(new unsigned char[_iobuf_in_size], std::default_delete()); - _iobuf_out = std::shared_ptr(new unsigned char[_iobuf_out_size], std::default_delete()); + _iobuf_in = std::shared_ptr(new (std::nothrow) unsigned char[_iobuf_in_size], std::default_delete()); + _iobuf_out = std::shared_ptr(new (std::nothrow) unsigned char[_iobuf_out_size], std::default_delete()); if (!_sc_svr || !_iobuf_in || !_iobuf_out) { _freeSSL(); @@ -1220,8 +1220,8 @@ bool WiFiClientSecure::_connectSSLServerEC(const X509List *chain, _oom_err = false; _sc_svr = std::make_shared(); _eng = &_sc_svr->eng; // Allocation/deallocation taken care of by the _sc shared_ptr - _iobuf_in = std::shared_ptr(new unsigned char[_iobuf_in_size], std::default_delete()); - _iobuf_out = std::shared_ptr(new unsigned char[_iobuf_out_size], std::default_delete()); + _iobuf_in = std::shared_ptr(new (std::nothrow) unsigned char[_iobuf_in_size], std::default_delete()); + _iobuf_out = std::shared_ptr(new (std::nothrow) unsigned char[_iobuf_out_size], std::default_delete()); if (!_sc_svr || !_iobuf_in || !_iobuf_out) { _freeSSL(); @@ -1421,7 +1421,7 @@ bool WiFiClientSecure::probeMaxFragmentLength(IPAddress ip, uint16_t port, uint1 default: return false; // Invalid size } int ttlLen = sizeof(clientHelloHead_P) + (2 + sizeof(suites_P)) + (sizeof(clientHelloTail_P) + 1); - uint8_t *clientHello = new uint8_t[ttlLen]; + uint8_t *clientHello = new (std::nothrow) uint8_t[ttlLen]; if (!clientHello) { DEBUG_BSSL("probeMaxFragmentLength: OOM\n"); return false; @@ -1580,21 +1580,21 @@ bool WiFiClientSecure::probeMaxFragmentLength(IPAddress ip, uint16_t port, uint1 // AXTLS compatibility interfaces bool WiFiClientSecure::setCACert(const uint8_t* pk, size_t size) { _axtls_ta = nullptr; - _axtls_ta = std::shared_ptr(new X509List(pk, size)); + _axtls_ta = std::shared_ptr(new (std::nothrow) X509List(pk, size)); _ta = _axtls_ta.get(); return _ta ? true : false; } bool WiFiClientSecure::setCertificate(const uint8_t* pk, size_t size) { _axtls_chain = nullptr; - _axtls_chain = std::shared_ptr(new X509List(pk, size)); + _axtls_chain = std::shared_ptr(new (std::nothrow) X509List(pk, size)); _chain = _axtls_chain.get(); return _chain ? true : false; } bool WiFiClientSecure::setPrivateKey(const uint8_t* pk, size_t size) { _axtls_sk = nullptr; - _axtls_sk = std::shared_ptr(new PrivateKey(pk, size)); + _axtls_sk = std::shared_ptr(new (std::nothrow) PrivateKey(pk, size)); _sk = _axtls_sk.get(); return _sk ? true : false; diff --git a/libraries/ESP8266WiFi/src/WiFiServer.cpp b/libraries/ESP8266WiFi/src/WiFiServer.cpp index 2ee09f85f..1ec78fed7 100644 --- a/libraries/ESP8266WiFi/src/WiFiServer.cpp +++ b/libraries/ESP8266WiFi/src/WiFiServer.cpp @@ -186,7 +186,10 @@ long WiFiServer::_accept(tcp_pcb* apcb, long err) { // always accept new PCB so incoming data can be stored in our buffers even before // user calls ::available() - ClientContext* client = new ClientContext(apcb, &WiFiServer::_s_discard, this); + ClientContext* client = new (std::nothrow) ClientContext(apcb, &WiFiServer::_s_discard, this); + if (client == nullptr) { + return ERR_MEM; + } // backlog doc: // http://lwip.100.n7.nabble.com/Problem-re-opening-listening-pbc-tt32484.html#a32494 diff --git a/libraries/ESP8266WiFi/src/WiFiServerSecureBearSSL.cpp b/libraries/ESP8266WiFi/src/WiFiServerSecureBearSSL.cpp index 087c90b4e..b4cb0e0e9 100644 --- a/libraries/ESP8266WiFi/src/WiFiServerSecureBearSSL.cpp +++ b/libraries/ESP8266WiFi/src/WiFiServerSecureBearSSL.cpp @@ -107,8 +107,8 @@ WiFiClientSecure WiFiServerSecure::available(uint8_t* status) { void WiFiServerSecure::setServerKeyAndCert(const uint8_t *key, int keyLen, const uint8_t *cert, int certLen) { _axtls_chain = nullptr; _axtls_sk = nullptr; - _axtls_chain = std::shared_ptr(new X509List(cert, certLen)); - _axtls_sk = std::shared_ptr(new PrivateKey(key, keyLen)); + _axtls_chain = std::shared_ptr(new (std::nothrow) X509List(cert, certLen)); + _axtls_sk = std::shared_ptr(new (std::nothrow) PrivateKey(key, keyLen)); setRSACert(_axtls_chain.get(), _axtls_sk.get()); } diff --git a/libraries/ESP8266WiFi/src/WiFiUdp.cpp b/libraries/ESP8266WiFi/src/WiFiUdp.cpp index a0a5c1d4e..8bbcddb27 100644 --- a/libraries/ESP8266WiFi/src/WiFiUdp.cpp +++ b/libraries/ESP8266WiFi/src/WiFiUdp.cpp @@ -80,7 +80,10 @@ uint8_t WiFiUDP::begin(uint16_t port) _ctx = 0; } - _ctx = new UdpContext; + _ctx = new (std::nothrow) UdpContext; + if (_ctx == nullptr) { + return 0; + } _ctx->ref(); return (_ctx->listen(IPAddress(), port)) ? 1 : 0; } @@ -96,7 +99,10 @@ uint8_t WiFiUDP::beginMulticast(IPAddress interfaceAddr, IPAddress multicast, ui return 0; } - _ctx = new UdpContext; + _ctx = new (std::nothrow) UdpContext; + if (_ctx == nullptr) { + return 0; + } _ctx->ref(); ip_addr_t addr = IPADDR4_INIT(INADDR_ANY); if (!_ctx->listen(&addr, port)) { @@ -147,7 +153,10 @@ int WiFiUDP::beginPacket(const char *host, uint16_t port) int WiFiUDP::beginPacket(IPAddress ip, uint16_t port) { if (!_ctx) { - _ctx = new UdpContext; + _ctx = new (std::nothrow) UdpContext; + if (_ctx == nullptr) { + return 0; + } _ctx->ref(); } return (_ctx->connect(ip, port)) ? 1 : 0; @@ -157,7 +166,10 @@ int WiFiUDP::beginPacketMulticast(IPAddress multicastAddress, uint16_t port, IPAddress interfaceAddress, int ttl) { if (!_ctx) { - _ctx = new UdpContext; + _ctx = new (std::nothrow) UdpContext; + if (_ctx == nullptr) { + return 0; + } _ctx->ref(); } if (!_ctx->connect(multicastAddress, port)) { diff --git a/libraries/ESP8266WiFi/src/include/ClientContext.h b/libraries/ESP8266WiFi/src/include/ClientContext.h index 8095e402a..47407bc00 100644 --- a/libraries/ESP8266WiFi/src/include/ClientContext.h +++ b/libraries/ESP8266WiFi/src/include/ClientContext.h @@ -374,7 +374,7 @@ public: if (!_pcb) { return 0; } - return _write_from_source(new BufferDataSource(data, size)); + return _write_from_source(new (std::nothrow) BufferDataSource(data, size)); } size_t write(Stream& stream) @@ -382,7 +382,7 @@ public: if (!_pcb) { return 0; } - return _write_from_source(new BufferedStreamDataSource(stream, stream.available())); + return _write_from_source(new (std::nothrow) BufferedStreamDataSource(stream, stream.available())); } size_t write_P(PGM_P buf, size_t size) @@ -391,7 +391,7 @@ public: return 0; } ProgmemStream stream(buf, size); - return _write_from_source(new BufferedStreamDataSource(stream, size)); + return _write_from_source(new (std::nothrow) BufferedStreamDataSource(stream, size)); } void keepAlive (uint16_t idle_sec = TCP_DEFAULT_KEEPALIVE_IDLE_SEC, uint16_t intv_sec = TCP_DEFAULT_KEEPALIVE_INTERVAL_SEC, uint8_t count = TCP_DEFAULT_KEEPALIVE_COUNT) diff --git a/libraries/ESP8266WiFi/src/include/DataSource.h b/libraries/ESP8266WiFi/src/include/DataSource.h index 2a0bfed26..624a9277e 100644 --- a/libraries/ESP8266WiFi/src/include/DataSource.h +++ b/libraries/ESP8266WiFi/src/include/DataSource.h @@ -75,7 +75,7 @@ public: //Buffer too small? if (_bufferSize < min_buffer_size) { - uint8_t *new_buffer = new uint8_t[min_buffer_size]; + uint8_t *new_buffer = new (std::nothrow) uint8_t[min_buffer_size]; //If stream reading is ahead, than some data is already in the old buffer and needs to be copied to new resized buffer if (_buffer && stream_read > 0) { memcpy(new_buffer, _buffer.get(), stream_read); diff --git a/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino b/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino index e196ef641..26fd06fbd 100644 --- a/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino +++ b/libraries/ESP8266httpUpdate/examples/httpUpdateSigned/httpUpdateSigned.ino @@ -74,9 +74,9 @@ void setup() { WiFiMulti.addAP(STASSID, STAPSK); #if MANUAL_SIGNING - signPubKey = new BearSSL::PublicKey(pubkey); - hash = new BearSSL::HashSHA256(); - sign = new BearSSL::SigningVerifier(signPubKey); + signPubKey = new (std::nothrow) BearSSL::PublicKey(pubkey); + hash = new (std::nothrow) BearSSL::HashSHA256(); + sign = new (std::nothrow) BearSSL::SigningVerifier(signPubKey); #endif } diff --git a/libraries/ESP8266mDNS/src/ESP8266mDNS_Legacy.cpp b/libraries/ESP8266mDNS/src/ESP8266mDNS_Legacy.cpp index 879119552..c15ead17b 100644 --- a/libraries/ESP8266mDNS/src/ESP8266mDNS_Legacy.cpp +++ b/libraries/ESP8266mDNS/src/ESP8266mDNS_Legacy.cpp @@ -225,7 +225,11 @@ bool MDNSResponder::_listen() return false; } - _conn = new UdpContext; + _conn = new (std::nothrow) UdpContext; + if (_conn == nullptr) + { + return false; + } _conn->ref(); if (!_conn->listen(IP_ADDR_ANY, MDNS_PORT)) @@ -276,7 +280,11 @@ bool MDNSResponder::addServiceTxt(char *name, char *proto, char *key, char *valu { return false; //max txt record size } - MDNSTxt *newtxt = new MDNSTxt; + MDNSTxt *newtxt = new (std::nothrow) MDNSTxt; + if (newtxt == nullptr) + { + return false; + } newtxt->_txt = String(key) + '=' + String(value); newtxt->_next = 0; if (servicePtr->_txts == 0) //no services have been added diff --git a/libraries/LittleFS/src/LittleFS.cpp b/libraries/LittleFS/src/LittleFS.cpp index 7fd4351fc..6de443fff 100644 --- a/libraries/LittleFS/src/LittleFS.cpp +++ b/libraries/LittleFS/src/LittleFS.cpp @@ -203,7 +203,7 @@ int LittleFSImpl::lfs_flash_sync(const struct lfs_config *c) { #endif #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_LITTLEFS) -FS LittleFS = FS(FSImplPtr(new littlefs_impl::LittleFSImpl(FS_PHYS_ADDR, FS_PHYS_SIZE, FS_PHYS_PAGE, FS_PHYS_BLOCK, FS_MAX_OPEN_FILES))); +FS LittleFS = FS(FSImplPtr(new (std::nothrow) littlefs_impl::LittleFSImpl(FS_PHYS_ADDR, FS_PHYS_SIZE, FS_PHYS_PAGE, FS_PHYS_BLOCK, FS_MAX_OPEN_FILES))); extern "C" void littlefs_request_end(void) { diff --git a/libraries/LittleFS/src/LittleFS.h b/libraries/LittleFS/src/LittleFS.h index f78680f66..7af4c0e2b 100644 --- a/libraries/LittleFS/src/LittleFS.h +++ b/libraries/LittleFS/src/LittleFS.h @@ -324,7 +324,11 @@ class LittleFSFileImpl : public FileImpl { public: LittleFSFileImpl(LittleFSImpl* fs, const char *name, std::shared_ptr fd, int flags, time_t creation) : _fs(fs), _fd(fd), _opened(true), _flags(flags), _creation(creation) { - _name = std::shared_ptr(new char[strlen(name) + 1], std::default_delete()); + _name = std::shared_ptr(new (std::nothrow) char[strlen(name) + 1], std::default_delete()); + if (!_name) { + close(); + return; + } strcpy(_name.get(), name); } @@ -517,17 +521,26 @@ public: { memset(&_dirent, 0, sizeof(_dirent)); if (dirPath) { - _dirPath = std::shared_ptr(new char[strlen(dirPath) + 1], std::default_delete()); + _dirPath = std::shared_ptr(new (std::nothrow) char[strlen(dirPath) + 1], std::default_delete()); + if (_dirPath == nullptr) { + close(); + return; + } strcpy(_dirPath.get(), dirPath); } } - ~LittleFSDirImpl() override { + void close () { if (_opened) { lfs_dir_close(_fs->getFS(), _getDir()); + _opened = false; } } + ~LittleFSDirImpl() override { + close(); + } + FileImplPtr openFile(OpenMode openMode, AccessMode accessMode) override { if (!_valid) { return FileImplPtr(); diff --git a/libraries/SDFS/src/SDFS.cpp b/libraries/SDFS/src/SDFS.cpp index d862ff5d8..90ef270dc 100644 --- a/libraries/SDFS/src/SDFS.cpp +++ b/libraries/SDFS/src/SDFS.cpp @@ -32,7 +32,7 @@ using namespace fs; #if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_SDFS) -FS SDFS = FS(FSImplPtr(new sdfs::SDFSImpl())); +FS SDFS = FS(FSImplPtr(new (std::nothrow) sdfs::SDFSImpl())); #endif namespace sdfs { diff --git a/libraries/esp8266/examples/ConfigFile/ConfigFile.ino b/libraries/esp8266/examples/ConfigFile/ConfigFile.ino index cb1d25be0..d03c19790 100644 --- a/libraries/esp8266/examples/ConfigFile/ConfigFile.ino +++ b/libraries/esp8266/examples/ConfigFile/ConfigFile.ino @@ -25,7 +25,10 @@ bool loadConfig() { } // Allocate a buffer to store contents of the file. - std::unique_ptr buf(new char[size]); + std::unique_ptr buf(new (std::nothrow) char[size]); + if (buf == nullptr) { + return false; + } // We don't use String here because ArduinoJson library requires the input // buffer to be mutable. If you don't use ArduinoJson, you may as well diff --git a/libraries/esp8266/examples/SerialStress/SerialStress.ino b/libraries/esp8266/examples/SerialStress/SerialStress.ino index 1412abd2b..b93e44360 100644 --- a/libraries/esp8266/examples/SerialStress/SerialStress.ino +++ b/libraries/esp8266/examples/SerialStress/SerialStress.ino @@ -72,7 +72,7 @@ void setup() { // using HardwareSerial0 pins, // so we can still log to the regular usbserial chips - SoftwareSerial* ss = new SoftwareSerial(3, 1); + SoftwareSerial* ss = new (std::nothrow) SoftwareSerial(3, 1); ss->begin(SSBAUD); ss->enableIntTx(false); logger = ss;