1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-06-04 18:03:20 +03:00

replace new by new (std::nothrow), remove arduino_new

This commit is contained in:
david gauchard 2020-08-17 18:15:45 +02:00
parent 5b3d290de8
commit 6925982284
45 changed files with 207 additions and 167 deletions

View File

@ -740,17 +740,17 @@ String EspClass::getSketchMD5()
}
uint32_t lengthLeft = getSketchSize();
const size_t bufSize = 512;
std::unique_ptr<uint8_t[]> buf(new uint8_t[bufSize]);
std::unique_ptr<uint8_t[]> 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<uint32_t*>(buf.get()), (readBytes + 3) & ~3)) {
return String();
return emptyString;
}
md5.add(buf.get(), readBytes);
lengthLeft -= readBytes;

View File

@ -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<void(void)> intRoutine, int mode)
bool attachInterrupt(uint8_t pin, std::function<void(void)> 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<void(InterruptInfo)> scheduledIntRoutine, int mode)
bool attachScheduledInterrupt(uint8_t pin, std::function<void(InterruptInfo)> 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);
}

View File

@ -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;
}

View File

@ -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

View File

@ -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) {

View File

@ -36,35 +36,6 @@
#include <stddef.h> // size_t
#include <stdint.h>
#ifdef __cplusplus
namespace arduino
{
extern "C++"
template <typename T, typename ...TConstructorArgs>
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<Type>(0, ##__VA_ARGS__)
#define arduino_newarray(Type, n, ...) arduino::new0<Type>(n, ##__VA_ARGS__)
#endif // __cplusplus
#ifndef __STRINGIFY
#define __STRINGIFY(a) #a
#endif

View File

@ -323,36 +323,3 @@ C++
This assures correct behavior, including handling of all subobjects, which guarantees stability.
History: `#6269 <https://github.com/esp8266/Arduino/issues/6269>`__ `#6309 <https://github.com/esp8266/Arduino/pull/6309>`__ `#6312 <https://github.com/esp8266/Arduino/pull/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;

View File

@ -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(){

View File

@ -178,8 +178,7 @@ void DNSServer::processNextRequest()
return;
std::unique_ptr<uint8_t[]> buffer(new (std::nothrow) uint8_t[currentPacketSize]);
if (buffer == NULL)
if (buffer == nullptr)
return;
_udp.read(buffer.get(), currentPacketSize);

View File

@ -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;

View File

@ -41,7 +41,10 @@ void loop() {
// wait for WiFi connection
if ((WiFiMulti.run() == WL_CONNECTED)) {
std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
std::unique_ptr<BearSSL::WiFiClientSecure>client(new (std::nothrow) BearSSL::WiFiClientSecure);
if (client == nullptr) {
return;
}
client->setFingerprint(fingerprint);

View File

@ -38,7 +38,10 @@ void loop() {
// wait for WiFi connection
if ((WiFiMulti.run() == WL_CONNECTED)) {
std::unique_ptr<BearSSL::WiFiClientSecure> client(new BearSSL::WiFiClientSecure);
std::unique_ptr<BearSSL::WiFiClientSecure> 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");

View File

@ -37,7 +37,7 @@ public:
virtual std::unique_ptr<WiFiClient> create()
{
return std::unique_ptr<WiFiClient>(new WiFiClient());
return std::unique_ptr<WiFiClient>(new (std::nothrow) WiFiClient());
}
virtual bool verify(WiFiClient& client, const char* host)
@ -59,8 +59,9 @@ public:
std::unique_ptr<WiFiClient> 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<WiFiClient>(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;
}

View File

@ -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();

View File

@ -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))

View File

@ -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);

View File

@ -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);

View File

@ -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);

View File

@ -126,12 +126,12 @@ bool ESP8266WebServerTemplate<ServerType>::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<ServerType>::on(const Uri &uri, HTTPMethod method,
template <typename ServerType>
void ESP8266WebServerTemplate<ServerType>::on(const Uri &uri, HTTPMethod method, ESP8266WebServerTemplate<ServerType>::THandlerFunction fn, ESP8266WebServerTemplate<ServerType>::THandlerFunction ufn) {
_addRequestHandler(new FunctionRequestHandler<ServerType>(fn, ufn, uri, method));
_addRequestHandler(new (std::nothrow) FunctionRequestHandler<ServerType>(fn, ufn, uri, method));
}
template <typename ServerType>
@ -288,7 +288,7 @@ void ESP8266WebServerTemplate<ServerType>::_addRequestHandler(RequestHandlerType
template <typename ServerType>
void ESP8266WebServerTemplate<ServerType>::serveStatic(const char* uri, FS& fs, const char* path, const char* cache_header) {
_addRequestHandler(new StaticRequestHandler<ServerType>(fs, path, uri, cache_header));
_addRequestHandler(new (std::nothrow) StaticRequestHandler<ServerType>(fs, path, uri, cache_header));
}
template <typename ServerType>
@ -645,7 +645,9 @@ void ESP8266WebServerTemplate<ServerType>::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];

View File

@ -283,7 +283,9 @@ void ESP8266WebServerTemplate<ServerType>::_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<ServerType>());
}
@ -370,7 +372,11 @@ bool ESP8266WebServerTemplate<ServerType>::_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<ServerType>::_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;

View File

@ -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<String> &pathArgs) {

View File

@ -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<String> &pathArgs) override final {

View File

@ -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<String> &pathArgs) override final {

View File

@ -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<String> &pathArgs) override final {

View File

@ -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, "/");

View File

@ -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

View File

@ -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

View File

@ -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");

View File

@ -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<br_x509_decoder_context> dc(new br_x509_decoder_context); // auto-delete on exit
std::unique_ptr<br_x509_decoder_context> dc(new (std::nothrow) br_x509_decoder_context); // auto-delete on exit
std::vector<uint8_t> 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_object> pem_list;
std::unique_ptr<br_pem_decoder_context> pc(new br_pem_decoder_context); // auto-delete on exit
std::unique_ptr<br_pem_decoder_context> 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<br_pkey_decoder_context> dc(new br_pkey_decoder_context); // auto-delete on exit
std::unique_ptr<br_pkey_decoder_context> 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<br_skey_decoder_context> dc(new br_skey_decoder_context); // auto-delete on exit
std::unique_ptr<br_skey_decoder_context> dc(new (std::nothrow) br_skey_decoder_context); // auto-delete on exit
if (!dc.get()) {
return nullptr;
}

View File

@ -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");

View File

@ -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));

View File

@ -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);

View File

@ -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<uint16_t>(new uint16_t[cipherCount], std::default_delete<uint16_t[]>());
_cipher_list = std::shared_ptr<uint16_t>(new (std::nothrow) uint16_t[cipherCount], std::default_delete<uint16_t[]>());
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<br_ssl_client_context>();
_eng = &_sc->eng; // Allocation/deallocation taken care of by the _sc shared_ptr
_iobuf_in = std::shared_ptr<unsigned char>(new unsigned char[_iobuf_in_size], std::default_delete<unsigned char[]>());
_iobuf_out = std::shared_ptr<unsigned char>(new unsigned char[_iobuf_out_size], std::default_delete<unsigned char[]>());
_iobuf_in = std::shared_ptr<unsigned char>(new (std::nothrow) unsigned char[_iobuf_in_size], std::default_delete<unsigned char[]>());
_iobuf_out = std::shared_ptr<unsigned char>(new (std::nothrow) unsigned char[_iobuf_out_size], std::default_delete<unsigned char[]>());
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<br_ssl_server_context>();
_eng = &_sc_svr->eng; // Allocation/deallocation taken care of by the _sc shared_ptr
_iobuf_in = std::shared_ptr<unsigned char>(new unsigned char[_iobuf_in_size], std::default_delete<unsigned char[]>());
_iobuf_out = std::shared_ptr<unsigned char>(new unsigned char[_iobuf_out_size], std::default_delete<unsigned char[]>());
_iobuf_in = std::shared_ptr<unsigned char>(new (std::nothrow) unsigned char[_iobuf_in_size], std::default_delete<unsigned char[]>());
_iobuf_out = std::shared_ptr<unsigned char>(new (std::nothrow) unsigned char[_iobuf_out_size], std::default_delete<unsigned char[]>());
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<br_ssl_server_context>();
_eng = &_sc_svr->eng; // Allocation/deallocation taken care of by the _sc shared_ptr
_iobuf_in = std::shared_ptr<unsigned char>(new unsigned char[_iobuf_in_size], std::default_delete<unsigned char[]>());
_iobuf_out = std::shared_ptr<unsigned char>(new unsigned char[_iobuf_out_size], std::default_delete<unsigned char[]>());
_iobuf_in = std::shared_ptr<unsigned char>(new (std::nothrow) unsigned char[_iobuf_in_size], std::default_delete<unsigned char[]>());
_iobuf_out = std::shared_ptr<unsigned char>(new (std::nothrow) unsigned char[_iobuf_out_size], std::default_delete<unsigned char[]>());
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<X509List>(new X509List(pk, size));
_axtls_ta = std::shared_ptr<X509List>(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<X509List>(new X509List(pk, size));
_axtls_chain = std::shared_ptr<X509List>(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<PrivateKey>(new PrivateKey(pk, size));
_axtls_sk = std::shared_ptr<PrivateKey>(new (std::nothrow) PrivateKey(pk, size));
_sk = _axtls_sk.get();
return _sk ? true : false;

View File

@ -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

View File

@ -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<X509List>(new X509List(cert, certLen));
_axtls_sk = std::shared_ptr<PrivateKey>(new PrivateKey(key, keyLen));
_axtls_chain = std::shared_ptr<X509List>(new (std::nothrow) X509List(cert, certLen));
_axtls_sk = std::shared_ptr<PrivateKey>(new (std::nothrow) PrivateKey(key, keyLen));
setRSACert(_axtls_chain.get(), _axtls_sk.get());
}

View File

@ -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)) {

View File

@ -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, stream.available()));
return _write_from_source(new (std::nothrow) BufferedStreamDataSource<Stream>(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<ProgmemStream>(stream, size));
return _write_from_source(new (std::nothrow) BufferedStreamDataSource<ProgmemStream>(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)

View File

@ -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);

View File

@ -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
}

View File

@ -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

View File

@ -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)
{

View File

@ -324,7 +324,11 @@ class LittleFSFileImpl : public FileImpl
{
public:
LittleFSFileImpl(LittleFSImpl* fs, const char *name, std::shared_ptr<lfs_file_t> fd, int flags, time_t creation) : _fs(fs), _fd(fd), _opened(true), _flags(flags), _creation(creation) {
_name = std::shared_ptr<char>(new char[strlen(name) + 1], std::default_delete<char[]>());
_name = std::shared_ptr<char>(new (std::nothrow) char[strlen(name) + 1], std::default_delete<char[]>());
if (!_name) {
close();
return;
}
strcpy(_name.get(), name);
}
@ -517,17 +521,26 @@ public:
{
memset(&_dirent, 0, sizeof(_dirent));
if (dirPath) {
_dirPath = std::shared_ptr<char>(new char[strlen(dirPath) + 1], std::default_delete<char[]>());
_dirPath = std::shared_ptr<char>(new (std::nothrow) char[strlen(dirPath) + 1], std::default_delete<char[]>());
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();

View File

@ -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 {

View File

@ -25,7 +25,10 @@ bool loadConfig() {
}
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
std::unique_ptr<char[]> 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

View File

@ -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;