diff --git a/ChangeLog b/ChangeLog index d19495caa..4bc41e71a 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,14 @@ +2008-04-27 Tatsuhiro Tsujikawa + + Rewritten Exception class. Throw exception object, not its pointer and + catch by reference, so that remove problematic delete operator for + catched exception. + * src/Exception.cc + * src/Exception.h + * test/ExceptionTest.cc + * src/*: All files throwing/catching exception. + * test/*: All files throwing/catching exception. + 2008-04-26 Tatsuhiro Tsujikawa Now auto protocol detection is enabled without -Z option. diff --git a/src/AbstractCommand.cc b/src/AbstractCommand.cc index 9745cf8a0..40febf230 100644 --- a/src/AbstractCommand.cc +++ b/src/AbstractCommand.cc @@ -53,6 +53,7 @@ #include "Socket.h" #include "message.h" #include "prefs.h" +#include "StringFormat.h" namespace aria2 { @@ -104,7 +105,7 @@ bool AbstractCommand::execute() { if(!peerStat.isNull()) { if(peerStat->getStatus() == PeerStat::REQUEST_IDLE) { logger->info(MSG_ABORT_REQUESTED, cuid); - onAbort(0); + onAbort(); req->resetUrl(); tryReserved(); return true; @@ -141,39 +142,35 @@ bool AbstractCommand::execute() { return executeInternal(); } else { if(checkPoint.elapsed(timeout)) { - throw new DlRetryEx(EX_TIME_OUT); + throw DlRetryEx(EX_TIME_OUT); } e->commands.push_back(this); return false; } - } catch(DlAbortEx* err) { + } catch(DlAbortEx& err) { logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str()); - onAbort(err); - delete(err); + onAbort(); req->resetUrl(); tryReserved(); return true; - } catch(DlRetryEx* err) { + } catch(DlRetryEx& err) { logger->info(MSG_RESTARTING_DOWNLOAD, err, cuid, req->getUrl().c_str()); req->addTryCount(); bool isAbort = e->option->getAsInt(PREF_MAX_TRIES) != 0 && req->getTryCount() >= (unsigned int)e->option->getAsInt(PREF_MAX_TRIES); if(isAbort) { - onAbort(err); + onAbort(); } if(isAbort) { logger->info(MSG_MAX_TRY, cuid, req->getTryCount()); logger->error(MSG_DOWNLOAD_ABORTED, err, cuid, req->getUrl().c_str()); - delete(err); tryReserved(); return true; } else { - delete(err); return prepareForRetry(e->option->getAsInt(PREF_RETRY_WAIT)); } - } catch(DownloadFailureException* err) { + } catch(DownloadFailureException& err) { logger->error(EX_EXCEPTION_CAUGHT, err); - delete(err); _requestGroup->setHaltRequested(true); return true; } @@ -200,7 +197,7 @@ bool AbstractCommand::prepareForRetry(time_t wait) { return true; } -void AbstractCommand::onAbort(Exception* ex) { +void AbstractCommand::onAbort() { logger->debug(MSG_UNREGISTER_CUID, cuid); //_segmentMan->unregisterId(cuid); if(!_requestGroup->getPieceStorage().isNull()) { @@ -278,9 +275,9 @@ bool AbstractCommand::resolveHostname(const std::string& hostname, return true; break; case NameResolver::STATUS_ERROR: - throw new DlAbortEx(MSG_NAME_RESOLUTION_FAILED, cuid, - hostname.c_str(), - resolver->getError().c_str()); + throw DlAbortEx(StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid, + hostname.c_str(), + resolver->getError().c_str()).str()); default: return false; } diff --git a/src/AbstractCommand.h b/src/AbstractCommand.h index 4f1526992..831a0ada5 100644 --- a/src/AbstractCommand.h +++ b/src/AbstractCommand.h @@ -62,7 +62,7 @@ protected: void tryReserved(); virtual bool prepareForRetry(time_t wait); - virtual void onAbort(Exception* ex); + virtual void onAbort(); virtual bool executeInternal() = 0; void setReadCheckSocket(const SharedHandle& socket); diff --git a/src/AbstractDiskWriter.cc b/src/AbstractDiskWriter.cc index 9b3914f4d..1b86da280 100644 --- a/src/AbstractDiskWriter.cc +++ b/src/AbstractDiskWriter.cc @@ -40,6 +40,7 @@ #include "Logger.h" #include "DlAbortEx.h" #include "a2io.h" +#include "StringFormat.h" #include #include #include @@ -79,11 +80,13 @@ void AbstractDiskWriter::openExistingFile(const std::string& filename, this->filename = filename; File f(filename); if(!f.isFile()) { - throw new DlAbortEx(EX_FILE_OPEN, filename.c_str(), MSG_FILE_NOT_FOUND); + throw DlAbortEx + (StringFormat(EX_FILE_OPEN, filename.c_str(), MSG_FILE_NOT_FOUND).str()); } if((fd = open(filename.c_str(), O_RDWR|O_BINARY, OPEN_MODE)) < 0) { - throw new DlAbortEx(EX_FILE_OPEN, filename.c_str(), strerror(errno)); + throw DlAbortEx + (StringFormat(EX_FILE_OPEN, filename.c_str(), strerror(errno)).str()); } } @@ -93,7 +96,7 @@ void AbstractDiskWriter::createFile(const std::string& filename, int addFlags) assert(filename.size()); Util::mkdirs(File(filename).getDirname()); if((fd = open(filename.c_str(), O_CREAT|O_RDWR|O_TRUNC|O_BINARY|addFlags, OPEN_MODE)) < 0) { - throw new DlAbortEx(EX_FILE_OPEN, filename.c_str(), strerror(errno)); + throw DlAbortEx(StringFormat(EX_FILE_OPEN, filename.c_str(), strerror(errno)).str()); } } @@ -121,7 +124,8 @@ ssize_t AbstractDiskWriter::readDataInternal(unsigned char* data, size_t len) void AbstractDiskWriter::seek(off_t offset) { if(offset != lseek(fd, offset, SEEK_SET)) { - throw new DlAbortEx(EX_FILE_SEEK, filename.c_str(), strerror(errno)); + throw DlAbortEx + (StringFormat(EX_FILE_SEEK, filename.c_str(), strerror(errno)).str()); } } @@ -129,7 +133,7 @@ void AbstractDiskWriter::writeData(const unsigned char* data, size_t len, off_t { seek(offset); if(writeDataInternal(data, len) < 0) { - throw new DlAbortEx(EX_FILE_WRITE, filename.c_str(), strerror(errno)); + throw DlAbortEx(StringFormat(EX_FILE_WRITE, filename.c_str(), strerror(errno)).str()); } } @@ -138,7 +142,7 @@ ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len, off_t offs ssize_t ret; seek(offset); if((ret = readDataInternal(data, len)) < 0) { - throw new DlAbortEx(EX_FILE_READ, filename.c_str(), strerror(errno)); + throw DlAbortEx(StringFormat(EX_FILE_READ, filename.c_str(), strerror(errno)).str()); } return ret; } @@ -146,7 +150,7 @@ ssize_t AbstractDiskWriter::readData(unsigned char* data, size_t len, off_t offs void AbstractDiskWriter::truncate(uint64_t length) { if(fd == -1) { - throw new DlAbortEx("File not opened."); + throw DlAbortEx("File not opened."); } ftruncate(fd, length); } @@ -155,7 +159,7 @@ void AbstractDiskWriter::truncate(uint64_t length) uint64_t AbstractDiskWriter::size() const { if(fd == -1) { - throw new DlAbortEx("File not opened."); + throw DlAbortEx("File not opened."); } struct stat fileStat; if(fstat(fd, &fileStat) < 0) { diff --git a/src/AbstractProxyResponseCommand.cc b/src/AbstractProxyResponseCommand.cc index e7a620be0..dcab70ed8 100644 --- a/src/AbstractProxyResponseCommand.cc +++ b/src/AbstractProxyResponseCommand.cc @@ -66,7 +66,7 @@ bool AbstractProxyResponseCommand::executeInternal() { return false; } if(httpResponse->getResponseStatus() != "200") { - throw new DlRetryEx(EX_PROXY_CONNECTION_FAILED); + throw DlRetryEx(EX_PROXY_CONNECTION_FAILED); } e->commands.push_back(getNextCommand()); return true; diff --git a/src/BtAllowedFastMessage.cc b/src/BtAllowedFastMessage.cc index 788198070..434a053ce 100644 --- a/src/BtAllowedFastMessage.cc +++ b/src/BtAllowedFastMessage.cc @@ -38,16 +38,19 @@ #include "DlAbortEx.h" #include "message.h" #include "Peer.h" +#include "StringFormat.h" namespace aria2 { BtAllowedFastMessageHandle BtAllowedFastMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 5) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "allowed fast", dataLength, 5); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "allowed fast", dataLength, 5).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "allowed fast", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "allowed fast", ID).str()); } BtAllowedFastMessageHandle message(new BtAllowedFastMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); @@ -56,8 +59,9 @@ BtAllowedFastMessageHandle BtAllowedFastMessage::create(const unsigned char* dat void BtAllowedFastMessage::doReceivedAction() { if(!peer->isFastExtensionEnabled()) { - throw new DlAbortEx("%s received while fast extension is disabled", - toString().c_str()); + throw DlAbortEx + (StringFormat("%s received while fast extension is disabled", + toString().c_str()).str()); } peer->addPeerAllowedIndex(index); } diff --git a/src/BtBitfieldMessage.cc b/src/BtBitfieldMessage.cc index 9c8466e0d..4cd935efd 100644 --- a/src/BtBitfieldMessage.cc +++ b/src/BtBitfieldMessage.cc @@ -38,6 +38,7 @@ #include "DlAbortEx.h" #include "message.h" #include "Peer.h" +#include "StringFormat.h" #include namespace aria2 { @@ -57,11 +58,13 @@ BtBitfieldMessageHandle BtBitfieldMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength <= 1) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "bitfield", dataLength, 1); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "bitfield", dataLength, 1).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "bitfield", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "bitfield", ID).str()); } BtBitfieldMessageHandle message(new BtBitfieldMessage()); message->setBitfield((unsigned char*)data+1, dataLength-1); diff --git a/src/BtCancelMessage.cc b/src/BtCancelMessage.cc index 144cd089b..ef6d3dac1 100644 --- a/src/BtCancelMessage.cc +++ b/src/BtCancelMessage.cc @@ -38,16 +38,19 @@ #include "DlAbortEx.h" #include "message.h" #include "BtMessageDispatcher.h" +#include "StringFormat.h" namespace aria2 { BtCancelMessageHandle BtCancelMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 13) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "cancel", dataLength, 13); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "cancel", dataLength, 13).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "cancel", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "cancel", ID).str()); } BtCancelMessageHandle message(new BtCancelMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); diff --git a/src/BtChokeMessage.cc b/src/BtChokeMessage.cc index 9c328e6c0..e3d5bc6e0 100644 --- a/src/BtChokeMessage.cc +++ b/src/BtChokeMessage.cc @@ -39,16 +39,19 @@ #include "Peer.h" #include "BtMessageDispatcher.h" #include "BtRequestFactory.h" +#include "StringFormat.h" namespace aria2 { BtChokeMessageHandle BtChokeMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 1) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "choke", dataLength, 1); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "choke", dataLength, 1).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "choke", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "choke", ID).str()); } BtChokeMessageHandle chokeMessage(new BtChokeMessage()); return chokeMessage; diff --git a/src/BtDependency.cc b/src/BtDependency.cc index 40c958675..36c30fe7e 100644 --- a/src/BtDependency.cc +++ b/src/BtDependency.cc @@ -75,9 +75,8 @@ bool BtDependency::resolve() btContext->setPeerIdPrefix(_option->get(PREF_PEER_ID_PREFIX)); } btContext->setDir(_dependant->getDownloadContext()->getDir()); - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { _logger->error(EX_EXCEPTION_CAUGHT, e); - delete e; _logger->debug("BtDependency for GID#%d failed. Go without Bt.", _dependant->getGID()); return true; diff --git a/src/BtExtendedMessage.cc b/src/BtExtendedMessage.cc index 361503e6a..b576bd4d0 100644 --- a/src/BtExtendedMessage.cc +++ b/src/BtExtendedMessage.cc @@ -48,6 +48,7 @@ #include "DlAbortEx.h" #include "message.h" #include "Util.h" +#include "StringFormat.h" #include #include @@ -100,11 +101,13 @@ BtExtendedMessage::create(const BtContextHandle& btContext, const unsigned char* data, size_t dataLength) { if(dataLength < 2) { - throw new DlAbortEx(MSG_TOO_SMALL_PAYLOAD_SIZE, "extended", dataLength); + throw DlAbortEx + (StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE, "extended", dataLength).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "extended", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "extended", ID).str()); } ExtensionMessageFactoryHandle factory = EXTENSION_MESSAGE_FACTORY(btContext, peer); diff --git a/src/BtHandshakeMessageValidator.h b/src/BtHandshakeMessageValidator.h index 2bdcef671..a7a7ff4b5 100644 --- a/src/BtHandshakeMessageValidator.h +++ b/src/BtHandshakeMessageValidator.h @@ -39,6 +39,7 @@ #include "BtHandshakeMessage.h" #include "Util.h" #include "PeerMessageUtil.h" +#include "StringFormat.h" #include namespace aria2 { @@ -58,17 +59,19 @@ public: virtual bool validate(Errors& error) { // TODO if(message->getPstrlen() != 19) { - throw new DlAbortEx("invalid handshake pstrlen=%u", - message->getPstrlen()); + throw DlAbortEx(StringFormat("invalid handshake pstrlen=%u", + message->getPstrlen()).str()); } if(memcmp(BtHandshakeMessage::BT_PSTR, message->getPstr(), 19) != 0) { - throw new DlAbortEx("invalid handshake pstr=%s", - Util::urlencode(message->getPstr(), 19).c_str()); + throw DlAbortEx + (StringFormat("invalid handshake pstr=%s", + Util::urlencode(message->getPstr(), 19).c_str()).str()); } if(memcmp(infoHash, message->getInfoHash(), 20) != 0) { - throw new DlAbortEx("invalid handshake info hash: expected:%s, actual:%s", - Util::toHex(infoHash, 20).c_str(), - Util::toHex(message->getInfoHash(), 20).c_str()); + throw DlAbortEx + (StringFormat("invalid handshake info hash: expected:%s, actual:%s", + Util::toHex(infoHash, 20).c_str(), + Util::toHex(message->getInfoHash(), 20).c_str()).str()); } return true; } diff --git a/src/BtHaveAllMessage.cc b/src/BtHaveAllMessage.cc index ba82fd1a4..07a78f435 100644 --- a/src/BtHaveAllMessage.cc +++ b/src/BtHaveAllMessage.cc @@ -37,16 +37,19 @@ #include "PeerMessageUtil.h" #include "message.h" #include "Peer.h" +#include "StringFormat.h" namespace aria2 { BtHaveAllMessageHandle BtHaveAllMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 1) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "have all", dataLength, 1); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "have all", dataLength, 1).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "have all", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "have all", ID).str()); } BtHaveAllMessageHandle message(new BtHaveAllMessage()); return message; @@ -54,8 +57,9 @@ BtHaveAllMessageHandle BtHaveAllMessage::create(const unsigned char* data, size_ void BtHaveAllMessage::doReceivedAction() { if(!peer->isFastExtensionEnabled()) { - throw new DlAbortEx("%s received while fast extension is disabled", - toString().c_str()); + throw DlAbortEx + (StringFormat("%s received while fast extension is disabled", + toString().c_str()).str()); } peer->setAllBitfield(); } diff --git a/src/BtHaveMessage.cc b/src/BtHaveMessage.cc index 6ea78e5f7..7aa445f96 100644 --- a/src/BtHaveMessage.cc +++ b/src/BtHaveMessage.cc @@ -38,16 +38,19 @@ #include "DlAbortEx.h" #include "message.h" #include "Peer.h" +#include "StringFormat.h" namespace aria2 { BtHaveMessageHandle BtHaveMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 5) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "have", dataLength, 5); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "have", dataLength, 5).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "have", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "have", ID).str()); } BtHaveMessageHandle message(new BtHaveMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); diff --git a/src/BtHaveNoneMessage.cc b/src/BtHaveNoneMessage.cc index 3220ba4ab..04d163254 100644 --- a/src/BtHaveNoneMessage.cc +++ b/src/BtHaveNoneMessage.cc @@ -37,16 +37,19 @@ #include "PeerMessageUtil.h" #include "message.h" #include "Peer.h" +#include "StringFormat.h" namespace aria2 { BtHaveNoneMessageHandle BtHaveNoneMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 1) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "have none", dataLength, 1); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "have none", dataLength, 1).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "have none", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "have none", ID).str()); } BtHaveNoneMessageHandle message(new BtHaveNoneMessage()); return message; @@ -54,8 +57,9 @@ BtHaveNoneMessageHandle BtHaveNoneMessage::create(const unsigned char* data, siz void BtHaveNoneMessage::doReceivedAction() { if(!peer->isFastExtensionEnabled()) { - throw new DlAbortEx("%s received while fast extension is disabled", - toString().c_str()); + throw DlAbortEx + (StringFormat("%s received while fast extension is disabled", + toString().c_str()).str()); } } diff --git a/src/BtInterestedMessage.cc b/src/BtInterestedMessage.cc index 46523abe8..3e63b2f24 100644 --- a/src/BtInterestedMessage.cc +++ b/src/BtInterestedMessage.cc @@ -40,16 +40,19 @@ #include "BtRegistry.h" #include "BtContext.h" #include "PeerStorage.h" +#include "StringFormat.h" namespace aria2 { BtInterestedMessageHandle BtInterestedMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 1) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "interested", dataLength, 1); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "interested", dataLength, 1).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "interested", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "interested", ID).str()); } BtInterestedMessageHandle message(new BtInterestedMessage()); return message; diff --git a/src/BtNotInterestedMessage.cc b/src/BtNotInterestedMessage.cc index 32ec0da90..a93e1fafd 100644 --- a/src/BtNotInterestedMessage.cc +++ b/src/BtNotInterestedMessage.cc @@ -40,16 +40,19 @@ #include "BtRegistry.h" #include "BtContext.h" #include "PeerStorage.h" +#include "StringFormat.h" namespace aria2 { BtNotInterestedMessageHandle BtNotInterestedMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 1) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "not interested", dataLength, 1); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "not interested", dataLength, 1).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "not interested", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "not interested", ID).str()); } BtNotInterestedMessageHandle message(new BtNotInterestedMessage()); return message; diff --git a/src/BtPieceMessage.cc b/src/BtPieceMessage.cc index a5de003f6..4bc58b05e 100644 --- a/src/BtPieceMessage.cc +++ b/src/BtPieceMessage.cc @@ -50,6 +50,7 @@ #include "BtMessageFactory.h" #include "BtRequestFactory.h" #include "PeerConnection.h" +#include "StringFormat.h" #include namespace aria2 { @@ -63,11 +64,13 @@ void BtPieceMessage::setBlock(const unsigned char* block, size_t blockLength) { BtPieceMessageHandle BtPieceMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength <= 9) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "piece", dataLength, 9); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "piece", dataLength, 9).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID).str()); } BtPieceMessageHandle message(new BtPieceMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); @@ -171,7 +174,7 @@ size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const { size_t writtenLength = 0; for(int i = 0; i < res.quot; i++) { if((size_t)pieceStorage->getDiskAdaptor()->readData(buf, BUF_SIZE, offset+i*BUF_SIZE) < BUF_SIZE) { - throw new DlAbortEx(EX_DATA_READ); + throw DlAbortEx(EX_DATA_READ); } size_t ws = peerConnection->sendMessage(buf, BUF_SIZE); writtenLength += ws; @@ -181,7 +184,7 @@ size_t BtPieceMessage::sendPieceData(off_t offset, size_t length) const { } if(res.rem > 0) { if(pieceStorage->getDiskAdaptor()->readData(buf, res.rem, offset+res.quot*BUF_SIZE) < res.rem) { - throw new DlAbortEx(EX_DATA_READ); + throw DlAbortEx(EX_DATA_READ); } size_t ws = peerConnection->sendMessage(buf, res.rem); writtenLength += ws; diff --git a/src/BtPortMessage.cc b/src/BtPortMessage.cc index 4414e241b..17cd1c8b5 100644 --- a/src/BtPortMessage.cc +++ b/src/BtPortMessage.cc @@ -44,6 +44,7 @@ #include "DHTTaskQueue.h" #include "DHTTaskFactory.h" #include "DHTTask.h" +#include "StringFormat.h" namespace aria2 { @@ -57,11 +58,13 @@ BtPortMessage::~BtPortMessage() SharedHandle BtPortMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 3) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "port", dataLength, 3); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "port", dataLength, 3).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "piece", ID).str()); } uint16_t port = PeerMessageUtil::getShortIntParam(data, 1); SharedHandle message(new BtPortMessage(port)); diff --git a/src/BtPostDownloadHandler.cc b/src/BtPostDownloadHandler.cc index 8253224e7..92a68b773 100644 --- a/src/BtPostDownloadHandler.cc +++ b/src/BtPostDownloadHandler.cc @@ -70,7 +70,7 @@ RequestGroups BtPostDownloadHandler::getNextRequestGroups(RequestGroup* requestG requestGroup->getPieceStorage()->getDiskAdaptor()->openExistingFile(); content = Util::toString(requestGroup->getPieceStorage()->getDiskAdaptor()); requestGroup->getPieceStorage()->getDiskAdaptor()->closeFile(); - } catch(Exception* e) { + } catch(Exception& e) { requestGroup->getPieceStorage()->getDiskAdaptor()->closeFile(); throw; } diff --git a/src/BtRejectMessage.cc b/src/BtRejectMessage.cc index feb430e07..79213a1e5 100644 --- a/src/BtRejectMessage.cc +++ b/src/BtRejectMessage.cc @@ -40,16 +40,19 @@ #include "Peer.h" #include "RequestSlot.h" #include "BtMessageDispatcher.h" +#include "StringFormat.h" namespace aria2 { BtRejectMessageHandle BtRejectMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 13) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "reject", dataLength, 13); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "reject", dataLength, 13).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "reject", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "reject", ID).str()); } BtRejectMessageHandle message(new BtRejectMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); @@ -60,14 +63,15 @@ BtRejectMessageHandle BtRejectMessage::create(const unsigned char* data, size_t void BtRejectMessage::doReceivedAction() { if(!peer->isFastExtensionEnabled()) { - throw new DlAbortEx("%s received while fast extension is disabled.", - toString().c_str()); + throw DlAbortEx + (StringFormat("%s received while fast extension is disabled.", + toString().c_str()).str()); } // TODO Current implementation does not close a connection even if // a request for this reject message has never sent. RequestSlot slot = dispatcher->getOutstandingRequest(index, begin, length); if(RequestSlot::isNull(slot)) { - //throw new DlAbortEx("reject recieved, but it is not in the request slots."); + //throw DlAbortEx("reject recieved, but it is not in the request slots."); } else { dispatcher->removeOutstandingRequest(slot); } diff --git a/src/BtRequestMessage.cc b/src/BtRequestMessage.cc index 5b9a9bfe2..1c46a3a5d 100644 --- a/src/BtRequestMessage.cc +++ b/src/BtRequestMessage.cc @@ -44,16 +44,19 @@ #include "PieceStorage.h" #include "BtMessageDispatcher.h" #include "BtMessageFactory.h" +#include "StringFormat.h" namespace aria2 { BtRequestMessageHandle BtRequestMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 13) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "request", dataLength, 13); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "request", dataLength, 13).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "request", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "request", ID).str()); } BtRequestMessageHandle message(new BtRequestMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); diff --git a/src/BtSuggestPieceMessage.cc b/src/BtSuggestPieceMessage.cc index 38aee573c..b2cb7670e 100644 --- a/src/BtSuggestPieceMessage.cc +++ b/src/BtSuggestPieceMessage.cc @@ -37,16 +37,19 @@ #include "Util.h" #include "DlAbortEx.h" #include "message.h" +#include "StringFormat.h" namespace aria2 { BtSuggestPieceMessageHandle BtSuggestPieceMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 5) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "suggest piece", dataLength, 5); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "suggest piece", dataLength, 5).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "suggest piece", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "suggest piece", ID).str()); } BtSuggestPieceMessageHandle message(new BtSuggestPieceMessage()); message->setIndex(PeerMessageUtil::getIntParam(data, 1)); diff --git a/src/BtUnchokeMessage.cc b/src/BtUnchokeMessage.cc index 00c3d437b..87057f303 100644 --- a/src/BtUnchokeMessage.cc +++ b/src/BtUnchokeMessage.cc @@ -37,16 +37,19 @@ #include "DlAbortEx.h" #include "message.h" #include "Peer.h" +#include "StringFormat.h" namespace aria2 { BtUnchokeMessageHandle BtUnchokeMessage::create(const unsigned char* data, size_t dataLength) { if(dataLength != 1) { - throw new DlAbortEx(EX_INVALID_PAYLOAD_SIZE, "unchoke", dataLength, 1); + throw DlAbortEx + (StringFormat(EX_INVALID_PAYLOAD_SIZE, "unchoke", dataLength, 1).str()); } uint8_t id = PeerMessageUtil::getId(data); if(id != ID) { - throw new DlAbortEx(EX_INVALID_BT_MESSAGE_ID, id, "unchoke", ID); + throw DlAbortEx + (StringFormat(EX_INVALID_BT_MESSAGE_ID, id, "unchoke", ID).str()); } BtUnchokeMessageHandle message(new BtUnchokeMessage()); return message; diff --git a/src/CheckIntegrityCommand.cc b/src/CheckIntegrityCommand.cc index 4d6cbf230..54a6ffa74 100644 --- a/src/CheckIntegrityCommand.cc +++ b/src/CheckIntegrityCommand.cc @@ -79,7 +79,7 @@ bool CheckIntegrityCommand::executeInternal() } } -bool CheckIntegrityCommand::handleException(Exception* e) +bool CheckIntegrityCommand::handleException(Exception& e) { logger->error(MSG_FILE_VALIDATION_FAILURE, e, cuid); logger->error(MSG_DOWNLOAD_NOT_COMPLETE, cuid, _requestGroup->getFilePath().c_str()); diff --git a/src/CheckIntegrityCommand.h b/src/CheckIntegrityCommand.h index b19829f58..4cf1378b8 100644 --- a/src/CheckIntegrityCommand.h +++ b/src/CheckIntegrityCommand.h @@ -57,7 +57,7 @@ public: virtual bool executeInternal(); - virtual bool handleException(Exception* e); + virtual bool handleException(Exception& e); }; } // namespace aria2 diff --git a/src/ChunkedEncoding.cc b/src/ChunkedEncoding.cc index 015216b4d..ea9ea2f23 100644 --- a/src/ChunkedEncoding.cc +++ b/src/ChunkedEncoding.cc @@ -36,6 +36,7 @@ #include "DlAbortEx.h" #include "message.h" #include "Util.h" +#include "StringFormat.h" #include namespace aria2 { @@ -144,7 +145,7 @@ int ChunkedEncoding::readDataEOL(unsigned char** pp) { } else if(strbufTail-*pp < 2) { return -1; } else { - throw new DlAbortEx(EX_INVALID_CHUNK_SIZE); + throw DlAbortEx(EX_INVALID_CHUNK_SIZE); } } @@ -166,7 +167,7 @@ int ChunkedEncoding::readChunkSize(unsigned char** pp) { std::string temp(*pp, exsp); chunkSize = Util::parseInt(temp, 16); if(chunkSize < 0) { - throw new DlAbortEx(EX_INVALID_CHUNK_SIZE); + throw DlAbortEx(EX_INVALID_CHUNK_SIZE); } *pp = p+2; return 0; @@ -176,7 +177,8 @@ void ChunkedEncoding::addBuffer(const unsigned char* inbuf, size_t inlen) { size_t realbufSize = strbufTail-strbuf; if(realbufSize+inlen >= strbufSize) { if(realbufSize+inlen > MAX_BUFSIZE) { - throw new DlAbortEx(EX_TOO_LARGE_CHUNK, realbufSize+inlen); + throw DlAbortEx + (StringFormat(EX_TOO_LARGE_CHUNK, realbufSize+inlen).str()); } strbufSize = realbufSize+inlen; unsigned char* temp = new unsigned char[strbufSize]; diff --git a/src/CookieBoxFactory.cc b/src/CookieBoxFactory.cc index ba610a954..f022f5988 100644 --- a/src/CookieBoxFactory.cc +++ b/src/CookieBoxFactory.cc @@ -60,10 +60,9 @@ void CookieBoxFactory::loadDefaultCookie(std::istream& s) if(c.good()) { defaultCookies.push_back(c); } - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { // ignore malformed cookie entry // TODO better to log it - delete e; } } } diff --git a/src/DHTAnnouncePeerMessage.cc b/src/DHTAnnouncePeerMessage.cc index 794bd797a..802d361fa 100644 --- a/src/DHTAnnouncePeerMessage.cc +++ b/src/DHTAnnouncePeerMessage.cc @@ -45,6 +45,7 @@ #include "DHTTokenTracker.h" #include "DlAbortEx.h" #include "BtConstants.h" +#include "StringFormat.h" #include namespace aria2 { @@ -97,10 +98,11 @@ void DHTAnnouncePeerMessage::validate() const if(!_tokenTracker->validateToken(_token, _infoHash, _remoteNode->getIPAddress(), _remoteNode->getPort())) { - throw new DlAbortEx("Invalid token=%s from %s:%u", - Util::toHex(_token).c_str(), - _remoteNode->getIPAddress().c_str(), - _remoteNode->getPort()); + throw DlAbortEx + (StringFormat("Invalid token=%s from %s:%u", + Util::toHex(_token).c_str(), + _remoteNode->getIPAddress().c_str(), + _remoteNode->getPort()).str()); } } diff --git a/src/DHTAutoSaveCommand.cc b/src/DHTAutoSaveCommand.cc index 30aca9f9e..72ae4cbc9 100644 --- a/src/DHTAutoSaveCommand.cc +++ b/src/DHTAutoSaveCommand.cc @@ -117,10 +117,9 @@ void DHTAutoSaveCommand::save() } catch(std::ios::failure const& e) { logger->error("Failed to save DHT routing table to %s. cause:%s", tempFile.c_str(), strerror(errno)); - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { logger->error("Exception caught while saving DHT routing table to %s", e, tempFile.c_str()); - delete e; } } diff --git a/src/DHTConnectionImpl.cc b/src/DHTConnectionImpl.cc index 3e0036c50..6b285356f 100644 --- a/src/DHTConnectionImpl.cc +++ b/src/DHTConnectionImpl.cc @@ -71,9 +71,8 @@ bool DHTConnectionImpl::bind(uint16_t& port) port = svaddr.second; _logger->info("Bind socket for DHT. port=%u", port); return true; - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { _logger->error("Failed to bind for DHT. port=%u", e, port); - delete e; } return false; } diff --git a/src/DHTEntryPointNameResolveCommand.cc b/src/DHTEntryPointNameResolveCommand.cc index f5c52008a..9c214d30e 100644 --- a/src/DHTEntryPointNameResolveCommand.cc +++ b/src/DHTEntryPointNameResolveCommand.cc @@ -48,6 +48,7 @@ #include "DHTTask.h" #include "RequestGroupMan.h" #include "Logger.h" +#include "StringFormat.h" namespace aria2 { @@ -95,9 +96,8 @@ bool DHTEntryPointNameResolveCommand::execute() return false; } } - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { logger->error(EX_EXCEPTION_CAUGHT, e); - delete e; _entryPoints.erase(_entryPoints.begin()); _resolver->reset(); } @@ -107,9 +107,8 @@ bool DHTEntryPointNameResolveCommand::execute() _taskQueue->addPeriodicTask1(_taskFactory->createNodeLookupTask(_localNode->getID())); _taskQueue->addPeriodicTask1(_taskFactory->createBucketRefreshTask()); } - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { logger->error(EX_EXCEPTION_CAUGHT, e); - delete e; } return true; } @@ -142,9 +141,10 @@ bool DHTEntryPointNameResolveCommand::resolveHostname(const std::string& hostnam return true; break; case NameResolver::STATUS_ERROR: - throw new DlAbortEx(MSG_NAME_RESOLUTION_FAILED, cuid, - hostname.c_str(), - resolver->getError().c_str()); + throw DlAbortEx + (StringFormat(MSG_NAME_RESOLUTION_FAILED, cuid, + hostname.c_str(), + resolver->getError().c_str()).str()); default: return false; } diff --git a/src/DHTInteractionCommand.cc b/src/DHTInteractionCommand.cc index f758cbe53..7422d2bf1 100644 --- a/src/DHTInteractionCommand.cc +++ b/src/DHTInteractionCommand.cc @@ -84,9 +84,8 @@ bool DHTInteractionCommand::execute() _receiver->handleTimeout(); try { _dispatcher->sendMessages(); - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { logger->error(EX_EXCEPTION_CAUGHT, e); - delete e; } _e->commands.push_back(this); return false; diff --git a/src/DHTMessageDispatcherImpl.cc b/src/DHTMessageDispatcherImpl.cc index 9d85c89b1..1abe373ed 100644 --- a/src/DHTMessageDispatcherImpl.cc +++ b/src/DHTMessageDispatcherImpl.cc @@ -41,6 +41,7 @@ #include "LogFactory.h" #include "Logger.h" #include "DHTConstants.h" +#include "StringFormat.h" namespace aria2 { @@ -75,9 +76,8 @@ DHTMessageDispatcherImpl::sendMessage(const SharedHandle& entry _tracker->addMessage(entry->_message, entry->_timeout, entry->_callback); } _logger->info("Message sent: %s", entry->_message->toString().c_str()); - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { _logger->error("Failed to send message: %s", e, entry->_message->toString().c_str()); - delete e; } } diff --git a/src/DHTMessageFactoryImpl.cc b/src/DHTMessageFactoryImpl.cc index cd072a09c..cbe083e9b 100644 --- a/src/DHTMessageFactoryImpl.cc +++ b/src/DHTMessageFactoryImpl.cc @@ -59,6 +59,7 @@ #include "Util.h" #include "Peer.h" #include "Logger.h" +#include "StringFormat.h" #include #include @@ -87,7 +88,8 @@ static const Dictionary* getDictionary(const Dictionary* d, const std::string& k if(c) { return c; } else { - throw new DlAbortEx("Malformed DHT message. Missing %s", key.c_str()); + throw DlAbortEx + (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str()); } } @@ -97,7 +99,8 @@ static const Data* getData(const Dictionary* d, const std::string& key) if(c) { return c; } else { - throw new DlAbortEx("Malformed DHT message. Missing %s", key.c_str()); + throw DlAbortEx + (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str()); } } @@ -107,8 +110,9 @@ static const Data* getData(const List* l, size_t index) if(c) { return c; } else { - throw new DlAbortEx("Malformed DHT message. element[%u] is not Data.", - index); + throw DlAbortEx + (StringFormat("Malformed DHT message. element[%u] is not Data.", + index).str()); } } @@ -118,33 +122,37 @@ static const List* getList(const Dictionary* d, const std::string& key) if(l) { return l; } else { - throw new DlAbortEx("Malformed DHT message. Missing %s", key.c_str()); + throw DlAbortEx + (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str()); } } void DHTMessageFactoryImpl::validateID(const Data* id) const { if(id->getLen() != DHT_ID_LENGTH) { - throw new DlAbortEx("Malformed DHT message. Invalid ID length. Expected:%d, Actual:%d", DHT_ID_LENGTH, id->getLen()); + throw DlAbortEx + (StringFormat("Malformed DHT message. Invalid ID length. Expected:%d, Actual:%d", DHT_ID_LENGTH, id->getLen()).str()); } } void DHTMessageFactoryImpl::validateIDMatch(const unsigned char* expected, const unsigned char* actual) const { if(memcmp(expected, actual, DHT_ID_LENGTH) != 0) { - //throw new DlAbortEx("Different ID received."); + //throw DlAbortEx("Different ID received."); } } void DHTMessageFactoryImpl::validatePort(const Data* i) const { if(!i->isNumber()) { - throw new DlAbortEx("Malformed DHT message. Invalid port=%s", - Util::toHex(i->toString()).c_str()); + throw DlAbortEx + (StringFormat("Malformed DHT message. Invalid port=%s", + Util::toHex(i->toString()).c_str()).str()); } uint32_t port = i->toInt(); if(UINT16_MAX < port) { - throw new DlAbortEx("Malformed DHT message. Invalid port=%u", port); + throw DlAbortEx + (StringFormat("Malformed DHT message. Invalid port=%u", port).str()); } } @@ -157,7 +165,7 @@ SharedHandle DHTMessageFactoryImpl::createQueryMessage(const Diction const Data* y = getData(d, "y"); const Dictionary* a = getDictionary(d, "a"); if(y->toString() != "q") { - throw new DlAbortEx("Malformed DHT message. y != q"); + throw DlAbortEx("Malformed DHT message. y != q"); } const Data* id = getData(getDictionary(d, "a"), "id"); validateID(id); @@ -186,7 +194,8 @@ SharedHandle DHTMessageFactoryImpl::createQueryMessage(const Diction static_cast(port->toInt()), token->toString(), transactionID); } else { - throw new DlAbortEx("Unsupported message type: %s", messageType.c_str()); + throw DlAbortEx + (StringFormat("Unsupported message type: %s", messageType.c_str()).str()); } } @@ -207,10 +216,11 @@ DHTMessageFactoryImpl::createResponseMessage(const std::string& messageType, } else { _logger->debug("e doesn't have 2 elements."); } - throw new DlAbortEx("Received Error DHT message."); + throw DlAbortEx("Received Error DHT message."); } else if(y->toString() != "r") { - throw new DlAbortEx("Malformed DHT message. y != r: y=%s", - Util::urlencode(y->toString()).c_str()); + throw DlAbortEx + (StringFormat("Malformed DHT message. y != r: y=%s", + Util::urlencode(y->toString()).c_str()).str()); } const Dictionary* r = getDictionary(d, "r"); const Data* id = getData(r, "id"); @@ -231,13 +241,14 @@ DHTMessageFactoryImpl::createResponseMessage(const std::string& messageType, if(nodes) { return createGetPeersReplyMessageWithNodes(remoteNode, d, transactionID); } else { - throw new DlAbortEx("Malformed DHT message: missing nodes/values"); + throw DlAbortEx("Malformed DHT message: missing nodes/values"); } } } else if(messageType == "announce_peer") { return createAnnouncePeerReplyMessage(remoteNode, transactionID); } else { - throw new DlAbortEx("Unsupported message type: %s", messageType.c_str()); + throw DlAbortEx + (StringFormat("Unsupported message type: %s", messageType.c_str()).str()); } } @@ -292,7 +303,7 @@ std::deque > DHTMessageFactoryImpl::extractNodes(const unsigned char* src, size_t length) { if(length%26 != 0) { - throw new DlAbortEx("Nodes length is not multiple of 26"); + throw DlAbortEx("Nodes length is not multiple of 26"); } std::deque > nodes; for(size_t offset = 0; offset < length; offset += 26) { diff --git a/src/DHTMessageReceiver.cc b/src/DHTMessageReceiver.cc index fda00568a..ff3a159d1 100644 --- a/src/DHTMessageReceiver.cc +++ b/src/DHTMessageReceiver.cc @@ -110,9 +110,8 @@ SharedHandle DHTMessageReceiver::receiveMessage() callback->onReceived(message); } return message; - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { _logger->info("Exception thrown while receiving DHT message.", e); - delete e; return handleUnknownMessage(data, sizeof(data), remoteAddr, remotePort); } } diff --git a/src/DHTMessageTracker.cc b/src/DHTMessageTracker.cc index b3d911fae..6b2f2e3b5 100644 --- a/src/DHTMessageTracker.cc +++ b/src/DHTMessageTracker.cc @@ -46,6 +46,7 @@ #include "Data.h" #include "DlAbortEx.h" #include "DHTConstants.h" +#include "StringFormat.h" #include namespace aria2 { @@ -72,7 +73,8 @@ DHTMessageTracker::messageArrived(const Dictionary* d, { const Data* tid = dynamic_cast(d->get("t")); if(!tid) { - throw new DlAbortEx("Malformed DHT message. From:%s:%u", ipaddr.c_str(), port); + throw DlAbortEx(StringFormat("Malformed DHT message. From:%s:%u", + ipaddr.c_str(), port).str()); } _logger->debug("Searching tracker entry for TransactionID=%s, Remote=%s:%u", Util::toHex(tid->toString()).c_str(), ipaddr.c_str(), port); @@ -119,9 +121,8 @@ void DHTMessageTracker::handleTimeout() if(!callback.isNull()) { callback->onTimeout(node); } - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { _logger->info("Exception thrown while handling timeouts.", e); - delete e; } } else { ++i; diff --git a/src/DHTPeerAnnounceCommand.cc b/src/DHTPeerAnnounceCommand.cc index 9cba7e4dc..1de3fead2 100644 --- a/src/DHTPeerAnnounceCommand.cc +++ b/src/DHTPeerAnnounceCommand.cc @@ -56,9 +56,8 @@ void DHTPeerAnnounceCommand::process() { try { _peerAnnounceStorage->handleTimeout(); - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { logger->error(EX_EXCEPTION_CAUGHT, e); - delete e; } } diff --git a/src/DHTRoutingTableDeserializer.cc b/src/DHTRoutingTableDeserializer.cc index cc38afa78..db84f7f79 100644 --- a/src/DHTRoutingTableDeserializer.cc +++ b/src/DHTRoutingTableDeserializer.cc @@ -39,6 +39,7 @@ #include "DlAbortEx.h" #include "Logger.h" #include "a2netcompat.h" +#include "StringFormat.h" #include #include #include @@ -81,8 +82,9 @@ void DHTRoutingTableDeserializer::deserialize(std::istream& in) // header in.read(buf, 8); if(memcmp(header, buf, 8) != 0) { - throw new DlAbortEx("Failed to load DHT routing table. cause:%s", - "bad header"); + throw DlAbortEx + (StringFormat("Failed to load DHT routing table. cause:%s", + "bad header").str()); } // time in.read(buf, 4); @@ -150,8 +152,9 @@ void DHTRoutingTableDeserializer::deserialize(std::istream& in) _localNode = localNode; } catch(std::ios::failure const& exception) { _nodes.clear(); - throw new DlAbortEx("Failed to load DHT routing table. cause:%s", - strerror(errno)); + throw DlAbortEx + (StringFormat("Failed to load DHT routing table. cause:%s", + strerror(errno)).str()); } } diff --git a/src/DHTRoutingTableSerializer.cc b/src/DHTRoutingTableSerializer.cc index 65d9f16a9..00f74434f 100644 --- a/src/DHTRoutingTableSerializer.cc +++ b/src/DHTRoutingTableSerializer.cc @@ -39,6 +39,7 @@ #include "PeerMessageUtil.h" #include "Logger.h" #include "a2netcompat.h" +#include "StringFormat.h" #include #include #include @@ -121,8 +122,9 @@ void DHTRoutingTableSerializer::serialize(std::ostream& o) o.write(zero, 4); } } catch(std::ios::failure const& exception) { - throw new DlAbortEx("Failed to save DHT routing table. cause:%s", - strerror(errno)); + throw DlAbortEx + (StringFormat("Failed to save DHT routing table. cause:%s", + strerror(errno)).str()); } } diff --git a/src/DHTSetup.cc b/src/DHTSetup.cc index eaf3ca03c..f4824f0de 100644 --- a/src/DHTSetup.cc +++ b/src/DHTSetup.cc @@ -93,10 +93,9 @@ Commands DHTSetup::setup(DownloadEngine* e, const Option* option) in.exceptions(std::ios::failbit); deserializer.deserialize(in); localNode = deserializer.getLocalNode(); - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { _logger->error("Exception caught while loading DHT routing table from %s", e, dhtFile.c_str()); - delete e; } } if(localNode.isNull()) { @@ -108,7 +107,7 @@ Commands DHTSetup::setup(DownloadEngine* e, const Option* option) IntSequence seq = Util::parseIntRange(option->get(PREF_DHT_LISTEN_PORT)); uint16_t port; if(!connection->bind(port, seq)) { - throw new DlAbortEx("Error occurred while binding port for DHT"); + throw DlAbortEx("Error occurred while binding port for DHT"); } localNode->setPort(port); } @@ -235,9 +234,8 @@ Commands DHTSetup::setup(DownloadEngine* e, const Option* option) _initialized = true; return commands; - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { _logger->error("Exception caught while initializing DHT functionality. DHT is disabled.", e); - delete e; DHTRegistry::clear(); return Commands(); } diff --git a/src/DHTTokenTracker.cc b/src/DHTTokenTracker.cc index cc64cbd97..d92a8af0f 100644 --- a/src/DHTTokenTracker.cc +++ b/src/DHTTokenTracker.cc @@ -38,6 +38,7 @@ #include "DlAbortEx.h" #include "DHTConstants.h" #include "MessageDigestHelper.h" +#include "StringFormat.h" #include namespace aria2 { @@ -62,8 +63,9 @@ std::string DHTTokenTracker::generateToken(const unsigned char* infoHash, { unsigned char src[DHT_ID_LENGTH+6+SECRET_SIZE]; if(!PeerMessageUtil::createcompact(src+DHT_ID_LENGTH, ipaddr, port)) { - throw new DlAbortEx("Token generation failed: ipaddr=%s, port=%u", - ipaddr.c_str(), port); + throw DlAbortEx + (StringFormat("Token generation failed: ipaddr=%s, port=%u", + ipaddr.c_str(), port).str()); } memcpy(src, infoHash, DHT_ID_LENGTH); memcpy(src+DHT_ID_LENGTH+6, secret, SECRET_SIZE); diff --git a/src/DHTTokenUpdateCommand.cc b/src/DHTTokenUpdateCommand.cc index e380347f3..a699f4ca9 100644 --- a/src/DHTTokenUpdateCommand.cc +++ b/src/DHTTokenUpdateCommand.cc @@ -58,9 +58,8 @@ void DHTTokenUpdateCommand::process() { try { _tokenTracker->updateTokenSecret(); - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { logger->error(EX_EXCEPTION_CAUGHT, e); - delete e; } } diff --git a/src/DefaultBtAnnounce.cc b/src/DefaultBtAnnounce.cc index f1cacb871..4ad880626 100644 --- a/src/DefaultBtAnnounce.cc +++ b/src/DefaultBtAnnounce.cc @@ -52,6 +52,7 @@ #include "PeerStorage.h" #include "Peer.h" #include "Option.h" +#include "StringFormat.h" namespace aria2 { @@ -198,12 +199,13 @@ DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse, trackerResponseLength)); const Dictionary* response = dynamic_cast(entry.get()); if(!response) { - throw new DlAbortEx(MSG_NULL_TRACKER_RESPONSE); + throw DlAbortEx(MSG_NULL_TRACKER_RESPONSE); } const Data* failureReasonData = dynamic_cast(response->get("failure reason")); if(failureReasonData) { - throw new DlAbortEx(EX_TRACKER_FAILURE, - failureReasonData->toString().c_str()); + throw DlAbortEx + (StringFormat(EX_TRACKER_FAILURE, + failureReasonData->toString().c_str()).str()); } const Data* warningMessageData = dynamic_cast(response->get("warning message")); if(warningMessageData) { diff --git a/src/DefaultBtContext.cc b/src/DefaultBtContext.cc index 737d5d0b1..3753f4fdb 100644 --- a/src/DefaultBtContext.cc +++ b/src/DefaultBtContext.cc @@ -49,6 +49,7 @@ #include "FileEntry.h" #include "message.h" #include "PeerMessageUtil.h" +#include "StringFormat.h" #include #include #include @@ -134,11 +135,13 @@ void DefaultBtContext::extractFileEntries(const Dictionary* infoDic, if(lengthData) { length += lengthData->toLLInt(); } else { - throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file length"); + throw DlAbortEx + (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file length").str()); } const List* pathList = dynamic_cast(fileDic->get("path")); if(!pathList) { - throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file path list"); + throw DlAbortEx + (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file path list").str()); } const std::deque& paths = pathList->getList(); std::string path; @@ -147,14 +150,16 @@ void DefaultBtContext::extractFileEntries(const Dictionary* infoDic, if(subpath) { path += subpath->toString()+"/"; } else { - throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element"); + throw DlAbortEx + (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element").str()); } } const Data* lastPath = dynamic_cast(paths.back()); if(lastPath) { path += lastPath->toString(); } else { - throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element"); + throw DlAbortEx + (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file path element").str()); } std::deque uris; @@ -175,7 +180,8 @@ void DefaultBtContext::extractFileEntries(const Dictionary* infoDic, if(length) { totalLength = length->toLLInt(); } else { - throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "file length"); + throw DlAbortEx + (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "file length").str()); } FileEntryHandle fileEntry(new FileEntry(name, totalLength, 0, urlList)); fileEntries.push_back(fileEntry); @@ -265,7 +271,8 @@ void DefaultBtContext::loadFromMemory(const unsigned char* content, SharedHandle rootEntry(MetaFileUtil::bdecoding(content, length)); const Dictionary* rootDic = dynamic_cast(rootEntry.get()); if(!rootDic) { - throw new DlAbortEx("torrent file does not contain a root dictionary ."); + throw DlAbortEx + (StringFormat("torrent file does not contain a root dictionary .").str()); } processRootDictionary(rootDic, defaultName); } @@ -274,7 +281,8 @@ void DefaultBtContext::load(const std::string& torrentFile) { SharedHandle rootEntry(MetaFileUtil::parseMetaFile(torrentFile)); const Dictionary* rootDic = dynamic_cast(rootEntry.get()); if(!rootDic) { - throw new DlAbortEx("torrent file does not contain a root dictionary ."); + throw DlAbortEx + (StringFormat("torrent file does not contain a root dictionary .").str()); } processRootDictionary(rootDic, torrentFile); } @@ -284,7 +292,8 @@ void DefaultBtContext::processRootDictionary(const Dictionary* rootDic, const st clear(); const Dictionary* infoDic = dynamic_cast(rootDic->get("info")); if(!infoDic) { - throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "info directory"); + throw DlAbortEx + (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "info directory").str()); } // retrieve infoHash BencodeVisitor v; @@ -296,19 +305,21 @@ void DefaultBtContext::processRootDictionary(const Dictionary* rootDic, const st // calculate the number of pieces const Data* pieceHashData = dynamic_cast(infoDic->get("pieces")); if(!pieceHashData) { - throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "pieces"); + throw DlAbortEx + (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "pieces").str()); } if(pieceHashData->getLen() == 0) { - throw new DlAbortEx("The length of piece hash is 0."); + throw DlAbortEx("The length of piece hash is 0."); } numPieces = pieceHashData->getLen()/PIECE_HASH_LENGTH; if(numPieces == 0) { - throw new DlAbortEx("The number of pieces is 0."); + throw DlAbortEx("The number of pieces is 0."); } // retrieve piece length const Data* pieceLengthData = dynamic_cast(infoDic->get("piece length")); if(!pieceLengthData) { - throw new DlAbortEx(MSG_SOMETHING_MISSING_IN_TORRENT, "piece length"); + throw DlAbortEx + (StringFormat(MSG_SOMETHING_MISSING_IN_TORRENT, "piece length").str()); } pieceLength = pieceLengthData->toInt(); // retrieve piece hashes @@ -327,7 +338,7 @@ void DefaultBtContext::processRootDictionary(const Dictionary* rootDic, const st // retrieve file entries extractFileEntries(infoDic, defaultName, urlList); if((totalLength+pieceLength-1)/pieceLength != numPieces) { - throw new DlAbortEx("Too few/many piece hash."); + throw DlAbortEx("Too few/many piece hash."); } // retrieve announce const Data* announceData = dynamic_cast(rootDic->get("announce")); diff --git a/src/DefaultBtInteractive.cc b/src/DefaultBtInteractive.cc index be73826e6..fce09bc6b 100644 --- a/src/DefaultBtInteractive.cc +++ b/src/DefaultBtInteractive.cc @@ -64,6 +64,7 @@ #include "BtRegistry.h" #include "Logger.h" #include "LogFactory.h" +#include "StringFormat.h" namespace aria2 { @@ -351,7 +352,7 @@ void DefaultBtInteractive::detectMessageFlooding() { if(floodingCheckPoint.elapsed(FLOODING_CHECK_INTERVAL)) { if(floodingStat.getChokeUnchokeCount() >= 2 || floodingStat.getKeepAliveCount() >= 2) { - throw new DlAbortEx(EX_FLOODING_DETECTED); + throw DlAbortEx(EX_FLOODING_DETECTED); } else { floodingStat.reset(); } @@ -368,7 +369,8 @@ void DefaultBtInteractive::checkActiveInteraction() if(!peer->amInterested() && !peer->peerInterested() && inactiveCheckPoint.elapsed(interval)) { // TODO change the message - throw new DlAbortEx("Disconnect peer because we are not interested each other after %u second(s).", interval); + throw DlAbortEx + (StringFormat("Disconnect peer because we are not interested each other after %u second(s).", interval).str()); } } // Since the peers which are *just* connected and do nothing to improve @@ -377,7 +379,8 @@ void DefaultBtInteractive::checkActiveInteraction() { time_t interval = 2*60; if(inactiveCheckPoint.elapsed(interval)) { - throw new DlAbortEx(EX_DROP_INACTIVE_CONNECTION, interval); + throw DlAbortEx + (StringFormat(EX_DROP_INACTIVE_CONNECTION, interval).str()); } } } diff --git a/src/DefaultBtMessageFactory.cc b/src/DefaultBtMessageFactory.cc index e650ca3b2..b35f8df23 100644 --- a/src/DefaultBtMessageFactory.cc +++ b/src/DefaultBtMessageFactory.cc @@ -68,6 +68,7 @@ #include "BtRegistry.h" #include "BtContext.h" #include "PieceStorage.h" +#include "StringFormat.h" namespace aria2 { @@ -194,12 +195,12 @@ DefaultBtMessageFactory::createBtMessage(const unsigned char* data, size_t dataL if(peer->isExtendedMessagingEnabled()) { msg = BtExtendedMessage::create(btContext, peer, data, dataLength); } else { - throw new DlAbortEx("Received extended message from peer during a session with extended messaging disabled."); + throw DlAbortEx("Received extended message from peer during a session with extended messaging disabled."); } break; } default: - throw new DlAbortEx("Invalid message ID. id=%u", id); + throw DlAbortEx(StringFormat("Invalid message ID. id=%u", id).str()); } } setCommonProperty(msg); diff --git a/src/DefaultBtProgressInfoFile.cc b/src/DefaultBtProgressInfoFile.cc index 2e2624499..6cc2dc31e 100644 --- a/src/DefaultBtProgressInfoFile.cc +++ b/src/DefaultBtProgressInfoFile.cc @@ -51,6 +51,7 @@ #include "Util.h" #include "a2io.h" #include "DownloadFailureException.h" +#include "StringFormat.h" #include #include #include @@ -149,12 +150,12 @@ void DefaultBtProgressInfoFile::save() { _logger->info(MSG_SAVED_SEGMENT_FILE); } catch(std::ios::failure const& exception) { // TODO std::ios::failure doesn't give us the reasons of failure... - throw new DlAbortEx(EX_SEGMENT_FILE_WRITE, - _filename.c_str(), strerror(errno)); + throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_WRITE, + _filename.c_str(), strerror(errno)).str()); } if(!File(filenameTemp).renameTo(_filename)) { - throw new DlAbortEx(EX_SEGMENT_FILE_WRITE, - _filename.c_str(), strerror(errno)); + throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_WRITE, + _filename.c_str(), strerror(errno)).str()); } } @@ -169,8 +170,9 @@ void DefaultBtProgressInfoFile::load() unsigned char version[2]; in.read((char*)version, sizeof(version)); if(std::string("0000") != Util::toHex(version, sizeof(version))) { - throw new DlAbortEx("Unsupported ctrl file version: %s", - Util::toHex(version, sizeof(version)).c_str()); + throw DlAbortEx + (StringFormat("Unsupported ctrl file version: %s", + Util::toHex(version, sizeof(version)).c_str()).str()); } unsigned char extension[4]; in.read((char*)extension, sizeof(extension)); @@ -184,7 +186,8 @@ void DefaultBtProgressInfoFile::load() uint32_t infoHashLength; in.read(reinterpret_cast(&infoHashLength), sizeof(infoHashLength)); if((infoHashLength < 0) || ((infoHashLength == 0) && infoHashCheckEnabled)) { - throw new DlAbortEx("Invalid info hash length: %d", infoHashLength); + throw DlAbortEx + (StringFormat("Invalid info hash length: %d", infoHashLength).str()); } if(infoHashLength > 0) { savedInfoHash = new unsigned char[infoHashLength]; @@ -192,9 +195,10 @@ void DefaultBtProgressInfoFile::load() BtContextHandle btContext(dynamic_pointer_cast(_dctx)); if(infoHashCheckEnabled && Util::toHex(savedInfoHash, infoHashLength) != btContext->getInfoHashAsString()) { - throw new DlAbortEx("info hash mismatch. expected: %s, actual: %s", - btContext->getInfoHashAsString().c_str(), - Util::toHex(savedInfoHash, infoHashLength).c_str()); + throw DlAbortEx + (StringFormat("info hash mismatch. expected: %s, actual: %s", + btContext->getInfoHashAsString().c_str(), + Util::toHex(savedInfoHash, infoHashLength).c_str()).str()); } delete [] savedInfoHash; savedInfoHash = 0; @@ -206,9 +210,10 @@ void DefaultBtProgressInfoFile::load() uint64_t totalLength; in.read(reinterpret_cast(&totalLength), sizeof(totalLength)); if(totalLength != _dctx->getTotalLength()) { - throw new DlAbortEx("total length mismatch. expected: %s, actual: %s", - Util::itos(_dctx->getTotalLength()).c_str(), - Util::itos(totalLength).c_str()); + throw DlAbortEx + (StringFormat("total length mismatch. expected: %s, actual: %s", + Util::itos(_dctx->getTotalLength()).c_str(), + Util::itos(totalLength).c_str()).str()); } uint64_t uploadLength; in.read(reinterpret_cast(&uploadLength), sizeof(uploadLength)); @@ -221,9 +226,10 @@ void DefaultBtProgressInfoFile::load() in.read(reinterpret_cast(&bitfieldLength), sizeof(bitfieldLength)); uint32_t expectedBitfieldLength = ((totalLength+pieceLength-1)/pieceLength+7)/8; if(expectedBitfieldLength != bitfieldLength) { - throw new DlAbortEx("bitfield length mismatch. expected: %d, actual: %d", - expectedBitfieldLength, - bitfieldLength); + throw DlAbortEx + (StringFormat("bitfield length mismatch. expected: %d, actual: %d", + expectedBitfieldLength, + bitfieldLength).str()); } savedBitfield = new unsigned char[bitfieldLength]; @@ -242,19 +248,22 @@ void DefaultBtProgressInfoFile::load() uint32_t index; in.read(reinterpret_cast(&index), sizeof(index)); if(!(index < _dctx->getNumPieces())) { - throw new DlAbortEx("piece index out of range: %u", index); + throw DlAbortEx + (StringFormat("piece index out of range: %u", index).str()); } uint32_t length; in.read(reinterpret_cast(&length), sizeof(length)); if(!(length <=_dctx->getPieceLength())) { - throw new DlAbortEx("piece length out of range: %u", length); + throw DlAbortEx + (StringFormat("piece length out of range: %u", length).str()); } PieceHandle piece(new Piece(index, length)); uint32_t bitfieldLength; in.read(reinterpret_cast(&bitfieldLength), sizeof(bitfieldLength)); if(piece->getBitfieldLength() != bitfieldLength) { - throw new DlAbortEx("piece bitfield length mismatch. expected: %u actual: %u", - piece->getBitfieldLength(), bitfieldLength); + throw DlAbortEx + (StringFormat("piece bitfield length mismatch. expected: %u actual: %u", + piece->getBitfieldLength(), bitfieldLength).str()); } savedBitfield = new unsigned char[bitfieldLength]; in.read(reinterpret_cast(savedBitfield), bitfieldLength); @@ -272,7 +281,8 @@ void DefaultBtProgressInfoFile::load() src.setBitfield(savedBitfield, bitfieldLength); if((src.getCompletedLength() || numInFlightPiece) && !_option->getAsBool(PREF_ALLOW_PIECE_LENGTH_CHANGE)) { - throw new DownloadFailureException("WARNING: Detected a change in piece length. You can proceed with --allow-piece-length-change=true, but you may lose some download progress."); + throw DownloadFailureException + ("WARNING: Detected a change in piece length. You can proceed with --allow-piece-length-change=true, but you may lose some download progress."); } BitfieldMan dest(_dctx->getPieceLength(), totalLength); Util::convertBitfield(&dest, &src); @@ -285,8 +295,8 @@ void DefaultBtProgressInfoFile::load() delete [] savedBitfield; delete [] savedInfoHash; // TODO std::ios::failure doesn't give us the reasons of failure... - throw new DlAbortEx(EX_SEGMENT_FILE_READ, - _filename.c_str(), strerror(errno)); + throw DlAbortEx(StringFormat(EX_SEGMENT_FILE_READ, + _filename.c_str(), strerror(errno)).str()); } } diff --git a/src/DefaultExtensionMessageFactory.cc b/src/DefaultExtensionMessageFactory.cc index 4b580fb4c..2295a70ec 100644 --- a/src/DefaultExtensionMessageFactory.cc +++ b/src/DefaultExtensionMessageFactory.cc @@ -41,6 +41,7 @@ #include "LogFactory.h" #include "Logger.h" #include "BtRegistry.h" +#include "StringFormat.h" namespace aria2 { @@ -68,8 +69,9 @@ DefaultExtensionMessageFactory::createMessage(const unsigned char* data, size_t } else { std::string extensionName = getExtensionName(extensionMessageID); if(extensionName.empty()) { - throw new DlAbortEx("No extension registered for extended message ID %u", - extensionMessageID); + throw DlAbortEx + (StringFormat("No extension registered for extended message ID %u", + extensionMessageID).str()); } if(extensionName == "ut_pex") { // uTorrent compatible Peer-Exchange @@ -78,7 +80,9 @@ DefaultExtensionMessageFactory::createMessage(const unsigned char* data, size_t m->setBtContext(_btContext); return m; } else { - throw new DlAbortEx("Unsupported extension message received. extensionMessageID=%u, extensionName=%s", extensionMessageID, extensionName.c_str()); + throw DlAbortEx + (StringFormat("Unsupported extension message received. extensionMessageID=%u, extensionName=%s", + extensionMessageID, extensionName.c_str()).str()); } } } diff --git a/src/DefaultPieceStorage.cc b/src/DefaultPieceStorage.cc index db8a0e424..6bbd97397 100644 --- a/src/DefaultPieceStorage.cc +++ b/src/DefaultPieceStorage.cc @@ -52,6 +52,7 @@ #include "Util.h" #include "a2functional.h" #include "Option.h" +#include "StringFormat.h" #include #include @@ -367,7 +368,7 @@ void DefaultPieceStorage::setFileFilter(const std::deque& filePaths for(std::deque::const_iterator pitr = filePaths.begin(); pitr != filePaths.end(); pitr++) { if(!diskAdaptor->addDownloadEntry(*pitr)) { - throw new DlAbortEx(EX_NO_SUCH_FILE_ENTRY, (*pitr).c_str()); + throw DlAbortEx(StringFormat(EX_NO_SUCH_FILE_ENTRY, (*pitr).c_str()).str()); } FileEntryHandle fileEntry = diskAdaptor->getFileEntryFromPath(*pitr); bitfieldMan->addFilter(fileEntry->getOffset(), fileEntry->getLength()); diff --git a/src/DiskAdaptor.cc b/src/DiskAdaptor.cc index 590c1d48f..fef04d507 100644 --- a/src/DiskAdaptor.cc +++ b/src/DiskAdaptor.cc @@ -38,6 +38,7 @@ #include "Logger.h" #include "message.h" #include "DlAbortEx.h" +#include "StringFormat.h" namespace aria2 { @@ -53,7 +54,7 @@ FileEntryHandle DiskAdaptor::getFileEntryFromPath(const std::string& fileEntryPa return *itr; } } - throw new DlAbortEx(EX_NO_SUCH_FILE_ENTRY, fileEntryPath.c_str()); + throw DlAbortEx(StringFormat(EX_NO_SUCH_FILE_ENTRY, fileEntryPath.c_str()).str()); } bool DiskAdaptor::addDownloadEntry(const std::string& fileEntryPath) diff --git a/src/DlAbortEx.h b/src/DlAbortEx.h index 3168ff777..9f10305ab 100644 --- a/src/DlAbortEx.h +++ b/src/DlAbortEx.h @@ -38,23 +38,18 @@ namespace aria2 { -class DlAbortEx : public RecoverableException { +class DlAbortEx:public RecoverableException { +protected: + virtual SharedHandle copy() const + { + SharedHandle e(new DlAbortEx(*this)); + return e; + } public: - DlAbortEx(Exception* cause = 0):RecoverableException(cause) {} - - DlAbortEx(const char* msg, ...) { - va_list ap; - va_start(ap, msg); - setMsg(msg, ap); - va_end(ap); - } - - DlAbortEx(Exception* cause, const char* msg, ...):RecoverableException(cause) { - va_list ap; - va_start(ap, msg); - setMsg(msg, ap); - va_end(ap); - } + DlAbortEx(const std::string& msg):RecoverableException(msg) {} + DlAbortEx(const std::string& msg, + const Exception& cause):RecoverableException(msg, cause) {} + DlAbortEx(const RecoverableException& e):RecoverableException(e) {} }; } // namespace aria2 diff --git a/src/DlRetryEx.h b/src/DlRetryEx.h index c896ae012..caaf8ea5b 100644 --- a/src/DlRetryEx.h +++ b/src/DlRetryEx.h @@ -38,23 +38,18 @@ namespace aria2 { -class DlRetryEx : public RecoverableException { +class DlRetryEx:public RecoverableException { +protected: + virtual SharedHandle copy() const + { + SharedHandle e(new DlRetryEx(*this)); + return e; + } public: - DlRetryEx(Exception* cause = 0):RecoverableException(cause) {} - - DlRetryEx(const char* msg, ...) { - va_list ap; - va_start(ap, msg); - setMsg(msg, ap); - va_end(ap); - } - - DlRetryEx(Exception* cause, const char* msg, ...):RecoverableException(cause) { - va_list ap; - va_start(ap, msg); - setMsg(msg, ap); - va_end(ap); - } + DlRetryEx(const std::string& msg):RecoverableException(msg) {} + DlRetryEx(const std::string& msg, + const Exception& cause):RecoverableException(msg, cause) {} + DlRetryEx(const DlRetryEx& e):RecoverableException(e) {} }; } // namespace aria2 diff --git a/src/DownloadCommand.cc b/src/DownloadCommand.cc index 4f86c30f7..15d08e3f5 100644 --- a/src/DownloadCommand.cc +++ b/src/DownloadCommand.cc @@ -54,6 +54,7 @@ #include "Socket.h" #include "message.h" #include "prefs.h" +#include "StringFormat.h" #ifdef ENABLE_MESSAGE_DIGEST # include "MessageDigestHelper.h" #endif // ENABLE_MESSAGE_DIGEST @@ -138,7 +139,7 @@ bool DownloadCommand::executeInternal() { peerStat->updateDownloadLength(infbufSize); } if(_requestGroup->getTotalLength() != 0 && bufSize == 0) { - throw new DlRetryEx(EX_GOT_EOF); + throw DlRetryEx(EX_GOT_EOF); } if((!transferDecoder.isNull() && transferDecoder->finished()) || (transferDecoder.isNull() && segment->complete()) @@ -162,10 +163,10 @@ void DownloadCommand::checkLowestDownloadSpeed() const if(peerStat->getDownloadStartTime().elapsed(startupIdleTime)) { unsigned int nowSpeed = peerStat->calculateDownloadSpeed(); if(lowestDownloadSpeedLimit > 0 && nowSpeed <= lowestDownloadSpeedLimit) { - throw new DlAbortEx(EX_TOO_SLOW_DOWNLOAD_SPEED, - nowSpeed, - lowestDownloadSpeedLimit, - req->getHost().c_str()); + throw DlAbortEx(StringFormat(EX_TOO_SLOW_DOWNLOAD_SPEED, + nowSpeed, + lowestDownloadSpeedLimit, + req->getHost().c_str()).str()); } } } @@ -221,7 +222,8 @@ void DownloadCommand::validatePieceHash(const SegmentHandle& segment) actualPieceHash.c_str()); segment->clear(); _requestGroup->getSegmentMan()->cancelSegment(cuid); - throw new DlRetryEx("Invalid checksum index=%d", segment->getIndex()); + throw DlRetryEx + (StringFormat("Invalid checksum index=%d", segment->getIndex()).str()); } } else #endif // ENABLE_MESSAGE_DIGEST diff --git a/src/DownloadFailureException.h b/src/DownloadFailureException.h index 7ddf11fd2..d60231d77 100644 --- a/src/DownloadFailureException.h +++ b/src/DownloadFailureException.h @@ -42,23 +42,18 @@ namespace aria2 { * Throw this exception when a RequestGroup should aborted. * FYI, DlAbortEx is the exception to abort 1 Request. */ -class DownloadFailureException : public RecoverableException { +class DownloadFailureException:public RecoverableException { +protected: + virtual SharedHandle copy() const + { + SharedHandle e(new DownloadFailureException(*this)); + return e; + } public: - DownloadFailureException(Exception* cause = 0):RecoverableException(cause) {} - - DownloadFailureException(const char* msg, ...) { - va_list ap; - va_start(ap, msg); - setMsg(msg, ap); - va_end(ap); - } - - DownloadFailureException(Exception* cause, const char* msg, ...):RecoverableException(cause) { - va_list ap; - va_start(ap, msg); - setMsg(msg, ap); - va_end(ap); - } + DownloadFailureException(const std::string& msg):RecoverableException(msg) {} + DownloadFailureException(const std::string& msg, + const Exception& cause):RecoverableException(msg, cause) {} + DownloadFailureException(const DownloadFailureException& e):RecoverableException(e) {} }; } // namespace aria2 diff --git a/src/Exception.cc b/src/Exception.cc index 47beb3f5a..6830d79f9 100644 --- a/src/Exception.cc +++ b/src/Exception.cc @@ -33,17 +33,38 @@ */ /* copyright --> */ #include "Exception.h" -#include namespace aria2 { -std::ostream& operator<<(std::ostream& o, const Exception& e) +Exception::Exception(const std::string& msg):exception(), _msg(msg) {} + +Exception::Exception(const std::string& msg, + const Exception& cause): + exception(), _msg(msg), _cause(cause.copy()) {} + +Exception::Exception(const Exception& e):_msg(e._msg), _cause(e._cause) +{} + +Exception::~Exception() throw() {} + +const char* Exception::what() const throw() { - o << e.getMsg() << "\n"; - for(Exception* cause = e.getCause(); cause; cause = cause->getCause()) { - o << "Cause: " << cause->getMsg() << "\n"; + return _msg.c_str(); +} + +std::string Exception::stackTrace() const throw() +{ + std::string stackTrace = "Exception: "; + stackTrace += what(); + stackTrace += "\n"; + SharedHandle e = _cause; + while(!e.isNull()) { + stackTrace += " -> "; + stackTrace += e->what(); + stackTrace += "\n"; + e = e->_cause; } - return o; + return stackTrace; } } // namespace aria2 diff --git a/src/Exception.h b/src/Exception.h index c88353add..f788483dd 100644 --- a/src/Exception.h +++ b/src/Exception.h @@ -36,36 +36,32 @@ #define _D_EXCEPTION_H_ #include "common.h" +#include "SharedHandle.h" #include -#include -#include -#include namespace aria2 { -class Exception { +class Exception:public std::exception { private: - std::string msg; + std::string _msg; + + SharedHandle _cause; + protected: - Exception* cause; + virtual SharedHandle copy() const = 0; - void setMsg(const std::string& msgsrc, va_list ap) { - char buf[1024]; - vsnprintf(buf, sizeof(buf), msgsrc.c_str(), ap); - msg = buf; - } public: - Exception(Exception* cause = 0):cause(cause) {} + Exception(const std::string& msg); - virtual ~Exception() { - delete cause; - } + Exception(const std::string& msg, const Exception& cause); - const std::string& getMsg() const { return msg; } + Exception(const Exception& e); - Exception* getCause() const { return cause; } + virtual ~Exception() throw(); - friend std::ostream& operator<<(std::ostream& o, const Exception& e); + virtual const char* what() const throw(); + + std::string stackTrace() const throw(); }; } // namespace aria2 diff --git a/src/ExpatMetalinkProcessor.cc b/src/ExpatMetalinkProcessor.cc index fcfbdf9e7..f7d8a20ed 100644 --- a/src/ExpatMetalinkProcessor.cc +++ b/src/ExpatMetalinkProcessor.cc @@ -125,20 +125,20 @@ ExpatMetalinkProcessor::parseFromBinaryStream(const SharedHandle& break; } if(XML_Parse(parser, (const char*)buf, res, 0) == XML_STATUS_ERROR) { - throw new DlAbortEx(MSG_CANNOT_PARSE_METALINK); + throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); } readOffset += res; } if(XML_Parse(parser, 0, 0, 1) == XML_STATUS_ERROR) { - throw new DlAbortEx(MSG_CANNOT_PARSE_METALINK); + throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); } - } catch(Exception* e) { + } catch(Exception& e) { XML_ParserFree(parser); throw; } XML_ParserFree(parser); if(!_stm->finished()) { - throw new DlAbortEx(MSG_CANNOT_PARSE_METALINK); + throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); } return _stm->getResult(); } diff --git a/src/FatalException.h b/src/FatalException.h index b7e36cbac..a61344005 100644 --- a/src/FatalException.h +++ b/src/FatalException.h @@ -38,23 +38,18 @@ namespace aria2 { -class FatalException : public Exception { +class FatalException:public Exception { +protected: + virtual SharedHandle copy() const + { + SharedHandle e(new FatalException(*this)); + return e; + } public: - FatalException(Exception* cause = 0):Exception(cause) {} - - FatalException(const char* msg, ...):Exception() { - va_list ap; - va_start(ap, msg); - setMsg(msg, ap); - va_end(ap); - } - - FatalException(Exception* cause, const char* msg, ...):Exception(cause) { - va_list ap; - va_start(ap, msg); - setMsg(msg, ap); - va_end(ap); - } + FatalException(const std::string& msg):Exception(msg) {} + FatalException(const std::string& msg, + const Exception& cause):Exception(msg, cause) {} + FatalException(const FatalException& e):Exception(e) {} }; } // namespace aria2 diff --git a/src/FileAllocationCommand.cc b/src/FileAllocationCommand.cc index 79e1d0593..4f2021bf5 100644 --- a/src/FileAllocationCommand.cc +++ b/src/FileAllocationCommand.cc @@ -71,7 +71,7 @@ bool FileAllocationCommand::executeInternal() } } -bool FileAllocationCommand::handleException(Exception* e) +bool FileAllocationCommand::handleException(Exception& e) { _e->_fileAllocationMan->markCurrentFileAllocationEntryDone(); logger->error(MSG_FILE_ALLOCATION_FAILURE, e, cuid); diff --git a/src/FileAllocationCommand.h b/src/FileAllocationCommand.h index 601c923cd..d17cab46d 100644 --- a/src/FileAllocationCommand.h +++ b/src/FileAllocationCommand.h @@ -56,7 +56,7 @@ public: virtual bool executeInternal(); - virtual bool handleException(Exception* e); + virtual bool handleException(Exception& e); }; } // namespace aria2 diff --git a/src/FileMetalinkParserState.cc b/src/FileMetalinkParserState.cc index 99fd84335..0912eb6fb 100644 --- a/src/FileMetalinkParserState.cc +++ b/src/FileMetalinkParserState.cc @@ -65,8 +65,7 @@ void FileMetalinkParserState::beginElement(MetalinkParserStateMachine* stm, } else { try { maxConnections = Util::parseInt((*itr).second); - } catch(RecoverableException* e) { - delete e; + } catch(RecoverableException& e) { maxConnections = -1; } } diff --git a/src/FillRequestGroupCommand.cc b/src/FillRequestGroupCommand.cc index 3ba7b7adb..869496b5f 100644 --- a/src/FillRequestGroupCommand.cc +++ b/src/FillRequestGroupCommand.cc @@ -61,9 +61,8 @@ bool FillRequestGroupCommand::execute() } try { _e->_requestGroupMan->fillRequestGroupFromReserver(_e); - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { logger->error(EX_EXCEPTION_CAUGHT, ex); - delete ex; } if(_e->_requestGroupMan->downloadFinished()) { return true; diff --git a/src/FtpConnection.cc b/src/FtpConnection.cc index 91e0671b0..08a888544 100644 --- a/src/FtpConnection.cc +++ b/src/FtpConnection.cc @@ -184,7 +184,7 @@ bool FtpConnection::bulkReceiveResponse(std::pair& re size_t size = sizeof(buf)-1; socket->readData(buf, size); if(size == 0) { - throw new DlRetryEx(EX_GOT_EOF); + throw DlRetryEx(EX_GOT_EOF); } buf[size] = '\0'; strbuf += buf; @@ -193,7 +193,7 @@ bool FtpConnection::bulkReceiveResponse(std::pair& re if(strbuf.size() >= 4) { status = getStatus(strbuf); if(status == 0) { - throw new DlAbortEx(EX_INVALID_RESPONSE); + throw DlAbortEx(EX_INVALID_RESPONSE); } } else { return false; @@ -262,7 +262,7 @@ unsigned int FtpConnection::receivePasvResponse(std::pair // port number dest.second = 256*p1+p2; } else { - throw new DlRetryEx(EX_INVALID_RESPONSE); + throw DlRetryEx(EX_INVALID_RESPONSE); } } return response.first; diff --git a/src/FtpInitiateConnectionCommand.cc b/src/FtpInitiateConnectionCommand.cc index 9abb0574a..79bb36902 100644 --- a/src/FtpInitiateConnectionCommand.cc +++ b/src/FtpInitiateConnectionCommand.cc @@ -102,7 +102,7 @@ bool FtpInitiateConnectionCommand::executeInternal() { command = new FtpTunnelRequestCommand(cuid, req, _requestGroup, e, socket); } else { // TODO - throw new DlAbortEx("ERROR"); + throw DlAbortEx("ERROR"); } } else { logger->info(MSG_CONNECTING_TO_SERVER, cuid, req->getHost().c_str(), diff --git a/src/FtpNegotiationCommand.cc b/src/FtpNegotiationCommand.cc index 223cdf68b..08b9a2d03 100644 --- a/src/FtpNegotiationCommand.cc +++ b/src/FtpNegotiationCommand.cc @@ -53,6 +53,7 @@ #include "DownloadFailureException.h" #include "ServerHost.h" #include "Socket.h" +#include "StringFormat.h" #include #include #include @@ -115,7 +116,7 @@ bool FtpNegotiationCommand::recvGreeting() { return false; } if(status != 220) { - throw new DlAbortEx(EX_CONNECTION_FAILED); + throw DlAbortEx(EX_CONNECTION_FAILED); } sequence = SEQ_SEND_USER; @@ -140,7 +141,7 @@ bool FtpNegotiationCommand::recvUser() { sequence = SEQ_SEND_PASS; break; default: - throw new DlAbortEx(EX_BAD_STATUS, status); + throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); } return true; } @@ -157,7 +158,7 @@ bool FtpNegotiationCommand::recvPass() { return false; } if(status != 230) { - throw new DlAbortEx(EX_BAD_STATUS, status); + throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); } sequence = SEQ_SEND_TYPE; return true; @@ -175,7 +176,7 @@ bool FtpNegotiationCommand::recvType() { return false; } if(status != 200) { - throw new DlAbortEx(EX_BAD_STATUS, status); + throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); } sequence = SEQ_SEND_CWD; return true; @@ -193,7 +194,7 @@ bool FtpNegotiationCommand::recvCwd() { return false; } if(status != 250) { - throw new DlAbortEx(EX_BAD_STATUS, status); + throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); } sequence = SEQ_SEND_SIZE; return true; @@ -212,10 +213,11 @@ bool FtpNegotiationCommand::recvSize() { return false; } if(status != 213) { - throw new DlAbortEx(EX_BAD_STATUS, status); + throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); } if(size > INT64_MAX) { - throw new DlAbortEx(EX_TOO_LARGE_FILE, Util::uitos(size, true).c_str()); + throw DlAbortEx + (StringFormat(EX_TOO_LARGE_FILE, Util::uitos(size, true).c_str()).str()); } if(_requestGroup->getPieceStorage().isNull()) { SingleFileDownloadContextHandle dctx = @@ -224,8 +226,9 @@ bool FtpNegotiationCommand::recvSize() { dctx->setFilename(Util::urldecode(req->getFile())); _requestGroup->preDownloadProcessing(); if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) { - throw new DownloadFailureException(EX_DUPLICATE_FILE_DOWNLOAD, - _requestGroup->getFilePath().c_str()); + throw DownloadFailureException + (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD, + _requestGroup->getFilePath().c_str()).str()); } _requestGroup->initPieceStorage(); @@ -280,7 +283,7 @@ bool FtpNegotiationCommand::recvPort() { return false; } if(status != 200) { - throw new DlAbortEx(EX_BAD_STATUS, status); + throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); } sequence = SEQ_SEND_REST; return true; @@ -300,7 +303,7 @@ bool FtpNegotiationCommand::recvPasv() { return false; } if(status != 227) { - throw new DlAbortEx(EX_BAD_STATUS, status); + throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); } // make a data connection to the server. logger->info(MSG_CONNECTING_TO_SERVER, cuid, @@ -336,7 +339,7 @@ bool FtpNegotiationCommand::recvRest() { } // TODO if we recieve negative response, then we set _requestGroup->getSegmentMan()->splittable = false, and continue. if(status != 350) { - throw new DlAbortEx(EX_BAD_STATUS, status); + throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); } sequence = SEQ_SEND_RETR; return true; @@ -354,7 +357,7 @@ bool FtpNegotiationCommand::recvRetr() { return false; } if(status != 150 && status != 125) { - throw new DlAbortEx(EX_BAD_STATUS, status); + throw DlAbortEx(StringFormat(EX_BAD_STATUS, status).str()); } if(e->option->getAsBool(PREF_FTP_PASV)) { sequence = SEQ_NEGOTIATION_COMPLETED; diff --git a/src/HandshakeExtensionMessage.cc b/src/HandshakeExtensionMessage.cc index 022b93e6e..0eefc91e6 100644 --- a/src/HandshakeExtensionMessage.cc +++ b/src/HandshakeExtensionMessage.cc @@ -44,6 +44,7 @@ #include "LogFactory.h" #include "Logger.h" #include "message.h" +#include "StringFormat.h" namespace aria2 { @@ -133,8 +134,9 @@ HandshakeExtensionMessageHandle HandshakeExtensionMessage::create(const unsigned char* data, size_t length) { if(length < 1) { - throw new DlAbortEx(MSG_TOO_SMALL_PAYLOAD_SIZE, - EXTENSION_NAME.c_str(), length); + throw DlAbortEx + (StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE, + EXTENSION_NAME.c_str(), length).str()); } HandshakeExtensionMessageHandle msg(new HandshakeExtensionMessage()); msg->_logger->debug("Creating HandshakeExtensionMessage from %s", @@ -142,7 +144,7 @@ HandshakeExtensionMessage::create(const unsigned char* data, size_t length) SharedHandle root(MetaFileUtil::bdecoding(data+1, length-1)); Dictionary* d = dynamic_cast(root.get()); if(d == 0) { - throw new DlAbortEx("Unexpected payload format for extended message handshake"); + throw DlAbortEx("Unexpected payload format for extended message handshake"); } const Data* p = dynamic_cast(d->get("p")); if(p) { diff --git a/src/HelpItemFactory.cc b/src/HelpItemFactory.cc index 5c9eccd23..d56ac1900 100644 --- a/src/HelpItemFactory.cc +++ b/src/HelpItemFactory.cc @@ -461,7 +461,7 @@ TagContainerHandle HelpItemFactory::createHelpItems(const Option* op) { HelpItemHandle item(new HelpItem("help", TEXT_HELP, TAG_BASIC)); item->setAvailableValues - (StringFormat("%s,%s,%s,%s,%s,%s,all", TAG_BASIC, TAG_ADVANCED, TAG_HTTP, TAG_FTP, TAG_METALINK, TAG_BITTORRENT).toString()); + (StringFormat("%s,%s,%s,%s,%s,%s,all", TAG_BASIC, TAG_ADVANCED, TAG_HTTP, TAG_FTP, TAG_METALINK, TAG_BITTORRENT).str()); item->addTag(TAG_BASIC); tc->addItem(item); } diff --git a/src/HttpConnection.cc b/src/HttpConnection.cc index 08b3c01ae..0f1dd0be4 100644 --- a/src/HttpConnection.cc +++ b/src/HttpConnection.cc @@ -112,7 +112,7 @@ void HttpConnection::sendProxyRequest(const HttpRequestHandle& httpRequest) HttpResponseHandle HttpConnection::receiveResponse() { if(outstandingHttpRequests.size() == 0) { - throw new DlAbortEx(EX_NO_HTTP_REQUEST_ENTRY_FOUND); + throw DlAbortEx(EX_NO_HTTP_REQUEST_ENTRY_FOUND); } HttpRequestEntryHandle entry = outstandingHttpRequests.front(); HttpHeaderProcessorHandle proc = entry->getHttpHeaderProcessor(); @@ -121,7 +121,7 @@ HttpResponseHandle HttpConnection::receiveResponse() size_t size = sizeof(buf); socket->peekData(buf, size); if(size == 0) { - throw new DlRetryEx(EX_INVALID_RESPONSE); + throw DlRetryEx(EX_INVALID_RESPONSE); } proc->update(buf, size); if(!proc->eoh()) { diff --git a/src/HttpHeaderProcessor.cc b/src/HttpHeaderProcessor.cc index b16d7f90c..4bfb570ec 100644 --- a/src/HttpHeaderProcessor.cc +++ b/src/HttpHeaderProcessor.cc @@ -61,7 +61,7 @@ void HttpHeaderProcessor::checkHeaderLimit(size_t incomingLength) { strm.seekg(0, std::ios::end); if((size_t)strm.tellg()+incomingLength > _limit) { - throw new DlAbortEx("Too large http header"); + throw DlAbortEx("Too large http header"); } } @@ -100,7 +100,7 @@ SharedHandle HttpHeaderProcessor::getHttpResponseHeader() getline(strm, line); // check HTTP status value if(line.size() <= 12) { - throw new DlRetryEx(EX_NO_STATUS_HEADER); + throw DlRetryEx(EX_NO_STATUS_HEADER); } HttpHeaderHandle httpHeader(new HttpHeader()); httpHeader->setResponseStatus(line.substr(9, 3)); diff --git a/src/HttpInitiateConnectionCommand.cc b/src/HttpInitiateConnectionCommand.cc index 6e904116f..cb4f35d9b 100644 --- a/src/HttpInitiateConnectionCommand.cc +++ b/src/HttpInitiateConnectionCommand.cc @@ -100,7 +100,7 @@ bool HttpInitiateConnectionCommand::executeInternal() { httpConnection, e, socket); } else { // TODO - throw new DlAbortEx("ERROR"); + throw DlAbortEx("ERROR"); } } else { SharedHandle pooledSocket = diff --git a/src/HttpResponse.cc b/src/HttpResponse.cc index 90cc528cd..2b14ea457 100644 --- a/src/HttpResponse.cc +++ b/src/HttpResponse.cc @@ -45,6 +45,7 @@ #include "Util.h" #include "message.h" #include "DlAbortEx.h" +#include "StringFormat.h" #include namespace aria2 { @@ -59,30 +60,35 @@ void HttpResponse::validateResponse() const { const std::string& status = getResponseStatus(); if(status == "401") { - throw new DlAbortEx(EX_AUTH_FAILED); + throw DlAbortEx(EX_AUTH_FAILED); } if(status == "404") { - throw new DlAbortEx(MSG_RESOURCE_NOT_FOUND); + throw DlAbortEx(MSG_RESOURCE_NOT_FOUND); } if(status >= "400") { - throw new DlAbortEx(EX_BAD_STATUS, Util::parseUInt(status)); + throw DlAbortEx + (StringFormat(EX_BAD_STATUS, Util::parseUInt(status)).str()); } if(status >= "300") { if(!httpHeader->defined("Location")) { - throw new DlAbortEx(EX_LOCATION_HEADER_REQUIRED, Util::parseUInt(status)); + throw DlAbortEx + (StringFormat(EX_LOCATION_HEADER_REQUIRED, + Util::parseUInt(status)).str()); } } else { if(!httpHeader->defined("Transfer-Encoding")) { // compare the received range against the requested range RangeHandle responseRange = httpHeader->getRange(); if(!httpRequest->isRangeSatisfied(responseRange)) { - throw new DlAbortEx(EX_INVALID_RANGE_HEADER, - Util::itos(httpRequest->getStartByte(), true).c_str(), - Util::itos(httpRequest->getEndByte(), true).c_str(), - Util::uitos(httpRequest->getEntityLength(), true).c_str(), - Util::itos(responseRange->getStartByte(), true).c_str(), - Util::itos(responseRange->getEndByte(), true).c_str(), - Util::uitos(responseRange->getEntityLength(), true).c_str()); + throw DlAbortEx + (StringFormat(EX_INVALID_RANGE_HEADER, + Util::itos(httpRequest->getStartByte(), true).c_str(), + Util::itos(httpRequest->getEndByte(), true).c_str(), + Util::uitos(httpRequest->getEntityLength(), true).c_str(), + Util::itos(responseRange->getStartByte(), true).c_str(), + Util::itos(responseRange->getEndByte(), true).c_str(), + Util::uitos(responseRange->getEntityLength(), true).c_str() + ).str()); } } } diff --git a/src/HttpResponseCommand.cc b/src/HttpResponseCommand.cc index 97ab2a79c..d19acd95e 100644 --- a/src/HttpResponseCommand.cc +++ b/src/HttpResponseCommand.cc @@ -59,6 +59,7 @@ #include "Socket.h" #include "message.h" #include "prefs.h" +#include "StringFormat.h" namespace aria2 { @@ -105,8 +106,9 @@ bool HttpResponseCommand::executeInternal() dctx->setContentType(httpResponse->getContentType()); _requestGroup->preDownloadProcessing(); if(e->_requestGroupMan->isSameFileBeingDownloaded(_requestGroup)) { - throw new DownloadFailureException(EX_DUPLICATE_FILE_DOWNLOAD, - _requestGroup->getFilePath().c_str()); + throw DownloadFailureException + (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD, + _requestGroup->getFilePath().c_str()).str()); } if(totalLength == 0 || httpResponse->isTransferEncodingSpecified()) { // we ignore content-length when transfer-encoding is set @@ -157,7 +159,7 @@ bool HttpResponseCommand::handleDefaultEncoding(const HttpResponseHandle& httpRe _requestGroup->getSegmentMan()->cancelSegment(cuid); } prepareForNextAction(command); - } catch(Exception* e) { + } catch(Exception& e) { delete command; throw; } @@ -183,8 +185,9 @@ HttpDownloadCommand* HttpResponseCommand::createHttpDownloadCommand(const HttpRe if(httpResponse->isTransferEncodingSpecified()) { enc = httpResponse->getTransferDecoder(); if(enc.isNull()) { - throw new DlAbortEx(EX_TRANSFER_ENCODING_NOT_SUPPORTED, - httpResponse->getTransferEncoding().c_str()); + throw DlAbortEx + (StringFormat(EX_TRANSFER_ENCODING_NOT_SUPPORTED, + httpResponse->getTransferEncoding().c_str()).str()); } enc->init(); } diff --git a/src/InitiateConnectionCommandFactory.cc b/src/InitiateConnectionCommandFactory.cc index e38baf700..ca3a7a755 100644 --- a/src/InitiateConnectionCommandFactory.cc +++ b/src/InitiateConnectionCommandFactory.cc @@ -39,6 +39,7 @@ #include "RequestGroup.h" #include "DownloadEngine.h" #include "DlAbortEx.h" +#include "StringFormat.h" namespace aria2 { @@ -55,7 +56,9 @@ InitiateConnectionCommandFactory::createInitiateConnectionCommand(int32_t cuid, return new FtpInitiateConnectionCommand(cuid, req, requestGroup, e); } else { // these protocols are not supported yet - throw new DlAbortEx("%s is not supported yet.", req->getProtocol().c_str()); + throw DlAbortEx + (StringFormat("%s is not supported yet.", + req->getProtocol().c_str()).str()); } } diff --git a/src/InitiatorMSEHandshakeCommand.cc b/src/InitiatorMSEHandshakeCommand.cc index 913f2d2d7..03c570ee8 100644 --- a/src/InitiatorMSEHandshakeCommand.cc +++ b/src/InitiatorMSEHandshakeCommand.cc @@ -167,7 +167,7 @@ bool InitiatorMSEHandshakeCommand::prepareForNextPeer(time_t wait) } } -void InitiatorMSEHandshakeCommand::onAbort(Exception* ex) +void InitiatorMSEHandshakeCommand::onAbort() { if(e->option->getAsBool(PREF_BT_REQUIRE_CRYPTO)) { peerStorage->returnPeer(peer); diff --git a/src/InitiatorMSEHandshakeCommand.h b/src/InitiatorMSEHandshakeCommand.h index 366e615d4..0c1b4f8a8 100644 --- a/src/InitiatorMSEHandshakeCommand.h +++ b/src/InitiatorMSEHandshakeCommand.h @@ -61,7 +61,7 @@ private: protected: virtual bool executeInternal(); virtual bool prepareForNextPeer(time_t wait); - virtual void onAbort(Exception* ex); + virtual void onAbort(); virtual bool exitBeforeExecute(); public: InitiatorMSEHandshakeCommand(int32_t cuid, diff --git a/src/IteratableChunkChecksumValidator.cc b/src/IteratableChunkChecksumValidator.cc index 3859644c7..518d3c2c9 100644 --- a/src/IteratableChunkChecksumValidator.cc +++ b/src/IteratableChunkChecksumValidator.cc @@ -45,6 +45,7 @@ #include "LogFactory.h" #include "Logger.h" #include "messageDigest.h" +#include "StringFormat.h" #include namespace aria2 { @@ -74,9 +75,8 @@ void IteratableChunkChecksumValidator::validateChunk() std::string actualChecksum; try { actualChecksum = calculateActualChecksum(); - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { _logger->debug("Caught exception while validating piece index=%d. Some part of file may be missing. Continue operation.", ex, _currentIndex); - delete ex; _bitfield->unsetBit(_currentIndex); _currentIndex++; return; @@ -143,8 +143,9 @@ std::string IteratableChunkChecksumValidator::digest(off_t offset, size_t length size_t r = _pieceStorage->getDiskAdaptor()->readData(_buffer, BUFSIZE, curoffset); if(r == 0) { - throw new DlAbortEx(EX_FILE_READ, _dctx->getActualBasePath().c_str(), - strerror(errno)); + throw DlAbortEx + (StringFormat(EX_FILE_READ, _dctx->getActualBasePath().c_str(), + strerror(errno)).str()); } size_t wlength; if(max < curoffset+r) { diff --git a/src/LibgcryptARC4Context.h b/src/LibgcryptARC4Context.h index db6b2e341..744a24dcf 100644 --- a/src/LibgcryptARC4Context.h +++ b/src/LibgcryptARC4Context.h @@ -37,6 +37,7 @@ #include "common.h" #include "DlAbortEx.h" +#include "StringFormat.h" #include namespace aria2 { @@ -47,8 +48,9 @@ private: void handleError(gcry_error_t err) const { - throw new DlAbortEx("Exception in libgcrypt routine(ARC4Context class): %s", - gcry_strerror(err)); + throw DlAbortEx + (StringFormat("Exception in libgcrypt routine(ARC4Context class): %s", + gcry_strerror(err)).str()); } public: LibgcryptARC4Context():_cipherCtx(0) {} diff --git a/src/LibgcryptARC4Decryptor.h b/src/LibgcryptARC4Decryptor.h index 94745f8a4..c85f3f31f 100644 --- a/src/LibgcryptARC4Decryptor.h +++ b/src/LibgcryptARC4Decryptor.h @@ -38,6 +38,7 @@ #include "common.h" #include "DlAbortEx.h" #include "LibgcryptARC4Context.h" +#include "StringFormat.h" #include namespace aria2 { @@ -48,8 +49,9 @@ private: void handleError(gcry_error_t err) const { - throw new DlAbortEx("Exception in libgcrypt routine(ARC4Decryptor class): %s", - gcry_strerror(err)); + throw DlAbortEx + (StringFormat("Exception in libgcrypt routine(ARC4Decryptor class): %s", + gcry_strerror(err)).str()); } public: ARC4Decryptor() {} diff --git a/src/LibgcryptARC4Encryptor.h b/src/LibgcryptARC4Encryptor.h index 63343aa5a..096b489b4 100644 --- a/src/LibgcryptARC4Encryptor.h +++ b/src/LibgcryptARC4Encryptor.h @@ -38,6 +38,7 @@ #include "common.h" #include "DlAbortEx.h" #include "LibgcryptARC4Context.h" +#include "StringFormat.h" #include namespace aria2 { @@ -48,8 +49,9 @@ private: void handleError(gcry_error_t err) const { - throw new DlAbortEx("Exception in libgcrypt routine(ARC4Encryptor class): %s", - gcry_strerror(err)); + throw DlAbortEx + (StringFormat("Exception in libgcrypt routine(ARC4Encryptor class): %s", + gcry_strerror(err)).str()); } public: ARC4Encryptor() {} diff --git a/src/LibgcryptDHKeyExchange.h b/src/LibgcryptDHKeyExchange.h index 4e9cad447..3912e8682 100644 --- a/src/LibgcryptDHKeyExchange.h +++ b/src/LibgcryptDHKeyExchange.h @@ -37,6 +37,7 @@ #include "common.h" #include "DlAbortEx.h" +#include "StringFormat.h" #include namespace aria2 { @@ -55,8 +56,9 @@ private: void handleError(gcry_error_t err) const { - throw new DlAbortEx("Exception in libgcrypt routine(DHKeyExchange class): %s", - gcry_strerror(err)); + throw DlAbortEx + (StringFormat("Exception in libgcrypt routine(DHKeyExchange class): %s", + gcry_strerror(err)).str()); } public: DHKeyExchange(): @@ -110,8 +112,9 @@ public: size_t getPublicKey(unsigned char* out, size_t outLength) const { if(outLength < _keyLength) { - throw new DlAbortEx("Insufficient buffer for public key. expect:%u, actual:%u", - _keyLength, outLength); + throw DlAbortEx + (StringFormat("Insufficient buffer for public key. expect:%u, actual:%u", + _keyLength, outLength).str()); } memset(out, 0, outLength); size_t publicKeyBytes = (gcry_mpi_get_nbits(_publicKey)+7)/8; @@ -135,8 +138,9 @@ public: size_t peerPublicKeyLength) const { if(outLength < _keyLength) { - throw new DlAbortEx("Insufficient buffer for secret. expect:%u, actual:%u", - _keyLength, outLength); + throw DlAbortEx + (StringFormat("Insufficient buffer for secret. expect:%u, actual:%u", + _keyLength, outLength).str()); } gcry_mpi_t peerPublicKey; { diff --git a/src/LibsslARC4Context.h b/src/LibsslARC4Context.h index 27200c19c..31b3463fc 100644 --- a/src/LibsslARC4Context.h +++ b/src/LibsslARC4Context.h @@ -37,6 +37,7 @@ #include "common.h" #include "DlAbortEx.h" +#include "StringFormat.h" #include #include @@ -48,8 +49,9 @@ private: void handleError() const { - throw new DlAbortEx("Exception in libssl routine(ARC4Context class): %s", - ERR_error_string(ERR_get_error(), 0)); + throw DlAbortEx + (StringFormat("Exception in libssl routine(ARC4Context class): %s", + ERR_error_string(ERR_get_error(), 0)).str()); } public: LibsslARC4Context():_cipherCtx(0) {} diff --git a/src/LibsslARC4Decryptor.h b/src/LibsslARC4Decryptor.h index e51808c0d..2079a7c10 100644 --- a/src/LibsslARC4Decryptor.h +++ b/src/LibsslARC4Decryptor.h @@ -38,6 +38,7 @@ #include "common.h" #include "DlAbortEx.h" #include "LibsslARC4Context.h" +#include "StringFormat.h" #include #include @@ -49,8 +50,9 @@ private: void handleError() const { - throw new DlAbortEx("Exception in libssl routine(ARC4Decryptor class): %s", - ERR_error_string(ERR_get_error(), 0)); + throw DlAbortEx + (StringFormat("Exception in libssl routine(ARC4Decryptor class): %s", + ERR_error_string(ERR_get_error(), 0)).str()); } public: ARC4Decryptor() {} diff --git a/src/LibsslARC4Encryptor.h b/src/LibsslARC4Encryptor.h index 49b8d5dca..9b47a2255 100644 --- a/src/LibsslARC4Encryptor.h +++ b/src/LibsslARC4Encryptor.h @@ -38,6 +38,7 @@ #include "common.h" #include "DlAbortEx.h" #include "LibsslARC4Context.h" +#include "StringFormat.h" #include #include @@ -49,8 +50,9 @@ private: void handleError() const { - throw new DlAbortEx("Exception in libssl routine(ARC4Encryptor class): %s", - ERR_error_string(ERR_get_error(), 0)); + throw DlAbortEx + (StringFormat("Exception in libssl routine(ARC4Encryptor class): %s", + ERR_error_string(ERR_get_error(), 0)).str()); } public: ARC4Encryptor() {} diff --git a/src/LibsslDHKeyExchange.h b/src/LibsslDHKeyExchange.h index 76f20ec3c..bab473d3c 100644 --- a/src/LibsslDHKeyExchange.h +++ b/src/LibsslDHKeyExchange.h @@ -37,6 +37,7 @@ #include "common.h" #include "DlAbortEx.h" +#include "StringFormat.h" #include #include #include @@ -60,8 +61,9 @@ private: void handleError(const std::string& funName) const { - throw new DlAbortEx("Exception in libssl routine %s(DHKeyExchange class): %s", - funName.c_str(), ERR_error_string(ERR_get_error(), 0)); + throw DlAbortEx + (StringFormat("Exception in libssl routine %s(DHKeyExchange class): %s", + funName.c_str(), ERR_error_string(ERR_get_error(), 0)).str()); } public: DHKeyExchange():_bnCtx(0), @@ -120,15 +122,17 @@ public: size_t getPublicKey(unsigned char* out, size_t outLength) const { if(outLength < _keyLength) { - throw new DlAbortEx("Insufficient buffer for public key. expect:%u, actual:%u", - _keyLength, outLength); + throw DlAbortEx + (StringFormat("Insufficient buffer for public key. expect:%u, actual:%u", + _keyLength, outLength).str()); } memset(out, 0, outLength); size_t publicKeyBytes = BN_num_bytes(_publicKey); size_t offset = _keyLength-publicKeyBytes; size_t nwritten = BN_bn2bin(_publicKey, out+offset); if(nwritten != publicKeyBytes) { - throw new DlAbortEx("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, publicKeyBytes); + throw DlAbortEx + (StringFormat("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, publicKeyBytes).str()); } return nwritten; } @@ -145,8 +149,9 @@ public: size_t peerPublicKeyLength) const { if(outLength < _keyLength) { - throw new DlAbortEx("Insufficient buffer for secret. expect:%u, actual:%u", - _keyLength, outLength); + throw DlAbortEx + (StringFormat("Insufficient buffer for secret. expect:%u, actual:%u", + _keyLength, outLength).str()); } @@ -165,7 +170,8 @@ public: size_t nwritten = BN_bn2bin(secret, out+offset); BN_free(secret); if(nwritten != secretBytes) { - throw new DlAbortEx("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, secretBytes); + throw DlAbortEx + (StringFormat("BN_bn2bin in DHKeyExchange::getPublicKey, %u bytes written, but %u bytes expected.", nwritten, secretBytes).str()); } return nwritten; } diff --git a/src/Logger.h b/src/Logger.h index 64a0e978e..91797457a 100644 --- a/src/Logger.h +++ b/src/Logger.h @@ -45,15 +45,15 @@ class Logger { public: virtual ~Logger() {} virtual void debug(const char* msg, ...) = 0; - virtual void debug(const char* msg, Exception* ex, ...) = 0; + virtual void debug(const char* msg, Exception& ex, ...) = 0; virtual void info(const char* msg, ...) = 0; - virtual void info(const char* msg, Exception* ex, ...) = 0; + virtual void info(const char* msg, Exception& ex, ...) = 0; virtual void notice(const char* msg, ...) = 0; - virtual void notice(const char* msg, Exception* ex, ...) = 0; + virtual void notice(const char* msg, Exception& ex, ...) = 0; virtual void warn(const char* msg, ...) = 0; - virtual void warn(const char* msg, Exception* ex, ...) = 0; + virtual void warn(const char* msg, Exception& ex, ...) = 0; virtual void error(const char* msg, ...) = 0; - virtual void error(const char* msg, Exception* ex, ...) = 0; + virtual void error(const char* msg, Exception& ex, ...) = 0; enum LEVEL { DEBUG = 1 << 0, diff --git a/src/MSEHandshake.cc b/src/MSEHandshake.cc index 0e80db796..2d1425500 100644 --- a/src/MSEHandshake.cc +++ b/src/MSEHandshake.cc @@ -50,6 +50,7 @@ #include "BtContext.h" #include "prefs.h" #include "Option.h" +#include "StringFormat.h" #include #include @@ -92,7 +93,7 @@ MSEHandshake::HANDSHAKE_TYPE MSEHandshake::identifyHandshakeType() size_t r = 20-_rbufLength; _socket->readData(_rbuf+_rbufLength, r); if(r == 0) { - throw new DlAbortEx(EX_EOF_FROM_PEER); + throw DlAbortEx(EX_EOF_FROM_PEER); } _rbufLength += r; if(_rbufLength < 20) { @@ -285,7 +286,7 @@ bool MSEHandshake::findInitiatorVCMarker() } _socket->peekData(_rbuf+_rbufLength, r); if(r == 0) { - throw new DlAbortEx(EX_EOF_FROM_PEER); + throw DlAbortEx(EX_EOF_FROM_PEER); } // find vc { @@ -293,7 +294,7 @@ bool MSEHandshake::findInitiatorVCMarker() std::string vc(&_initiatorVCMarker[0], &_initiatorVCMarker[VC_LENGTH]); if((_markerIndex = buf.find(vc)) == std::string::npos) { if(616-KEY_LENGTH <= _rbufLength+r) { - throw new DlAbortEx("Failed to find VC marker."); + throw DlAbortEx("Failed to find VC marker."); } else { _socket->readData(_rbuf+_rbufLength, r); _rbufLength += r; @@ -335,7 +336,8 @@ bool MSEHandshake::receiveInitiatorCryptoSelectAndPadDLength() _negotiatedCryptoType = CRYPTO_ARC4; } if(_negotiatedCryptoType == CRYPTO_NONE) { - throw new DlAbortEx("CUID#%d - No supported crypto type selected.", _cuid); + throw DlAbortEx + (StringFormat("CUID#%d - No supported crypto type selected.", _cuid).str()); } } // padD length @@ -371,7 +373,7 @@ bool MSEHandshake::findReceiverHashMarker() } _socket->peekData(_rbuf+_rbufLength, r); if(r == 0) { - throw new DlAbortEx(EX_EOF_FROM_PEER); + throw DlAbortEx(EX_EOF_FROM_PEER); } // find hash('req1', S), S is _secret. { @@ -381,7 +383,7 @@ bool MSEHandshake::findReceiverHashMarker() std::string req1(&md[0], &md[sizeof(md)]); if((_markerIndex = buf.find(req1)) == std::string::npos) { if(628-KEY_LENGTH <= _rbufLength+r) { - throw new DlAbortEx("Failed to find hash marker."); + throw DlAbortEx("Failed to find hash marker."); } else { _socket->readData(_rbuf+_rbufLength, r); _rbufLength += r; @@ -423,7 +425,7 @@ bool MSEHandshake::receiveReceiverHashAndPadCLength() } } if(btContext.isNull()) { - throw new DlAbortEx("Unknown info hash."); + throw DlAbortEx("Unknown info hash."); } initCipher(btContext->getInfoHash()); @@ -447,7 +449,8 @@ bool MSEHandshake::receiveReceiverHashAndPadCLength() _negotiatedCryptoType = CRYPTO_ARC4; } if(_negotiatedCryptoType == CRYPTO_NONE) { - throw new DlAbortEx("CUID#%d - No supported crypto type provided.", _cuid); + throw DlAbortEx + (StringFormat("CUID#%d - No supported crypto type provided.", _cuid).str()); } } // decrypt PadC length @@ -518,7 +521,8 @@ uint16_t MSEHandshake::verifyPadLength(const unsigned char* padlenbuf, const std uint16_t padLength = decodeLength16(padlenbuf); _logger->debug("CUID#%d - len(%s)=%u", _cuid, padName.c_str(), padLength); if(padLength > 512) { - throw new DlAbortEx("Too large %s length: %u", padName.c_str(), padLength); + throw DlAbortEx + (StringFormat("Too large %s length: %u", padName.c_str(), padLength).str()); } return padLength; } @@ -529,7 +533,8 @@ void MSEHandshake::verifyVC(const unsigned char* vcbuf) unsigned char vc[VC_LENGTH]; _decryptor->decrypt(vc, sizeof(vc), vcbuf, sizeof(vc)); if(memcmp(VC, vc, sizeof(VC)) != 0) { - throw new DlAbortEx("Invalid VC: %s", Util::toHex(vc, VC_LENGTH).c_str()); + throw DlAbortEx + (StringFormat("Invalid VC: %s", Util::toHex(vc, VC_LENGTH).c_str()).str()); } } @@ -539,7 +544,7 @@ void MSEHandshake::verifyReq1Hash(const unsigned char* req1buf) unsigned char md[20]; createReq1Hash(md); if(memcmp(md, req1buf, sizeof(md)) != 0) { - throw new DlAbortEx("Invalid req1 hash found."); + throw DlAbortEx("Invalid req1 hash found."); } } @@ -552,7 +557,7 @@ size_t MSEHandshake::receiveNBytes(size_t bytes) } _socket->readData(_rbuf+_rbufLength, r); if(r == 0) { - throw new DlAbortEx(EX_EOF_FROM_PEER); + throw DlAbortEx(EX_EOF_FROM_PEER); } _rbufLength += r; } diff --git a/src/MessageDigestHelper.cc b/src/MessageDigestHelper.cc index 6b82cb44b..5d23d3d19 100644 --- a/src/MessageDigestHelper.cc +++ b/src/MessageDigestHelper.cc @@ -38,6 +38,7 @@ #include "message.h" #include "DefaultDiskWriter.h" #include "Util.h" +#include "StringFormat.h" #include namespace aria2 { @@ -88,7 +89,8 @@ std::string MessageDigestHelper::digest(MessageDigestContext* ctx, for(uint64_t i = 0; i < iteration; ++i) { ssize_t readLength = bs->readData(BUF, BUFSIZE, offset); if((size_t)readLength != BUFSIZE) { - throw new DlAbortEx(EX_FILE_READ, "n/a", strerror(errno)); + throw DlAbortEx + (StringFormat(EX_FILE_READ, "n/a", strerror(errno)).str()); } ctx->digestUpdate(BUF, readLength); offset += readLength; @@ -96,7 +98,8 @@ std::string MessageDigestHelper::digest(MessageDigestContext* ctx, if(tail) { ssize_t readLength = bs->readData(BUF, tail, offset); if((size_t)readLength != tail) { - throw new DlAbortEx(EX_FILE_READ, "n/a", strerror(errno)); + throw DlAbortEx + (StringFormat(EX_FILE_READ, "n/a", strerror(errno)).str()); } ctx->digestUpdate(BUF, readLength); } @@ -125,7 +128,9 @@ void MessageDigestHelper::digest(unsigned char* md, size_t mdLength, const std::string& algo, const void* data, size_t length) { if(mdLength < MessageDigestContext::digestLength(algo)) { - throw new DlAbortEx("Insufficient space for storing message digest: %d required, but only %d is allocated", MessageDigestContext::digestLength(algo), mdLength); + throw DlAbortEx + (StringFormat("Insufficient space for storing message digest: %d required, but only %d is allocated", + MessageDigestContext::digestLength(algo), mdLength).str()); } MessageDigestContext ctx; ctx.trySetAlgo(algo); diff --git a/src/MetaFileUtil.cc b/src/MetaFileUtil.cc index 5133d33d6..27074535b 100644 --- a/src/MetaFileUtil.cc +++ b/src/MetaFileUtil.cc @@ -51,18 +51,18 @@ MetaEntry* MetaFileUtil::parseMetaFile(const std::string& file) { FILE* fp = fopen(file.c_str(), "r+b"); try { if(!fp) { - throw new DlAbortEx("cannot open metainfo file"); + throw DlAbortEx("cannot open metainfo file"); } if(fread(buf, len, 1, fp) != 1) { fclose(fp); - throw new DlAbortEx("cannot read metainfo"); + throw DlAbortEx("cannot read metainfo"); } fclose(fp); fp = 0; MetaEntry* entry = bdecoding(buf, len); delete [] buf; return entry; - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { delete [] buf; if(fp) { fclose(fp); @@ -82,7 +82,7 @@ MetaEntry* MetaFileUtil::bdecodingR(const unsigned char** pp, const unsigned char* end) { if(*pp >= end) { - throw new DlAbortEx("Malformed metainfo"); + throw DlAbortEx("Malformed metainfo"); } MetaEntry* e; switch(**pp) { @@ -108,7 +108,7 @@ Dictionary* MetaFileUtil::parseDictionaryTree(const unsigned char** pp, const unsigned char* end) { if(*pp >= end) { - throw new DlAbortEx("Malformed metainfo"); + throw DlAbortEx("Malformed metainfo"); } Dictionary* dic = new Dictionary(); try { @@ -122,7 +122,7 @@ MetaFileUtil::parseDictionaryTree(const unsigned char** pp, const unsigned char* dic->put(name, e); } return dic; - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { delete dic; throw; } @@ -132,7 +132,7 @@ List* MetaFileUtil::parseListTree(const unsigned char** pp, const unsigned char* end) { if(*pp >= end) { - throw new DlAbortEx("Malformed metainfo"); + throw DlAbortEx("Malformed metainfo"); } List* lis = new List(); try { @@ -145,7 +145,7 @@ MetaFileUtil::parseListTree(const unsigned char** pp, const unsigned char* end) lis->add(e); } return lis; - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { delete lis; throw; } @@ -155,12 +155,12 @@ Data* MetaFileUtil::decodeInt(const unsigned char** pp, const unsigned char* end) { if(*pp >= end) { - throw new DlAbortEx(EX_MALFORMED_META_INFO); + throw DlAbortEx(EX_MALFORMED_META_INFO); } unsigned char* endTerm = reinterpret_cast(memchr(*pp, 'e', end-*pp)); // TODO if endTerm is null if(!endTerm) { - throw new DlAbortEx(EX_MALFORMED_META_INFO); + throw DlAbortEx(EX_MALFORMED_META_INFO); } size_t numSize = endTerm-*pp; @@ -173,12 +173,12 @@ Data* MetaFileUtil::decodeWord(const unsigned char** pp, const unsigned char* end) { if(*pp >= end) { - throw new DlAbortEx("Malformed metainfo"); + throw DlAbortEx("Malformed metainfo"); } unsigned char* delim = reinterpret_cast(memchr(*pp, ':', end-*pp)); // TODO if delim is null if(delim == *pp || !delim) { - throw new DlAbortEx(EX_MALFORMED_META_INFO); + throw DlAbortEx(EX_MALFORMED_META_INFO); } size_t numSize = delim-*pp; unsigned char* temp = new unsigned char[numSize+1]; @@ -189,12 +189,12 @@ MetaFileUtil::decodeWord(const unsigned char** pp, const unsigned char* end) &endptr, 10); if(*endptr != '\0') { delete [] temp; - throw new DlAbortEx(EX_MALFORMED_META_INFO); + throw DlAbortEx(EX_MALFORMED_META_INFO); } delete [] temp; if(delim+1+size > end) { - throw new DlAbortEx(EX_MALFORMED_META_INFO); + throw DlAbortEx(EX_MALFORMED_META_INFO); } Data* data = new Data(delim+1, size); diff --git a/src/MetalinkHelper.cc b/src/MetalinkHelper.cc index 8374b855f..79c586046 100644 --- a/src/MetalinkHelper.cc +++ b/src/MetalinkHelper.cc @@ -72,7 +72,7 @@ std::deque > MetalinkHelper::query(const SharedHandle& metalinker, const Option* option) { if(metalinker->entries.empty()) { - throw new DlAbortEx("No file entry found. Probably, the metalink file is not configured properly or broken."); + throw DlAbortEx("No file entry found. Probably, the metalink file is not configured properly or broken."); } std::deque > entries = metalinker->queryEntry(option->get(PREF_METALINK_VERSION), diff --git a/src/MetalinkPostDownloadHandler.cc b/src/MetalinkPostDownloadHandler.cc index c6da129e8..bd2cebd4d 100644 --- a/src/MetalinkPostDownloadHandler.cc +++ b/src/MetalinkPostDownloadHandler.cc @@ -66,7 +66,7 @@ MetalinkPostDownloadHandler::getNextRequestGroups(RequestGroup* requestGroup) std::deque > rgs = Metalink2RequestGroup(op).generate(diskAdaptor); diskAdaptor->closeFile(); return rgs; - } catch(Exception* e) { + } catch(Exception& e) { diskAdaptor->closeFile(); throw; } diff --git a/src/MultiDiskAdaptor.cc b/src/MultiDiskAdaptor.cc index f0548469f..e9586a6f2 100644 --- a/src/MultiDiskAdaptor.cc +++ b/src/MultiDiskAdaptor.cc @@ -41,6 +41,7 @@ #include "DefaultDiskWriterFactory.h" #include "DlAbortEx.h" #include "File.h" +#include "StringFormat.h" namespace aria2 { @@ -201,7 +202,9 @@ void MultiDiskAdaptor::writeData(const unsigned char* data, size_t len, } } if(!writing) { - throw new DlAbortEx(EX_FILE_OFFSET_OUT_OF_RANGE, Util::itos(offset, true).c_str()); + throw DlAbortEx + (StringFormat(EX_FILE_OFFSET_OUT_OF_RANGE, + Util::itos(offset, true).c_str()).str()); } } @@ -244,7 +247,9 @@ ssize_t MultiDiskAdaptor::readData(unsigned char* data, size_t len, off_t offset } } if(!reading) { - throw new DlAbortEx(EX_FILE_OFFSET_OUT_OF_RANGE, Util::itos(offset, true).c_str()); + throw DlAbortEx + (StringFormat(EX_FILE_OFFSET_OUT_OF_RANGE, + Util::itos(offset, true).c_str()).str()); } return totalReadLength; } diff --git a/src/NameMatchOptionHandler.h b/src/NameMatchOptionHandler.h index d8c0e099c..12374a829 100644 --- a/src/NameMatchOptionHandler.h +++ b/src/NameMatchOptionHandler.h @@ -37,6 +37,7 @@ #include "OptionHandler.h" #include "DlAbortEx.h" +#include "StringFormat.h" #include namespace aria2 { @@ -62,8 +63,10 @@ public: { try { parseArg(option, arg); - } catch(Exception* e) { - throw new DlAbortEx(e, "Exception occurred while processing option %s", _optName.c_str()); + } catch(Exception& e) { + throw DlAbortEx + (StringFormat("Exception occurred while processing option %s", + _optName.c_str()).str(), e); } } }; diff --git a/src/NameResolver.cc b/src/NameResolver.cc index df77cd0e6..3b6ecadab 100644 --- a/src/NameResolver.cc +++ b/src/NameResolver.cc @@ -35,6 +35,7 @@ #include "NameResolver.h" #include "DlAbortEx.h" #include "message.h" +#include "StringFormat.h" #include namespace aria2 { @@ -108,8 +109,8 @@ void NameResolver::resolve(const std::string& hostname) struct addrinfo* res; int ec; if((ec = getaddrinfo(hostname.c_str(), 0, &ai, &res)) != 0) { - throw new DlAbortEx(EX_RESOLVE_HOSTNAME, - hostname.c_str(), gai_strerror(ec)); + throw DlAbortEx(StringFormat(EX_RESOLVE_HOSTNAME, + hostname.c_str(), gai_strerror(ec)).str()); } _addr = ((struct sockaddr_in*)res->ai_addr)->sin_addr; freeaddrinfo(res); diff --git a/src/Netrc.cc b/src/Netrc.cc index 9c73fc66e..b593049d7 100644 --- a/src/Netrc.cc +++ b/src/Netrc.cc @@ -34,6 +34,7 @@ /* copyright --> */ #include "Netrc.h" #include "RecoverableException.h" +#include "StringFormat.h" #include #include @@ -45,7 +46,8 @@ std::string Netrc::getRequiredNextToken(std::ifstream& f) const if(f >> token) { return token; } else { - throw new RecoverableException("Netrc:parse error. EOF reached where a token expected."); + throw RecoverableException + ("Netrc:parse error. EOF reached where a token expected."); } } @@ -66,7 +68,8 @@ void Netrc::parse(const std::string& path) std::ifstream f(path.c_str()); if(!f) { - throw new RecoverableException("File not found: %s", path.c_str()); + throw RecoverableException + (StringFormat("File not found: %s", path.c_str()).str()); } AuthenticatorHandle authenticator; @@ -81,7 +84,8 @@ void Netrc::parse(const std::string& path) authenticator.reset(new DefaultAuthenticator()); } else { if(authenticator.isNull()) { - throw new RecoverableException("Netrc:parse error. %s encounterd where 'machine' or 'default' expected."); + throw RecoverableException + ("Netrc:parse error. %s encounterd where 'machine' or 'default' expected."); } if(token == "login") { authenticator->setLogin(getRequiredNextToken(f)); diff --git a/src/NullLogger.h b/src/NullLogger.h index b6d3b2986..d113d2f82 100644 --- a/src/NullLogger.h +++ b/src/NullLogger.h @@ -42,15 +42,15 @@ public: NullLogger() {} virtual ~NullLogger() {} virtual void debug(const char* msg, ...) const {} - virtual void debug(const char* msg, Exception* ex, ...) const {} + virtual void debug(const char* msg, Exception& ex, ...) const {} virtual void info(const char* msg, ...) const {} - virtual void info(const char* msg, Exception* ex, ...) const {} + virtual void info(const char* msg, Exception& ex, ...) const {} virtual void notice(const char* msg, ...) const {} - virtual void notice(const char* msg, Exception* ex, ...) const {} + virtual void notice(const char* msg, Exception& ex, ...) const {} virtual void warn(const char* msg, ...) const {} - virtual void warn(const char* msg, Exception* ex, ...) const {} + virtual void warn(const char* msg, Exception& ex, ...) const {} virtual void error(const char* msg, ...) const {} - virtual void error(const char* msg, Exception* ex, ...) const {} + virtual void error(const char* msg, Exception& ex, ...) const {} }; #endif // _D_NULL_LOGGER_H_ diff --git a/src/OptionHandlerImpl.h b/src/OptionHandlerImpl.h index 1d6e81a98..8c042b5dd 100644 --- a/src/OptionHandlerImpl.h +++ b/src/OptionHandlerImpl.h @@ -41,6 +41,7 @@ #include "FatalException.h" #include "prefs.h" #include "Option.h" +#include "StringFormat.h" #include #include @@ -68,7 +69,7 @@ public: option->put(_optName, V_FALSE); } else { std::string msg = _optName+" "+_("must be either 'true' or 'false'."); - throw new FatalException(msg.c_str()); + throw FatalException(msg); } } }; @@ -89,7 +90,9 @@ public: int32_t v = seq.next(); if(v < _min || _max < v) { std::string msg = _optName+" "+_("must be between %s and %s."); - throw new FatalException(msg.c_str(), Util::itos(_min).c_str(), Util::itos(_max).c_str()); + throw FatalException + (StringFormat(msg.c_str(), Util::itos(_min).c_str(), + Util::itos(_max).c_str()).str()); } option->put(_optName, optarg); } @@ -118,18 +121,18 @@ public: } else { std::string msg = _optName+" "; if(_min == -1 && _max != -1) { - msg += _("must be smaller than or equal to %s."); - throw new FatalException(msg.c_str(), Util::itos(_max).c_str()); + msg += StringFormat(_("must be smaller than or equal to %s."), + Util::itos(_max).c_str()).str(); } else if(_min != -1 && _max != -1) { - msg += _("must be between %s and %s."); - throw new FatalException(msg.c_str(), Util::itos(_min).c_str(), Util::itos(_max).c_str()); + msg += StringFormat(_("must be between %s and %s."), + Util::itos(_min).c_str(), Util::itos(_max).c_str()).str(); } else if(_min != -1 && _max == -1) { - msg += _("must be greater than or equal to %s."); - throw new FatalException(msg.c_str(), Util::itos(_min).c_str()); + msg += StringFormat(_("must be greater than or equal to %s."), + Util::itos(_min).c_str()).str(); } else { msg += _("must be a number."); - throw new FatalException(msg.c_str()); } + throw FatalException(msg); } } }; @@ -164,18 +167,18 @@ public: } else { std::string msg = _optName+" "; if(_min < 0 && _max >= 0) { - msg += _("must be smaller than or equal to %.1f."); - throw new FatalException(msg.c_str(), _max); + msg += StringFormat(_("must be smaller than or equal to %.1f."), + _max).str(); } else if(_min >= 0 && _max >= 0) { - msg += _("must be between %.1f and %.1f."); - throw new FatalException(msg.c_str(), _min, _max); + msg += StringFormat(_("must be between %.1f and %.1f."), + _min, _max).str(); } else if(_min >= 0 && _max < 0) { - msg += _("must be greater than or equal to %.1f."); - throw new FatalException(msg.c_str(), _min); + msg += StringFormat(_("must be greater than or equal to %.1f."), + _min).str(); } else { msg += _("must be a number."); - throw new FatalException(msg.c_str()); } + throw FatalException(msg); } } }; @@ -260,7 +263,7 @@ public: msg += "'"+*itr+"' "; } } - throw new FatalException(msg.c_str()); + throw FatalException(msg); } else { option->put(_optName, optarg); } @@ -288,7 +291,7 @@ public: int32_t port = Util::parseInt(proxy.second); if(proxy.first.empty() || proxy.second.empty() || port <= 0 || 65535 < port) { - throw new FatalException(_("unrecognized proxy format")); + throw FatalException(_("unrecognized proxy format")); } option->put(_optName, optarg); setHostAndPort(option, proxy.first, port); diff --git a/src/PStringSegment.cc b/src/PStringSegment.cc index 56e40585b..3a650f3c8 100644 --- a/src/PStringSegment.cc +++ b/src/PStringSegment.cc @@ -51,7 +51,7 @@ void PStringSegment::accept(PStringVisitor* visitor) { PStringSegmentVisitor* v = dynamic_cast(visitor); if(!v) { - throw new FatalException("Class cast exception"); + throw FatalException("Class cast exception"); } v->hello(this); if(!_next.isNull()) { diff --git a/src/ParameterizedStringParser.cc b/src/ParameterizedStringParser.cc index 5de690647..48f31cc73 100644 --- a/src/ParameterizedStringParser.cc +++ b/src/ParameterizedStringParser.cc @@ -86,12 +86,12 @@ PStringDatumHandle ParameterizedStringParser::createSelect(const std::string& sr ++offset; std::string::size_type rightParenIndex = src.find("}", offset); if(rightParenIndex == std::string::npos) { - throw new FatalException("Missing '}' in the parameterized string."); + throw FatalException("Missing '}' in the parameterized string."); } std::deque values; Util::slice(values, src.substr(offset, rightParenIndex-offset), ',', true); if(values.empty()) { - throw new FatalException("Empty {} is not allowed."); + throw FatalException("Empty {} is not allowed."); } offset = rightParenIndex+1; PStringDatumHandle next = diggPString(src, offset); @@ -104,7 +104,7 @@ PStringDatumHandle ParameterizedStringParser::createLoop(const std::string& src, ++offset; std::string::size_type rightParenIndex = src.find("]", offset); if(rightParenIndex == std::string::npos) { - throw new FatalException("Missing ']' in the parameterized string."); + throw FatalException("Missing ']' in the parameterized string."); } std::string loopStr = src.substr(offset, rightParenIndex-offset); offset = rightParenIndex+1; @@ -116,13 +116,13 @@ PStringDatumHandle ParameterizedStringParser::createLoop(const std::string& src, if(Util::isNumber(stepStr)) { step = Util::parseUInt(stepStr); } else { - throw new FatalException("A step count must be a positive number."); + throw FatalException("A step count must be a positive number."); } loopStr.erase(colonIndex); } std::pair range = Util::split(loopStr, "-"); if(range.first == "" || range.second == "") { - throw new FatalException("Loop range missing."); + throw FatalException("Loop range missing."); } NumberDecoratorHandle nd; unsigned int start; @@ -140,7 +140,7 @@ PStringDatumHandle ParameterizedStringParser::createLoop(const std::string& src, start = Util::alphaToNum(range.first); end = Util::alphaToNum(range.second); } else { - throw new FatalException("Invalid loop range."); + throw FatalException("Invalid loop range."); } PStringDatumHandle next(diggPString(src, offset)); diff --git a/src/PeerAbstractCommand.cc b/src/PeerAbstractCommand.cc index b46fdc316..d8ee695f4 100644 --- a/src/PeerAbstractCommand.cc +++ b/src/PeerAbstractCommand.cc @@ -74,7 +74,7 @@ PeerAbstractCommand::~PeerAbstractCommand() { bool PeerAbstractCommand::execute() { if(exitBeforeExecute()) { - onAbort(0); + onAbort(); return true; } try { @@ -88,15 +88,14 @@ bool PeerAbstractCommand::execute() { checkPoint.reset(); } if(checkPoint.elapsed(timeout)) { - throw new DlAbortEx(EX_TIME_OUT); + throw DlAbortEx(EX_TIME_OUT); } return executeInternal(); - } catch(RecoverableException* err) { + } catch(RecoverableException& err) { logger->debug(MSG_TORRENT_DOWNLOAD_ABORTED, err, cuid); logger->debug(MSG_PEER_BANNED, cuid, peer->ipaddr.c_str(), peer->port); - onAbort(err); - delete err; + onAbort(); return prepareForNextPeer(0); } } diff --git a/src/PeerAbstractCommand.h b/src/PeerAbstractCommand.h index 2edbc6a36..e44e1d58b 100644 --- a/src/PeerAbstractCommand.h +++ b/src/PeerAbstractCommand.h @@ -57,7 +57,7 @@ protected: void setTimeout(time_t timeout) { this->timeout = timeout; } virtual bool prepareForNextPeer(time_t wait); - virtual void onAbort(Exception* ex) {}; + virtual void onAbort() {}; virtual bool exitBeforeExecute() = 0; virtual bool executeInternal() = 0; void setReadCheckSocket(const SharedHandle& socket); diff --git a/src/PeerConnection.cc b/src/PeerConnection.cc index d5e549e88..dc3a844d9 100644 --- a/src/PeerConnection.cc +++ b/src/PeerConnection.cc @@ -42,6 +42,7 @@ #include "a2netcompat.h" #include "ARC4Encryptor.h" #include "ARC4Decryptor.h" +#include "StringFormat.h" #include #include #include @@ -86,7 +87,7 @@ bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) { // we got EOF logger->debug("CUID#%d - In PeerConnection::receiveMessage(), remain=%zu", cuid, temp); - throw new DlAbortEx(EX_EOF_FROM_PEER); + throw DlAbortEx(EX_EOF_FROM_PEER); } lenbufLength += remaining; if(4 > lenbufLength) { @@ -95,7 +96,7 @@ bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) { } uint32_t payloadLength = ntohl(*(reinterpret_cast(lenbuf))); if(payloadLength > MAX_PAYLOAD_LEN) { - throw new DlAbortEx(EX_TOO_LONG_PAYLOAD, payloadLength); + throw DlAbortEx(StringFormat(EX_TOO_LONG_PAYLOAD, payloadLength).str()); } currentPayloadLength = payloadLength; } @@ -111,7 +112,7 @@ bool PeerConnection::receiveMessage(unsigned char* data, size_t& dataLength) { // we got EOF logger->debug("CUID#%d - In PeerConnection::receiveMessage(), payloadlen=%zu, remaining=%zu", cuid, currentPayloadLength, temp); - throw new DlAbortEx(EX_EOF_FROM_PEER); + throw DlAbortEx(EX_EOF_FROM_PEER); } resbufLength += remaining; if(currentPayloadLength > resbufLength) { @@ -142,7 +143,7 @@ bool PeerConnection::receiveHandshake(unsigned char* data, size_t& dataLength, // we got EOF logger->debug("CUID#%d - In PeerConnection::receiveHandshake(), remain=%zu", cuid, temp); - throw new DlAbortEx(EX_EOF_FROM_PEER); + throw DlAbortEx(EX_EOF_FROM_PEER); } resbufLength += remaining; if(BtHandshakeMessage::MESSAGE_LENGTH > resbufLength) { diff --git a/src/PeerInitiateConnectionCommand.cc b/src/PeerInitiateConnectionCommand.cc index ac3282dcd..239dc946f 100644 --- a/src/PeerInitiateConnectionCommand.cc +++ b/src/PeerInitiateConnectionCommand.cc @@ -103,7 +103,7 @@ bool PeerInitiateConnectionCommand::prepareForNextPeer(time_t wait) { return true; } -void PeerInitiateConnectionCommand::onAbort(Exception* ex) { +void PeerInitiateConnectionCommand::onAbort() { peerStorage->returnPeer(peer); } diff --git a/src/PeerInitiateConnectionCommand.h b/src/PeerInitiateConnectionCommand.h index ca72bb04c..04b58cc10 100644 --- a/src/PeerInitiateConnectionCommand.h +++ b/src/PeerInitiateConnectionCommand.h @@ -50,7 +50,7 @@ private: protected: virtual bool executeInternal(); virtual bool prepareForNextPeer(time_t wait); - virtual void onAbort(Exception* ex); + virtual void onAbort(); virtual bool exitBeforeExecute(); public: diff --git a/src/PeerInteractionCommand.cc b/src/PeerInteractionCommand.cc index b62acc89c..a954081a2 100644 --- a/src/PeerInteractionCommand.cc +++ b/src/PeerInteractionCommand.cc @@ -262,10 +262,9 @@ bool PeerInteractionCommand::prepareForNextPeer(time_t wait) { return true; } -void PeerInteractionCommand::onAbort(Exception* ex) { +void PeerInteractionCommand::onAbort() { btInteractive->cancelAllPiece(); peerStorage->returnPeer(peer); - //PeerAbstractCommand::onAbort(ex); } bool PeerInteractionCommand::exitBeforeExecute() diff --git a/src/PeerInteractionCommand.h b/src/PeerInteractionCommand.h index f8430cf79..525cac1da 100644 --- a/src/PeerInteractionCommand.h +++ b/src/PeerInteractionCommand.h @@ -61,7 +61,7 @@ private: protected: virtual bool executeInternal(); virtual bool prepareForNextPeer(time_t wait); - virtual void onAbort(Exception* ex); + virtual void onAbort(); virtual bool exitBeforeExecute(); public: PeerInteractionCommand(int32_t cuid, diff --git a/src/PeerListenCommand.cc b/src/PeerListenCommand.cc index 1b01b98ef..2a037f489 100644 --- a/src/PeerListenCommand.cc +++ b/src/PeerListenCommand.cc @@ -78,10 +78,9 @@ bool PeerListenCommand::bindPort(uint16_t& port, IntSequence& seq) socket->setNonBlockingMode(); logger->info(MSG_LISTENING_PORT, cuid, port); return true; - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { logger->error(MSG_BIND_FAILURE, ex, cuid, port); socket->closeConnection(); - delete ex; } } return false; @@ -116,9 +115,8 @@ bool PeerListenCommand::execute() { peer->ipaddr.c_str(), peer->port); logger->debug("Added CUID#%d to receive BitTorrent/MSE handshake.", cuid); - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { logger->debug(MSG_ACCEPT_FAILURE, ex, cuid); - delete ex; } } e->commands.push_back(this); diff --git a/src/PeerMessageUtil.cc b/src/PeerMessageUtil.cc index c71c94bf6..e611534db 100644 --- a/src/PeerMessageUtil.cc +++ b/src/PeerMessageUtil.cc @@ -35,6 +35,7 @@ #include "PeerMessageUtil.h" #include "DlAbortEx.h" #include "a2netcompat.h" +#include "StringFormat.h" #include #include @@ -59,35 +60,35 @@ uint16_t PeerMessageUtil::getShortIntParam(const unsigned char* msg, size_t pos) void PeerMessageUtil::checkIndex(size_t index, size_t pieces) { if(!(index < pieces)) { - throw new DlAbortEx("Invalid index: %zu", index); + throw DlAbortEx(StringFormat("Invalid index: %zu", index).str()); } } void PeerMessageUtil::checkBegin(uint32_t begin, size_t pieceLength) { if(!(begin < pieceLength)) { - throw new DlAbortEx("Invalid begin: %u", begin); + throw DlAbortEx(StringFormat("Invalid begin: %u", begin).str()); } } void PeerMessageUtil::checkLength(size_t length) { if(length > MAX_BLOCK_LENGTH) { - throw new DlAbortEx("Length too long: %zu > %uKB", length, - MAX_BLOCK_LENGTH/1024); + throw DlAbortEx(StringFormat("Length too long: %zu > %uKB", length, + MAX_BLOCK_LENGTH/1024).str()); } if(length == 0) { - throw new DlAbortEx("Invalid length: %zu", length); + throw DlAbortEx(StringFormat("Invalid length: %zu", length).str()); } } void PeerMessageUtil::checkRange(uint32_t begin, size_t length, size_t pieceLength) { if(!(0 < length)) { - throw new DlAbortEx("Invalid range: begin=%u, length=%zu", - begin, length); + throw DlAbortEx(StringFormat("Invalid range: begin=%u, length=%zu", + begin, length).str()); } uint32_t end = begin+length; if(!(end <= pieceLength)) { - throw new DlAbortEx("Invalid range: begin=%u, length=%zu", - begin, length); + throw DlAbortEx(StringFormat("Invalid range: begin=%u, length=%zu", + begin, length).str()); } } @@ -95,13 +96,13 @@ void PeerMessageUtil::checkBitfield(const unsigned char* bitfield, size_t bitfieldLength, size_t pieces) { if(!(bitfieldLength == (pieces+7)/8)) { - throw new DlAbortEx("Invalid bitfield length: %zu", - bitfieldLength); + throw DlAbortEx(StringFormat("Invalid bitfield length: %zu", + bitfieldLength).str()); } char lastbyte = bitfield[bitfieldLength-1]; for(size_t i = 0; i < 8-pieces%8 && pieces%8 != 0; ++i) { if(!(((lastbyte >> i) & 1) == 0)) { - throw new DlAbortEx("Invalid bitfield"); + throw DlAbortEx("Invalid bitfield"); } } } diff --git a/src/PeerReceiveHandshakeCommand.cc b/src/PeerReceiveHandshakeCommand.cc index 80db99915..3c4e411f5 100644 --- a/src/PeerReceiveHandshakeCommand.cc +++ b/src/PeerReceiveHandshakeCommand.cc @@ -52,6 +52,7 @@ #include "prefs.h" #include "Option.h" #include "RequestGroupMan.h" +#include "StringFormat.h" namespace aria2 { @@ -93,7 +94,8 @@ bool PeerReceiveHandshakeCommand::executeInternal() std::string infoHash = Util::toHex(&data[28], INFO_HASH_LENGTH); BtContextHandle btContext = BtRegistry::getBtContext(infoHash); if(btContext.isNull() || !BT_RUNTIME(btContext)->ready()) { - throw new DlAbortEx("Unknown info hash %s", infoHash.c_str()); + throw DlAbortEx + (StringFormat("Unknown info hash %s", infoHash.c_str()).str()); } TransferStat tstat = PEER_STORAGE(btContext)->calculateStat(); if((!PIECE_STORAGE(btContext)->downloadFinished() && diff --git a/src/PiecesMetalinkParserState.cc b/src/PiecesMetalinkParserState.cc index 5fa51d79e..8d589f5ef 100644 --- a/src/PiecesMetalinkParserState.cc +++ b/src/PiecesMetalinkParserState.cc @@ -51,8 +51,7 @@ void PiecesMetalinkParserState::beginElement(MetalinkParserStateMachine* stm, } else { try { stm->createNewHashOfChunkChecksum(Util::parseInt((*itr).second)); - } catch(RecoverableException* e) { - delete e; + } catch(RecoverableException& e) { stm->cancelChunkChecksumTransaction(); } } diff --git a/src/Platform.cc b/src/Platform.cc index 5b6ff6ffe..4b334f0a0 100644 --- a/src/Platform.cc +++ b/src/Platform.cc @@ -56,7 +56,7 @@ Platform::Platform() { WSADATA wsaData; memset((char*)&wsaData, 0, sizeof(wsaData)); if (WSAStartup(MAKEWORD(1, 1), &wsaData)) { - throw new DlAbortEx(MSG_WINSOCK_INIT_FAILD); + throw DlAbortEx(MSG_WINSOCK_INIT_FAILD); } } diff --git a/src/RealtimeCommand.cc b/src/RealtimeCommand.cc index 932154d48..44ea0f3a7 100644 --- a/src/RealtimeCommand.cc +++ b/src/RealtimeCommand.cc @@ -44,9 +44,8 @@ bool RealtimeCommand::execute() _e->setNoWait(true); try { return executeInternal(); - } catch(Exception* e) { + } catch(Exception& e) { bool r = handleException(e); - delete e; return r; } } diff --git a/src/RealtimeCommand.h b/src/RealtimeCommand.h index fd9269ada..d9e497099 100644 --- a/src/RealtimeCommand.h +++ b/src/RealtimeCommand.h @@ -59,7 +59,7 @@ public: virtual bool executeInternal() = 0; - virtual bool handleException(Exception* e) = 0; + virtual bool handleException(Exception& e) = 0; }; } // namespace aria2 diff --git a/src/ReceiverMSEHandshakeCommand.cc b/src/ReceiverMSEHandshakeCommand.cc index 75240f8ce..997b98b26 100644 --- a/src/ReceiverMSEHandshakeCommand.cc +++ b/src/ReceiverMSEHandshakeCommand.cc @@ -88,7 +88,7 @@ bool ReceiverMSEHandshakeCommand::executeInternal() break; case MSEHandshake::HANDSHAKE_LEGACY: { if(e->option->getAsBool(PREF_BT_REQUIRE_CRYPTO)) { - throw new DlAbortEx("The legacy BitTorrent handshake is not acceptable by the preference."); + throw DlAbortEx("The legacy BitTorrent handshake is not acceptable by the preference."); } SharedHandle peerConnection (new PeerConnection(cuid, socket, e->option)); @@ -100,7 +100,7 @@ bool ReceiverMSEHandshakeCommand::executeInternal() return true; } default: - throw new DlAbortEx("Not supported handshake type."); + throw DlAbortEx("Not supported handshake type."); } break; } diff --git a/src/RecoverableException.h b/src/RecoverableException.h index 5345d6910..664ddc481 100644 --- a/src/RecoverableException.h +++ b/src/RecoverableException.h @@ -38,23 +38,18 @@ namespace aria2 { -class RecoverableException : public Exception { +class RecoverableException:public Exception { +protected: + virtual SharedHandle copy() const + { + SharedHandle e(new RecoverableException(*this)); + return e; + } public: - RecoverableException(Exception* cause = 0):Exception(cause) {} - - RecoverableException(const char* msg, ...):Exception() { - va_list ap; - va_start(ap, msg); - setMsg(msg, ap); - va_end(ap); - } - - RecoverableException(Exception* cause, const char* msg, ...):Exception(cause) { - va_list ap; - va_start(ap, msg); - setMsg(msg, ap); - va_end(ap); - } + RecoverableException(const std::string& msg):Exception(msg) {} + RecoverableException(const std::string& msg, + const Exception& cause):Exception(msg, cause) {} + RecoverableException(const RecoverableException& e):Exception(e) {} }; } // namespace aria2 diff --git a/src/Request.cc b/src/Request.cc index e06f19817..8cf46c76e 100644 --- a/src/Request.cc +++ b/src/Request.cc @@ -127,8 +127,7 @@ bool Request::parseUrl(const std::string& url) { if(hostAndPort.second != "") { try { port = Util::parseInt(hostAndPort.second); - } catch(RecoverableException* e) { - delete e; + } catch(RecoverableException& e) { return false; } } else { @@ -181,7 +180,7 @@ std::string Request::urlencode(const std::string& src) const result.replace(index, 1, "%25"); } } else { - result.replace(index, 1, StringFormat("%%%02x", c).toString()); + result.replace(index, 1, StringFormat("%%%02x", c).str()); } } } diff --git a/src/RequestGroup.cc b/src/RequestGroup.cc index 31772af8a..5866cdf4e 100644 --- a/src/RequestGroup.cc +++ b/src/RequestGroup.cc @@ -70,6 +70,7 @@ #include "FileEntry.h" #include "Request.h" #include "FileAllocationIterator.h" +#include "StringFormat.h" #ifdef ENABLE_MESSAGE_DIGEST # include "CheckIntegrityCommand.h" #endif // ENABLE_MESSAGE_DIGEST @@ -177,8 +178,9 @@ Commands RequestGroup::createInitialCommand(DownloadEngine* e) BtContextHandle btContext = dynamic_pointer_cast(_downloadContext); if(!btContext.isNull()) { if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) { - throw new DownloadFailureException(EX_DUPLICATE_FILE_DOWNLOAD, - getFilePath().c_str()); + throw DownloadFailureException + (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD, + getFilePath().c_str()).str()); } initPieceStorage(); if(btContext->getFileEntries().size() > 1) { @@ -237,8 +239,10 @@ Commands RequestGroup::createInitialCommand(DownloadEngine* e) if(_option->get(PREF_CHECK_INTEGRITY) != V_TRUE && _option->get(PREF_ALLOW_OVERWRITE) != V_TRUE) { // TODO we need this->haltRequested = true? - throw new DownloadFailureException(MSG_FILE_ALREADY_EXISTS, - _pieceStorage->getDiskAdaptor()->getFilePath().c_str()); + throw DownloadFailureException + (StringFormat(MSG_FILE_ALREADY_EXISTS, + _pieceStorage->getDiskAdaptor()->getFilePath().c_str() + ).str()); } else { _pieceStorage->getDiskAdaptor()->openFile(); } @@ -272,8 +276,9 @@ Commands RequestGroup::createInitialCommand(DownloadEngine* e) return createNextCommand(e, 1); }else { if(e->_requestGroupMan->isSameFileBeingDownloaded(this)) { - throw new DownloadFailureException(EX_DUPLICATE_FILE_DOWNLOAD, - getFilePath().c_str()); + throw DownloadFailureException + (StringFormat(EX_DUPLICATE_FILE_DOWNLOAD, + getFilePath().c_str()).str()); } initPieceStorage(); BtProgressInfoFileHandle @@ -366,10 +371,11 @@ void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoF File outfile(getFilePath()); if(outfile.exists() && _option->get(PREF_CONTINUE) == V_TRUE) { if(getTotalLength() < outfile.size()) { - throw new DlAbortEx(EX_FILE_LENGTH_MISMATCH_BETWEEN_LOCAL_AND_REMOTE, - getFilePath().c_str(), - Util::itos(outfile.size()).c_str(), - Util::itos(getTotalLength()).c_str()); + throw DlAbortEx + (StringFormat(EX_FILE_LENGTH_MISMATCH_BETWEEN_LOCAL_AND_REMOTE, + getFilePath().c_str(), + Util::itos(outfile.size()).c_str(), + Util::itos(getTotalLength()).c_str()).str()); } _pieceStorage->getDiskAdaptor()->openExistingFile(); _pieceStorage->markPiecesDone(outfile.size()); @@ -388,8 +394,9 @@ void RequestGroup::loadAndOpenFile(const BtProgressInfoFileHandle& progressInfoF } } setProgressInfoFile(progressInfoFile); - } catch(RecoverableException* e) { - throw new DownloadFailureException(e, EX_DOWNLOAD_ABORTED); + } catch(RecoverableException& e) { + throw DownloadFailureException + (StringFormat(EX_DOWNLOAD_ABORTED).str(), e); } } @@ -405,12 +412,14 @@ void RequestGroup::shouldCancelDownloadForSafety() if(tryAutoFileRenaming()) { _logger->notice(MSG_FILE_RENAMED, getFilePath().c_str()); } else { - throw new DownloadFailureException("File renaming failed: %s", - getFilePath().c_str()); + throw DownloadFailureException + (StringFormat("File renaming failed: %s", + getFilePath().c_str()).str()); } } else { - throw new DownloadFailureException(MSG_FILE_ALREADY_EXISTS, - getFilePath().c_str()); + throw DownloadFailureException + (StringFormat(MSG_FILE_ALREADY_EXISTS, + getFilePath().c_str()).str()); } } } @@ -541,9 +550,9 @@ void RequestGroup::validateFilename(const std::string& expectedFilename, return; } if(expectedFilename != actualFilename) { - throw new DlAbortEx(EX_FILENAME_MISMATCH, - expectedFilename.c_str(), - actualFilename.c_str()); + throw DlAbortEx(StringFormat(EX_FILENAME_MISMATCH, + expectedFilename.c_str(), + actualFilename.c_str()).str()); } } @@ -554,9 +563,10 @@ void RequestGroup::validateTotalLength(uint64_t expectedTotalLength, return; } if(expectedTotalLength != actualTotalLength) { - throw new DlAbortEx(EX_SIZE_MISMATCH, - Util::itos(expectedTotalLength, true).c_str(), - Util::itos(actualTotalLength, true).c_str()); + throw DlAbortEx + (StringFormat(EX_SIZE_MISMATCH, + Util::itos(expectedTotalLength, true).c_str(), + Util::itos(actualTotalLength, true).c_str()).str()); } } @@ -682,9 +692,8 @@ void RequestGroup::preDownloadProcessing() return; } } - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { _logger->error(EX_EXCEPTION_CAUGHT, ex); - delete ex; return; } _logger->debug("No PreDownloadHandler found."); @@ -701,9 +710,8 @@ RequestGroups RequestGroup::postDownloadProcessing() return (*itr)->getNextRequestGroups(this); } } - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { _logger->error(EX_EXCEPTION_CAUGHT, ex); - delete ex; return RequestGroups(); } _logger->debug("No PostDownloadHandler found."); diff --git a/src/RequestGroupMan.cc b/src/RequestGroupMan.cc index ea03904cb..5819752e0 100644 --- a/src/RequestGroupMan.cc +++ b/src/RequestGroupMan.cc @@ -125,9 +125,8 @@ void RequestGroupMan::removeStoppedGroup() } else { (*itr)->getProgressInfoFile()->save(); } - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { _logger->error(EX_EXCEPTION_CAUGHT, ex); - delete ex; } (*itr)->releaseRuntimeResource(); ++count; @@ -158,9 +157,8 @@ void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e) _requestGroups.push_back(groupToAdd); ++count; e->addCommand(commands); - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { _logger->error(EX_EXCEPTION_CAUGHT, ex); - delete ex; _downloadResults.push_back(groupToAdd->createDownloadResult()); } } @@ -185,9 +183,8 @@ Commands RequestGroupMan::getInitialCommands(DownloadEngine* e) _reservedGroups.push_front((*itr)); itr = _requestGroups.erase(itr); } - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { _logger->error(EX_EXCEPTION_CAUGHT, e); - delete e; _downloadResults.push_back((*itr)->createDownloadResult()); itr = _requestGroups.erase(itr); } @@ -204,9 +201,8 @@ void RequestGroupMan::save() } else { try { (*itr)->getProgressInfoFile()->save(); - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { _logger->error(EX_EXCEPTION_CAUGHT, e); - delete e; } } } diff --git a/src/ResourcesMetalinkParserState.cc b/src/ResourcesMetalinkParserState.cc index 2cbd624bd..6ac10c74f 100644 --- a/src/ResourcesMetalinkParserState.cc +++ b/src/ResourcesMetalinkParserState.cc @@ -69,8 +69,7 @@ void ResourcesMetalinkParserState::beginElement(MetalinkParserStateMachine* stm, } else { try { preference = Util::parseInt((*itr).second); - } catch(RecoverableException* e) { - delete e; + } catch(RecoverableException& e) { preference = 0; } } @@ -83,8 +82,7 @@ void ResourcesMetalinkParserState::beginElement(MetalinkParserStateMachine* stm, } else { try { maxConnections = Util::parseInt((*itr).second); - } catch(RecoverableException* e) { - delete e; + } catch(RecoverableException& e) { maxConnections = -1; } } diff --git a/src/SimpleLogger.cc b/src/SimpleLogger.cc index 2dc5ab1da..27cdfc083 100644 --- a/src/SimpleLogger.cc +++ b/src/SimpleLogger.cc @@ -58,12 +58,15 @@ namespace aria2 { va_list ap;\ va_start(ap, MSG);\ writeFile(Logger::LEVEL, MSG, ap);\ +flush();\ va_end(ap); #define WRITE_LOG_EX(LEVEL, MSG, EX) \ va_list ap;\ va_start(ap, EX);\ -writeFile(Logger::LEVEL, MSG, ap, EX);\ +writeFile(Logger::LEVEL, MSG, ap);\ +writeStackTrace(Logger::LEVEL, EX);\ +flush();\ va_end(ap); SimpleLogger::SimpleLogger():stdoutField(0) {} @@ -75,7 +78,8 @@ SimpleLogger::~SimpleLogger() { void SimpleLogger::openFile(const std::string& filename) { file.open(filename.c_str(), std::ios::app|std::ios::binary); if(!file) { - throw new DlAbortEx(EX_FILE_OPEN, filename.c_str(), strerror(errno)); + throw DlAbortEx + (StringFormat(EX_FILE_OPEN, filename.c_str(), strerror(errno)).str()); } } @@ -100,7 +104,7 @@ void SimpleLogger::writeHeader(std::ostream& o, const std::string& date, } void SimpleLogger::writeLog(std::ostream& o, Logger::LEVEL level, - const char* msg, va_list ap, Exception* e, + const char* msg, va_list ap, bool printHeader) { va_list apCopy; @@ -142,31 +146,37 @@ void SimpleLogger::writeLog(std::ostream& o, Logger::LEVEL level, free(res); } } - for(Exception* nestedEx = e; nestedEx; nestedEx = nestedEx->getCause()) { - // TODO a quick hack not to print header in console - if(printHeader) { - writeHeader(o, datestr, levelStr); - } - o << StringFormat("exception: %s\n", Util::replace(nestedEx->getMsg(), "\r", "").c_str()); - } - o << std::flush; va_end(apCopy); } -void SimpleLogger::writeFile(Logger::LEVEL level, const char* msg, va_list ap, Exception* e) +void SimpleLogger::writeFile(Logger::LEVEL level, const char* msg, va_list ap) { - writeLog(file, level, msg, ap, e); + writeLog(file, level, msg, ap); if(stdoutField&level) { std::cout << "\n"; - writeLog(std::cout, level, msg, ap, e); + writeLog(std::cout, level, msg, ap); } } +void SimpleLogger::writeStackTrace(Logger::LEVEL level, const Exception& e) +{ + file << e.stackTrace(); + if(stdoutField&level) { + std::cout << e.stackTrace(); + } +} + +void SimpleLogger::flush() +{ + file << std::flush; + std::cout << std::flush; +} + void SimpleLogger::debug(const char* msg, ...) { WRITE_LOG(DEBUG, msg); } -void SimpleLogger::debug(const char* msg, Exception* e, ...) { +void SimpleLogger::debug(const char* msg, Exception& e, ...) { WRITE_LOG_EX(DEBUG, msg, e); } @@ -174,7 +184,7 @@ void SimpleLogger::info(const char* msg, ...) { WRITE_LOG(INFO, msg); } -void SimpleLogger::info(const char* msg, Exception* e, ...) { +void SimpleLogger::info(const char* msg, Exception& e, ...) { WRITE_LOG_EX(INFO, msg, e); } @@ -182,7 +192,7 @@ void SimpleLogger::notice(const char* msg, ...) { WRITE_LOG(NOTICE, msg); } -void SimpleLogger::notice(const char* msg, Exception* e, ...) { +void SimpleLogger::notice(const char* msg, Exception& e, ...) { WRITE_LOG_EX(INFO, msg, e); } @@ -190,7 +200,7 @@ void SimpleLogger::warn(const char* msg, ...) { WRITE_LOG(WARN, msg); } -void SimpleLogger::warn(const char* msg, Exception* e, ...) { +void SimpleLogger::warn(const char* msg, Exception& e, ...) { WRITE_LOG_EX(WARN, msg, e); } @@ -198,7 +208,7 @@ void SimpleLogger::error(const char* msg, ...) { WRITE_LOG(ERROR, msg); } -void SimpleLogger::error(const char* msg, Exception* e, ...) { +void SimpleLogger::error(const char* msg, Exception& e, ...) { WRITE_LOG_EX(ERROR, msg, e); } diff --git a/src/SimpleLogger.h b/src/SimpleLogger.h index 8d32c4e84..a16509b6e 100644 --- a/src/SimpleLogger.h +++ b/src/SimpleLogger.h @@ -44,12 +44,18 @@ namespace aria2 { class SimpleLogger:public Logger { private: - void writeFile(Logger::LEVEL level, const char* msg, va_list ap, Exception* e = 0); + void writeFile(Logger::LEVEL level, const char* msg, va_list ap); + + void writeStackTrace(Logger::LEVEL level, const Exception& e); + + void flush(); + void writeHeader(std::ostream& out, const std::string& date, const std::string& level); + void writeLog(std::ostream& out, Logger::LEVEL level, const char* msg, va_list ap, - Exception* e = 0, bool printHeader = true); + bool printHeader = true); std::ofstream file; int stdoutField; @@ -60,15 +66,15 @@ public: void openFile(const std::string& filename); void closeFile(); virtual void debug(const char* msg, ...); - virtual void debug(const char* msg, Exception* ex, ...); + virtual void debug(const char* msg, Exception& ex, ...); virtual void info(const char* msg, ...); - virtual void info(const char* msg, Exception* ex, ...); + virtual void info(const char* msg, Exception& ex, ...); virtual void notice(const char* msg, ...); - virtual void notice(const char* msg, Exception* ex, ...); + virtual void notice(const char* msg, Exception& ex, ...); virtual void warn(const char* msg, ...); - virtual void warn(const char* msg, Exception* ex, ...); + virtual void warn(const char* msg, Exception& ex, ...); virtual void error(const char* msg, ...); - virtual void error(const char* msg, Exception* ex, ...); + virtual void error(const char* msg, Exception& ex, ...); void setStdout(Logger::LEVEL level, bool enabled); }; diff --git a/src/SizeMetalinkParserState.cc b/src/SizeMetalinkParserState.cc index bb27ec0a3..5d0d438ad 100644 --- a/src/SizeMetalinkParserState.cc +++ b/src/SizeMetalinkParserState.cc @@ -52,8 +52,7 @@ void SizeMetalinkParserState::endElement(MetalinkParserStateMachine* stm, { try { stm->setFileLengthOfEntry(Util::parseLLInt(characters)); - } catch(RecoverableException* e) { - delete e; + } catch(RecoverableException& e) { // current metalink specification doesn't require size element. } stm->setFileState(); diff --git a/src/SocketCore.cc b/src/SocketCore.cc index 83c1f80bb..76f00d4cf 100644 --- a/src/SocketCore.cc +++ b/src/SocketCore.cc @@ -37,6 +37,7 @@ #include "a2netcompat.h" #include "DlRetryEx.h" #include "DlAbortEx.h" +#include "StringFormat.h" #include #include #include @@ -123,7 +124,7 @@ void SocketCore::bind(uint16_t port) int s; s = getaddrinfo(0, uitos(port).c_str(), &hints, &res); if(s) { - throw new DlAbortEx(EX_SOCKET_BIND, gai_strerror(s)); + throw DlAbortEx(StringFormat(EX_SOCKET_BIND, gai_strerror(s)).str()); } struct addrinfo* rp; for(rp = res; rp; rp = rp->ai_next) { @@ -145,14 +146,14 @@ void SocketCore::bind(uint16_t port) } freeaddrinfo(res); if(sockfd == -1) { - throw new DlAbortEx(EX_SOCKET_BIND, "all addresses failed"); + throw DlAbortEx(StringFormat(EX_SOCKET_BIND, "all addresses failed").str()); } } void SocketCore::beginListen() { if(listen(sockfd, 1) == -1) { - throw new DlAbortEx(EX_SOCKET_LISTEN, errorMsg()); + throw DlAbortEx(StringFormat(EX_SOCKET_LISTEN, errorMsg()).str()); } } @@ -163,7 +164,7 @@ SocketCore* SocketCore::acceptConnection() const int fd; while((fd = accept(sockfd, reinterpret_cast(&sockaddr), &len)) == -1 && errno == EINTR); if(fd == -1) { - throw new DlAbortEx(EX_SOCKET_ACCEPT, errorMsg()); + throw DlAbortEx(StringFormat(EX_SOCKET_ACCEPT, errorMsg()).str()); } return new SocketCore(fd, _sockType); } @@ -176,8 +177,8 @@ SocketCore::getNameInfoInNumeric(const struct sockaddr* sockaddr, socklen_t len) int s = getnameinfo(sockaddr, len, host, NI_MAXHOST, service, NI_MAXSERV, NI_NUMERICHOST|NI_NUMERICSERV); if(s != 0) { - throw new DlAbortEx("Failed to get hostname and port. cause: %s", - gai_strerror(s)); + throw DlAbortEx(StringFormat("Failed to get hostname and port. cause: %s", + gai_strerror(s)).str()); } return std::pair(host, atoi(service)); // TODO } @@ -188,7 +189,7 @@ void SocketCore::getAddrInfo(std::pair& addrinfo) const socklen_t len = sizeof(sockaddr); struct sockaddr* addrp = reinterpret_cast(&sockaddr); if(getsockname(sockfd, addrp, &len) == -1) { - throw new DlAbortEx(EX_SOCKET_GET_NAME, errorMsg()); + throw DlAbortEx(StringFormat(EX_SOCKET_GET_NAME, errorMsg()).str()); } addrinfo = SocketCore::getNameInfoInNumeric(addrp, len); } @@ -199,7 +200,7 @@ void SocketCore::getPeerInfo(std::pair& peerinfo) const socklen_t len = sizeof(sockaddr); struct sockaddr* addrp = reinterpret_cast(&sockaddr); if(getpeername(sockfd, addrp, &len) == -1) { - throw new DlAbortEx(EX_SOCKET_GET_NAME, errorMsg()); + throw DlAbortEx(StringFormat(EX_SOCKET_GET_NAME, errorMsg()).str()); } peerinfo = SocketCore::getNameInfoInNumeric(addrp, len); } @@ -218,7 +219,8 @@ void SocketCore::establishConnection(const std::string& host, uint16_t port) int s; s = getaddrinfo(host.c_str(), uitos(port).c_str(), &hints, &res); if(s) { - throw new DlAbortEx(EX_RESOLVE_HOSTNAME, host.c_str(), gai_strerror(s)); + throw DlAbortEx(StringFormat(EX_RESOLVE_HOSTNAME, + host.c_str(), gai_strerror(s)).str()); } struct addrinfo* rp; for(rp = res; rp; rp = rp->ai_next) { @@ -246,7 +248,8 @@ void SocketCore::establishConnection(const std::string& host, uint16_t port) } freeaddrinfo(res); if(sockfd == -1) { - throw new DlAbortEx(EX_SOCKET_CONNECT, host.c_str(), "all addresses failed"); + throw DlAbortEx(StringFormat(EX_SOCKET_CONNECT, host.c_str(), + "all addresses failed").str()); } } @@ -255,7 +258,7 @@ void SocketCore::setNonBlockingMode() #ifdef __MINGW32__ static u_long flag = 1; if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) { - throw new DlAbortEx(EX_SOCKET_NONBLOCKING, errorMsg()); + throw DlAbortEx(StringFormat(EX_SOCKET_NONBLOCKING, errorMsg()).str()); } #else int flags; @@ -271,7 +274,7 @@ void SocketCore::setBlockingMode() #ifdef __MINGW32__ static u_long flag = 0; if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) { - throw new DlAbortEx(EX_SOCKET_BLOCKING, errorMsg()); + throw DlAbortEx(StringFormat(EX_SOCKET_BLOCKING, errorMsg()).str()); } #else int flags; @@ -334,7 +337,7 @@ bool SocketCore::isWritable(time_t timeout) const if(SOCKET_ERRNO == EINPROGRESS || SOCKET_ERRNO == EINTR) { return false; } else { - throw new DlRetryEx(EX_SOCKET_CHECK_WRITABLE, errorMsg()); + throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_WRITABLE, errorMsg()).str()); } } } @@ -364,7 +367,7 @@ bool SocketCore::isReadable(time_t timeout) const if(SOCKET_ERRNO == EINPROGRESS || SOCKET_ERRNO == EINTR) { return false; } else { - throw new DlRetryEx(EX_SOCKET_CHECK_READABLE, errorMsg()); + throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_READABLE, errorMsg()).str()); } } } @@ -377,7 +380,7 @@ void SocketCore::writeData(const char* data, size_t len) while((ret = send(sockfd, data, len, 0)) == -1 && errno == EINTR); // TODO assuming Blocking mode. if(ret == -1 || (size_t)ret != len) { - throw new DlRetryEx(EX_SOCKET_SEND, errorMsg()); + throw DlRetryEx(StringFormat(EX_SOCKET_SEND, errorMsg()).str()); } } else { #ifdef HAVE_LIBSSL @@ -385,13 +388,13 @@ void SocketCore::writeData(const char* data, size_t len) // TODO handling len == 0 case required ret = SSL_write(ssl, data, len); if(ret <= 0 || (size_t)ret != len) { - throw new DlRetryEx(EX_SOCKET_SEND, ERR_error_string(ERR_get_error(), NULL)); + throw DlRetryEx(StringFormat(EX_SOCKET_SEND, ERR_error_string(ERR_get_error(), NULL)).str()); } #endif // HAVE_LIBSSL #ifdef HAVE_LIBGNUTLS ret = gnutls_record_send(sslSession, data, len); if(ret < 0 || (size_t)ret != len) { - throw new DlRetryEx(EX_SOCKET_SEND, gnutls_strerror(ret)); + throw DlRetryEx(StringFormat(EX_SOCKET_SEND, gnutls_strerror(ret)).str()); } #endif // HAVE_LIBGNUTLS } @@ -404,19 +407,22 @@ void SocketCore::readData(char* data, size_t& len) if(!secure) { while((ret = recv(sockfd, data, len, 0)) == -1 && errno == EINTR); if(ret == -1) { - throw new DlRetryEx(EX_SOCKET_RECV, errorMsg()); + throw DlRetryEx(StringFormat(EX_SOCKET_RECV, errorMsg()).str()); } } else { #ifdef HAVE_LIBSSL // for SSL // TODO handling len == 0 case required if ((ret = SSL_read(ssl, data, len)) <= 0) { - throw new DlRetryEx(EX_SOCKET_RECV, ERR_error_string(ERR_get_error(), NULL)); + throw DlRetryEx + (StringFormat(EX_SOCKET_RECV, + ERR_error_string(ERR_get_error(), 0)).str()); } #endif // HAVE_LIBSSL #ifdef HAVE_LIBGNUTLS if ((ret = gnutlsRecv(data, len)) < 0) { - throw new DlRetryEx(EX_SOCKET_RECV, gnutls_strerror(ret)); + throw DlRetryEx + (StringFormat(EX_SOCKET_RECV, gnutls_strerror(ret)).str()); } #endif // HAVE_LIBGNUTLS } @@ -431,19 +437,22 @@ void SocketCore::peekData(char* data, size_t& len) if(!secure) { while((ret = recv(sockfd, data, len, MSG_PEEK)) == -1 && errno == EINTR); if(ret == -1) { - throw new DlRetryEx(EX_SOCKET_PEEK, errorMsg()); + throw DlRetryEx(StringFormat(EX_SOCKET_PEEK, errorMsg()).str()); } } else { #ifdef HAVE_LIBSSL // for SSL // TODO handling len == 0 case required if ((ret = SSL_peek(ssl, data, len)) < 0) { - throw new DlRetryEx(EX_SOCKET_PEEK, ERR_error_string(ERR_get_error(), NULL)); + throw DlRetryEx + (StringFormat(EX_SOCKET_PEEK, + ERR_error_string(ERR_get_error(), 0)).str()); } #endif // HAVE_LIBSSL #ifdef HAVE_LIBGNUTLS if ((ret = gnutlsPeek(data, len)) < 0) { - throw new DlRetryEx(EX_SOCKET_PEEK, gnutls_strerror(ret)); + throw DlRetryEx(StringFormat(EX_SOCKET_PEEK, + gnutls_strerror(ret)).str()); } #endif // HAVE_LIBGNUTLS } @@ -490,7 +499,7 @@ ssize_t SocketCore::gnutlsRecv(char* data, size_t len) if(plen < len) { ssize_t ret = gnutls_record_recv(sslSession, data+plen, len-plen); if(ret < 0) { - throw new DlRetryEx(EX_SOCKET_RECV, gnutls_strerror(ret)); + throw DlRetryEx(StringFormat(EX_SOCKET_RECV, gnutls_strerror(ret)).str()); } return plen+ret; } else { @@ -507,7 +516,7 @@ ssize_t SocketCore::gnutlsPeek(char* data, size_t len) memcpy(data, peekBuf, peekBufLength); ssize_t ret = gnutls_record_recv(sslSession, data+peekBufLength, len-peekBufLength); if(ret < 0) { - throw new DlRetryEx(EX_SOCKET_PEEK, gnutls_strerror(ret)); + throw DlRetryEx(StringFormat(EX_SOCKET_PEEK, gnutls_strerror(ret)).str()); } addPeekData(data+peekBufLength, ret); return peekBufLength; @@ -522,15 +531,21 @@ void SocketCore::initiateSecureConnection() if(!secure) { sslCtx = SSL_CTX_new(SSLv23_client_method()); if(sslCtx == NULL) { - throw new DlAbortEx(EX_SSL_INIT_FAILURE, ERR_error_string(ERR_get_error(), NULL)); + throw DlAbortEx + (StringFormat(EX_SSL_INIT_FAILURE, + ERR_error_string(ERR_get_error(), 0)).str()); } SSL_CTX_set_mode(sslCtx, SSL_MODE_AUTO_RETRY); ssl = SSL_new(sslCtx); if(ssl == NULL) { - throw new DlAbortEx(EX_SSL_INIT_FAILURE, ERR_error_string(ERR_get_error(), NULL)); + throw DlAbortEx + (StringFormat(EX_SSL_INIT_FAILURE, + ERR_error_string(ERR_get_error(), 0)).str()); } if(SSL_set_fd(ssl, sockfd) == 0) { - throw new DlAbortEx(EX_SSL_INIT_FAILURE, ERR_error_string(ERR_get_error(), NULL)); + throw DlAbortEx + (StringFormat(EX_SSL_INIT_FAILURE, + ERR_error_string(ERR_get_error(), 0)).str()); } // TODO handling return value == 0 case required int e = SSL_connect(ssl); @@ -546,18 +561,20 @@ void SocketCore::initiateSecureConnection() case SSL_ERROR_WANT_X509_LOOKUP: case SSL_ERROR_ZERO_RETURN: if (blocking) { - throw new DlAbortEx(EX_SSL_CONNECT_ERROR, ssl_error); + throw DlAbortEx + (StringFormat(EX_SSL_CONNECT_ERROR, ssl_error).str()); } break; case SSL_ERROR_SYSCALL: - throw new DlAbortEx(EX_SSL_IO_ERROR); + throw DlAbortEx(EX_SSL_IO_ERROR); case SSL_ERROR_SSL: - throw new DlAbortEx(EX_SSL_PROTOCOL_ERROR); + throw DlAbortEx(EX_SSL_PROTOCOL_ERROR); default: - throw new DlAbortEx(EX_SSL_UNKNOWN_ERROR, ssl_error); + throw DlAbortEx + (StringFormat(EX_SSL_UNKNOWN_ERROR, ssl_error).str()); } } } @@ -578,7 +595,8 @@ void SocketCore::initiateSecureConnection() gnutls_transport_set_ptr(sslSession, (gnutls_transport_ptr_t)sockfd); int ret = gnutls_handshake(sslSession); if(ret < 0) { - throw new DlAbortEx(EX_SSL_INIT_FAILURE, gnutls_strerror(ret)); + throw DlAbortEx + (StringFormat(EX_SSL_INIT_FAILURE, gnutls_strerror(ret)).str()); } peekBuf = new char[peekBufMax]; } @@ -632,7 +650,7 @@ void SocketCore::writeData(const char* data, size_t len, const std::string& host int s; s = getaddrinfo(host.c_str(), uitos(port).c_str(), &hints, &res); if(s) { - throw new DlAbortEx(EX_SOCKET_SEND, gai_strerror(s)); + throw DlAbortEx(StringFormat(EX_SOCKET_SEND, gai_strerror(s)).str()); } struct addrinfo* rp; ssize_t r = -1; @@ -644,7 +662,7 @@ void SocketCore::writeData(const char* data, size_t len, const std::string& host } freeaddrinfo(res); if(r == -1) { - throw new DlAbortEx(EX_SOCKET_SEND, errorMsg()); + throw DlAbortEx(StringFormat(EX_SOCKET_SEND, errorMsg()).str()); } } @@ -659,7 +677,7 @@ ssize_t SocketCore::readDataFrom(char* data, size_t len, while((r = recvfrom(sockfd, data, len, 0, addrp, &sockaddrlen)) == -1 && EINTR == errno); if(r == -1) { - throw new DlAbortEx(EX_SOCKET_RECV, errorMsg()); + throw DlAbortEx(StringFormat(EX_SOCKET_RECV, errorMsg()).str()); } sender = SocketCore::getNameInfoInNumeric(addrp, sockaddrlen); diff --git a/src/StringFormat.cc b/src/StringFormat.cc index 2dadc0ac2..3f2517803 100644 --- a/src/StringFormat.cc +++ b/src/StringFormat.cc @@ -53,14 +53,14 @@ StringFormat::StringFormat(const char* fmt, ...) va_end(ap); } -const std::string& StringFormat::toString() const +const std::string& StringFormat::str() const { return _msg; } std::ostream& operator<<(std::ostream& o, const StringFormat& fmt) { - o << fmt.toString(); + o << fmt.str(); return o; } diff --git a/src/StringFormat.h b/src/StringFormat.h index f119863bb..ccc8dd597 100644 --- a/src/StringFormat.h +++ b/src/StringFormat.h @@ -47,7 +47,7 @@ private: public: StringFormat(const char* fmt, ...); - const std::string& toString() const; + const std::string& str() const; }; std::ostream& operator<<(std::ostream& o, const StringFormat& fmt); diff --git a/src/TrackerWatcherCommand.cc b/src/TrackerWatcherCommand.cc index 0d4703625..0e5cf100e 100644 --- a/src/TrackerWatcherCommand.cc +++ b/src/TrackerWatcherCommand.cc @@ -98,9 +98,8 @@ bool TrackerWatcherCommand::execute() { processTrackerResponse(trackerResponse); btAnnounce->announceSuccess(); btAnnounce->resetAnnounce(); - } catch(RecoverableException* ex) { + } catch(RecoverableException& ex) { logger->error(EX_EXCEPTION_CAUGHT, ex); - delete ex; btAnnounce->announceFailure(); if(btAnnounce->isAllAnnounceFailed()) { btAnnounce->resetAnnounce(); diff --git a/src/UTPexExtensionMessage.cc b/src/UTPexExtensionMessage.cc index 5139ece37..154777f70 100644 --- a/src/UTPexExtensionMessage.cc +++ b/src/UTPexExtensionMessage.cc @@ -46,6 +46,7 @@ #include "MetaFileUtil.h" #include "DlAbortEx.h" #include "message.h" +#include "StringFormat.h" namespace aria2 { @@ -125,8 +126,8 @@ UTPexExtensionMessage::create(const BtContextHandle& btContext, const unsigned char* data, size_t len) { if(len < 1) { - throw new DlAbortEx(MSG_TOO_SMALL_PAYLOAD_SIZE, - EXTENSION_NAME.c_str(), len); + throw DlAbortEx(StringFormat(MSG_TOO_SMALL_PAYLOAD_SIZE, + EXTENSION_NAME.c_str(), len).str()); } UTPexExtensionMessageHandle msg(new UTPexExtensionMessage(*data)); SharedHandle root(MetaFileUtil::bdecoding(data+1, len-1)); diff --git a/src/Util.cc b/src/Util.cc index 25829b9e8..106dae574 100644 --- a/src/Util.cc +++ b/src/Util.cc @@ -206,7 +206,7 @@ std::string Util::urlencode(const unsigned char* target, size_t len) { std::string dest; for(size_t i = 0; i < len; i++) { if(shouldUrlencode(target[i])) { - dest.append(StringFormat("%%%02x", target[i]).toString()); + dest.append(StringFormat("%%%02x", target[i]).str()); } else { dest += target[i]; } @@ -222,7 +222,7 @@ std::string Util::torrentUrlencode(const unsigned char* target, size_t len) { ('a' <= target[i] && target[i] <= 'z')) { dest += target[i]; } else { - dest.append(StringFormat("%%%02x", target[i]).toString()); + dest.append(StringFormat("%%%02x", target[i]).str()); } } return dest; @@ -396,20 +396,20 @@ int32_t Util::parseInt(const std::string& s, int32_t base) { std::string trimed = Util::trim(s); if(trimed.empty()) { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - "empty string"); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + "empty string").str()); } char* stop; errno = 0; long int v = strtol(trimed.c_str(), &stop, base); if(*stop != '\0') { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - trimed.c_str()); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + trimed.c_str()).str()); } else if((((v == LONG_MIN) || (v == LONG_MAX)) && (errno == ERANGE)) || (v > INT32_MAX) || (v < INT32_MIN)) { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - trimed.c_str()); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + trimed.c_str()).str()); } return v; } @@ -418,23 +418,23 @@ uint32_t Util::parseUInt(const std::string& s, int base) { std::string trimed = Util::trim(s); if(trimed.empty()) { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - "empty string"); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + "empty string").str()); } // We don't allow negative number. if(trimed[0] == '-') { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - trimed.c_str()); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + trimed.c_str()).str()); } char* stop; errno = 0; unsigned long int v = strtoul(trimed.c_str(), &stop, base); if(*stop != '\0') { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - trimed.c_str()); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + trimed.c_str()).str()); } else if(((v == ULONG_MAX) && (errno == ERANGE)) || (v > UINT32_MAX)) { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - trimed.c_str()); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + trimed.c_str()).str()); } return v; } @@ -443,18 +443,18 @@ int64_t Util::parseLLInt(const std::string& s, int32_t base) { std::string trimed = Util::trim(s); if(trimed.empty()) { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - "empty string"); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + "empty string").str()); } char* stop; errno = 0; int64_t v = strtoll(trimed.c_str(), &stop, base); if(*stop != '\0') { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - trimed.c_str()); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + trimed.c_str()).str()); } else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - trimed.c_str()); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + trimed.c_str()).str()); } return v; } @@ -463,23 +463,23 @@ uint64_t Util::parseULLInt(const std::string& s, int base) { std::string trimed = Util::trim(s); if(trimed.empty()) { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - "empty string"); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + "empty string").str()); } // We don't allow negative number. if(trimed[0] == '-') { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - trimed.c_str()); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + trimed.c_str()).str()); } char* stop; errno = 0; uint64_t v = strtoull(trimed.c_str(), &stop, base); if(*stop != '\0') { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - trimed.c_str()); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + trimed.c_str()).str()); } else if((v == ULLONG_MAX) && (errno == ERANGE)) { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - trimed.c_str()); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + trimed.c_str()).str()); } return v; } @@ -500,7 +500,8 @@ IntSequence Util::parseIntRange(const std::string& src) } else { std::pair vp = Util::split(p.first.c_str(), "-"); if(vp.first.empty() || vp.second.empty()) { - throw new DlAbortEx(MSG_INCOMPLETE_RANGE, p.first.c_str()); + throw DlAbortEx + (StringFormat(MSG_INCOMPLETE_RANGE, p.first.c_str()).str()); } int32_t v1 = Util::parseInt(vp.first.c_str()); int32_t v2 = Util::parseInt(vp.second.c_str()); @@ -643,10 +644,11 @@ int64_t Util::getRealSize(const std::string& sizeWithUnit) int64_t v = Util::parseLLInt(size); if(v < 0) { - throw new DlAbortEx("Negative value detected: %s", sizeWithUnit.c_str()); + throw DlAbortEx + (StringFormat("Negative value detected: %s", sizeWithUnit.c_str()).str()); } else if(INT64_MAX/mult < v) { - throw new DlAbortEx(MSG_STRING_INTEGER_CONVERSION_FAILURE, - "overflow/underflow"); + throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE, + "overflow/underflow").str()); } return v*mult; } @@ -805,9 +807,13 @@ void Util::mkdirs(const std::string& dirpath) if(dir.isDir()) { // do nothing } else if(dir.exists()) { - throw new DlAbortEx(EX_MAKE_DIR, dir.getPath().c_str(), "File already exists."); + throw DlAbortEx + (StringFormat(EX_MAKE_DIR, dir.getPath().c_str(), + "File already exists.").str()); } else if(!dir.mkdirs()) { - throw new DlAbortEx(EX_MAKE_DIR, dir.getPath().c_str(), strerror(errno)); + throw DlAbortEx + (StringFormat(EX_MAKE_DIR, dir.getPath().c_str(), + strerror(errno)).str()); } } @@ -845,7 +851,8 @@ void* Util::allocateAlignedMemory(size_t alignment, size_t size) void* buffer; int res; if((res = posix_memalign(&buffer, alignment, size)) != 0) { - throw new FatalException("Error in posix_memalign: %s", strerror(res)); + throw FatalException + (StringFormat("Error in posix_memalign: %s", strerror(res)).str()); } return buffer; } diff --git a/src/VerificationMetalinkParserState.cc b/src/VerificationMetalinkParserState.cc index e90811b44..ea4b5b6f9 100644 --- a/src/VerificationMetalinkParserState.cc +++ b/src/VerificationMetalinkParserState.cc @@ -77,8 +77,7 @@ void VerificationMetalinkParserState::beginElement(MetalinkParserStateMachine* s stm->newChunkChecksumTransaction(); stm->setLengthOfChunkChecksum(length); stm->setTypeOfChunkChecksum(type); - } catch(RecoverableException* e) { - delete e; + } catch(RecoverableException& e) { stm->cancelChunkChecksumTransaction(); } } else { diff --git a/src/XML2SAXMetalinkProcessor.cc b/src/XML2SAXMetalinkProcessor.cc index f6740ac7d..c3e5d2fde 100644 --- a/src/XML2SAXMetalinkProcessor.cc +++ b/src/XML2SAXMetalinkProcessor.cc @@ -138,7 +138,7 @@ XML2SAXMetalinkProcessor::parseFile(const std::string& filename) int retval = xmlSAXUserParseFile(&mySAXHandler, sessionData.get(), filename.c_str()); if(retval != 0) { - throw new DlAbortEx(MSG_CANNOT_PARSE_METALINK); + throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); } return _stm->getResult(); } @@ -152,7 +152,7 @@ XML2SAXMetalinkProcessor::parseFromBinaryStream(const SharedHandle ssize_t res = binaryStream->readData(buf, 4, 0); if(res != 4) { - throw new DlAbortEx("Too small data for parsing XML."); + throw DlAbortEx("Too small data for parsing XML."); } SharedHandle sessionData(new SessionData(_stm)); @@ -165,19 +165,19 @@ XML2SAXMetalinkProcessor::parseFromBinaryStream(const SharedHandle break; } if(xmlParseChunk(ctx, (const char*)buf, res, 0) != 0) { - throw new DlAbortEx(MSG_CANNOT_PARSE_METALINK); + throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); } readOffset += res; } xmlParseChunk(ctx, (const char*)buf, 0, 1); - } catch(Exception* e) { + } catch(Exception& e) { xmlFreeParserCtxt(ctx); - throw e; + throw; } xmlFreeParserCtxt(ctx); if(!_stm->finished()) { - throw new DlAbortEx(MSG_CANNOT_PARSE_METALINK); + throw DlAbortEx(MSG_CANNOT_PARSE_METALINK); } return _stm->getResult(); } diff --git a/src/main.cc b/src/main.cc index 4db1226ec..ddc9e819c 100644 --- a/src/main.cc +++ b/src/main.cc @@ -64,6 +64,7 @@ #include "ProtocolDetector.h" #include "ConsoleStatCalc.h" #include "NullStatCalc.h" +#include "StringFormat.h" #ifdef ENABLE_METALINK # include "MetalinkHelper.h" # include "Metalink2RequestGroup.h" @@ -191,7 +192,7 @@ int32_t downloadMetalink(Option* op) { RequestGroups groups = Metalink2RequestGroup(op).generate(op->get(PREF_METALINK_FILE)); if(groups.empty()) { - throw new FatalException("No files to download."); + throw FatalException("No files to download."); } return MultiUrlRequestInfo(groups, op, getStatCalc(op), getSummaryOut(op)).execute(); } @@ -221,11 +222,10 @@ public: try { groups.push_back(createBtRequestGroup(uri, _op, std::deque())); - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { // error occurred while parsing torrent file. // We simply ignore it. LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e); - delete e; } } #endif // ENABLE_BITTORRENT @@ -235,11 +235,10 @@ public: std::deque > metalinkGroups = Metalink2RequestGroup(_op).generate(uri); groups.insert(groups.end(), metalinkGroups.begin(), metalinkGroups.end()); - } catch(RecoverableException* e) { + } catch(RecoverableException& e) { // error occurred while parsing metalink file. // We simply ignore it. LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e); - delete e; } } #endif // ENABLE_METALINK @@ -286,7 +285,9 @@ int32_t downloadUriList(Option* op) return downloadUriList(op, std::cin); } else { if(!File(op->get(PREF_INPUT_FILE)).isFile()) { - throw new FatalException(EX_FILE_OPEN, op->get(PREF_INPUT_FILE).c_str(), "No such file"); + throw FatalException + (StringFormat(EX_FILE_OPEN, op->get(PREF_INPUT_FILE).c_str(), + "No such file").str()); } std::ifstream f(op->get(PREF_INPUT_FILE).c_str()); return downloadUriList(op, f); @@ -427,9 +428,8 @@ int main(int argc, char* argv[]) if(returnValue == 1) { exitStatus = EXIT_FAILURE; } - } catch(Exception* ex) { - std::cerr << EX_EXCEPTION_CAUGHT << "\n" << *ex << std::endl; - delete ex; + } catch(Exception& ex) { + std::cerr << EX_EXCEPTION_CAUGHT << "\n" << ex.stackTrace() << std::endl; exitStatus = EXIT_FAILURE; } delete op; diff --git a/src/messageDigest.h b/src/messageDigest.h index 62531ca5f..f2642c692 100644 --- a/src/messageDigest.h +++ b/src/messageDigest.h @@ -38,6 +38,7 @@ #include "common.h" #include "SharedHandle.h" #include "DlAbortEx.h" +#include "StringFormat.h" #include #ifdef HAVE_LIBSSL @@ -97,7 +98,9 @@ public: { DigestAlgoMap::const_iterator itr = digestAlgos.find(algostring); if(itr == digestAlgos.end()) { - throw new DlAbortEx("Digest algorithm %s is not supported.", algostring.c_str()); + throw DlAbortEx + (StringFormat("Digest algorithm %s is not supported.", + algostring.c_str()).str()); } return (*itr).second; } diff --git a/src/option_processing.cc b/src/option_processing.cc index 0f344bd66..ff0de5bf3 100644 --- a/src/option_processing.cc +++ b/src/option_processing.cc @@ -517,10 +517,9 @@ Option* option_processing(int argc, char* const argv[]) std::ifstream cfstream(cfname.c_str()); try { oparser.parse(op, cfstream); - } catch(Exception* e) { + } catch(Exception& e) { std::cerr << "Parse error in " << cfname << "\n" - << *e << std::endl; - delete e; + << e.stackTrace() << std::endl; exit(EXIT_FAILURE); } } else if(ucfname.size()) { @@ -530,9 +529,8 @@ Option* option_processing(int argc, char* const argv[]) } try { oparser.parse(op, cmdstream); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; exit(EXIT_FAILURE); } } diff --git a/test/BtDependencyTest.cc b/test/BtDependencyTest.cc index 6aa4d968e..09e11dcb6 100644 --- a/test/BtDependencyTest.cc +++ b/test/BtDependencyTest.cc @@ -91,9 +91,8 @@ void BtDependencyTest::testResolve_loadError() (dynamic_pointer_cast(dependant->getDownloadContext())); CPPUNIT_ASSERT(!dctx.isNull()); CPPUNIT_ASSERT_EQUAL(std::string("/tmp/index.html"), dctx->getActualBasePath()); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; CPPUNIT_FAIL("an exception was thrown."); } } diff --git a/test/BtExtendedMessageTest.cc b/test/BtExtendedMessageTest.cc index fc4b547be..ffe081a46 100644 --- a/test/BtExtendedMessageTest.cc +++ b/test/BtExtendedMessageTest.cc @@ -82,9 +82,8 @@ void BtExtendedMessageTest::testCreate() { PeerMessageUtil::createPeerMessageString(msg, sizeof(msg), 1, 20); BtExtendedMessage::create(ctx, peer, &msg[4], 1); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } // case: id is wrong try { @@ -92,9 +91,8 @@ void BtExtendedMessageTest::testCreate() { PeerMessageUtil::createPeerMessageString(msg, sizeof(msg), 2, 21); BtExtendedMessage::create(ctx, peer, &msg[4], 2); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } diff --git a/test/DHTConnectionImplTest.cc b/test/DHTConnectionImplTest.cc index 5c0c3f5c5..f4b5cb092 100644 --- a/test/DHTConnectionImplTest.cc +++ b/test/DHTConnectionImplTest.cc @@ -45,11 +45,8 @@ void DHTConnectionImplTest::testWriteAndReadData() CPPUNIT_ASSERT_EQUAL(message1, std::string(&readbuffer[0], &readbuffer[rlength])); } - } catch(Exception* e) { - std::string m = e->getMsg(); - std::cerr << *e << std::endl; - delete e; - CPPUNIT_FAIL(m); + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } diff --git a/test/DHTMessageFactoryImplTest.cc b/test/DHTMessageFactoryImplTest.cc index 3547f1bd0..c22525df0 100644 --- a/test/DHTMessageFactoryImplTest.cc +++ b/test/DHTMessageFactoryImplTest.cc @@ -185,9 +185,8 @@ void DHTMessageFactoryImplTest::testCreateFindNodeReplyMessage() CPPUNIT_ASSERT(nodes[7] == m->getClosestKNodes()[7]); CPPUNIT_ASSERT_EQUAL(Util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH), Util::toHex(m->getTransactionID())); - } catch(Exception* e) { - std::cerr << *e << std::endl; - CPPUNIT_FAIL("exception thrown."); + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -258,9 +257,8 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage_nodes() CPPUNIT_ASSERT(nodes[7] == m->getClosestKNodes()[7]); CPPUNIT_ASSERT_EQUAL(Util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH), Util::toHex(m->getTransactionID())); - } catch(Exception* e) { - std::cerr << *e << std::endl; - CPPUNIT_FAIL("exception thrown."); + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -302,9 +300,8 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage_values() CPPUNIT_ASSERT(peers[3] == m->getValues()[3]); CPPUNIT_ASSERT_EQUAL(Util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH), Util::toHex(m->getTransactionID())); - } catch(Exception* e) { - std::cerr << *e << std::endl; - CPPUNIT_FAIL("exception thrown."); + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -340,11 +337,8 @@ void DHTMessageFactoryImplTest::testCreateAnnouncePeerMessage() CPPUNIT_ASSERT_EQUAL(Util::toHex(infoHash, DHT_ID_LENGTH), Util::toHex(m->getInfoHash(), DHT_ID_LENGTH)); CPPUNIT_ASSERT_EQUAL(port, m->getTCPPort()); - } catch(Exception* e) { - std::cerr << *e << std::endl; - std::string msg = e->getMsg(); - delete e; - CPPUNIT_FAIL(msg); + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -387,8 +381,8 @@ void DHTMessageFactoryImplTest::testReceivedErrorMessage() try { factory->createResponseMessage("announce_peer", d.get(), remoteNode); CPPUNIT_FAIL("exception must be thrown."); - } catch(RecoverableException* e) { - std::cerr << *e << std::endl; + } catch(RecoverableException& e) { + std::cerr << e.stackTrace() << std::endl; } } diff --git a/test/DHTMessageTrackerEntryTest.cc b/test/DHTMessageTrackerEntryTest.cc index 25d08dae7..5cf7be418 100644 --- a/test/DHTMessageTrackerEntryTest.cc +++ b/test/DHTMessageTrackerEntryTest.cc @@ -46,11 +46,8 @@ void DHTMessageTrackerEntryTest::testMatch() CPPUNIT_ASSERT(!entry.match(msg2->getTransactionID(), msg2->getRemoteNode()->getIPAddress(), msg2->getRemoteNode()->getPort())); - } catch(Exception* e) { - std::cerr << *e << std::endl; - std::string msg = e->getMsg(); - delete e; - CPPUNIT_FAIL(msg); + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } diff --git a/test/DefaultBtAnnounceTest.cc b/test/DefaultBtAnnounceTest.cc index c8985587b..7cf5bdb0f 100644 --- a/test/DefaultBtAnnounceTest.cc +++ b/test/DefaultBtAnnounceTest.cc @@ -286,9 +286,8 @@ void DefaultBtAnnounceTest::testProcessAnnounceResponse_malformed() SharedHandle ctx(new MockBtContext()); DefaultBtAnnounce(ctx, _option).processAnnounceResponse(reinterpret_cast(res.c_str()), res.size()); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -299,9 +298,8 @@ void DefaultBtAnnounceTest::testProcessAnnounceResponse_failureReason() SharedHandle ctx(new MockBtContext()); DefaultBtAnnounce(ctx, _option).processAnnounceResponse(reinterpret_cast(res.c_str()), res.size()); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } diff --git a/test/DefaultBtContextTest.cc b/test/DefaultBtContextTest.cc index 104dcc233..88fd85a14 100644 --- a/test/DefaultBtContextTest.cc +++ b/test/DefaultBtContextTest.cc @@ -325,9 +325,8 @@ void DefaultBtContextTest::testLoadFromMemory_somethingMissing() DefaultBtContext btContext; btContext.loadFromMemory(memory, "default"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } diff --git a/test/DefaultBtMessageFactoryTest.cc b/test/DefaultBtMessageFactoryTest.cc index c92597249..3de44c060 100644 --- a/test/DefaultBtMessageFactoryTest.cc +++ b/test/DefaultBtMessageFactoryTest.cc @@ -88,9 +88,8 @@ void DefaultBtMessageFactoryTest::testCreateBtMessage_BtExtendedMessage() _peer->setExtendedMessagingEnabled(false); factory.createBtMessage((const unsigned char*)msg+4, sizeof(msg)); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -110,11 +109,8 @@ void DefaultBtMessageFactoryTest::testCreatePortMessage() (factory.createBtMessage(&data[4], sizeof(data)-4))); CPPUNIT_ASSERT(!m.isNull()); CPPUNIT_ASSERT_EQUAL((uint16_t)6881, m->getPort()); - } catch(Exception* e) { - std::cerr << *e << std::endl; - std::string msg = e->getMsg(); - delete e; - CPPUNIT_FAIL(msg); + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } { diff --git a/test/DefaultExtensionMessageFactoryTest.cc b/test/DefaultExtensionMessageFactoryTest.cc index 2692880ad..df0b5ca7b 100644 --- a/test/DefaultExtensionMessageFactoryTest.cc +++ b/test/DefaultExtensionMessageFactoryTest.cc @@ -70,9 +70,8 @@ void DefaultExtensionMessageFactoryTest::testCreateMessage_unknown() factory.createMessage(reinterpret_cast(data.c_str()), data.size()); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } diff --git a/test/ExceptionTest.cc b/test/ExceptionTest.cc new file mode 100644 index 000000000..87964eb64 --- /dev/null +++ b/test/ExceptionTest.cc @@ -0,0 +1,37 @@ +#include "Exception.h" +#include "DownloadFailureException.h" +#include "Util.h" +#include +#include + +namespace aria2 { + +class ExceptionTest:public CppUnit::TestFixture { + + CPPUNIT_TEST_SUITE(ExceptionTest); + CPPUNIT_TEST(testStackTrace); + CPPUNIT_TEST_SUITE_END(); +public: + void setUp() {} + + void tearDown() {} + + void testStackTrace(); +}; + + +CPPUNIT_TEST_SUITE_REGISTRATION(ExceptionTest); + +void ExceptionTest::testStackTrace() +{ + DownloadFailureException c1("cause1"); + DownloadFailureException c2("cause2", c1); + DownloadFailureException e("exception thrown", c2); + + CPPUNIT_ASSERT_EQUAL(std::string("Exception: exception thrown\n" + " -> cause2\n" + " -> cause1\n"), + e.stackTrace()); +} + +} // namespace aria2 diff --git a/test/HandshakeExtensionMessageTest.cc b/test/HandshakeExtensionMessageTest.cc index 711ae23c0..898ca8cb1 100644 --- a/test/HandshakeExtensionMessageTest.cc +++ b/test/HandshakeExtensionMessageTest.cc @@ -105,9 +105,8 @@ void HandshakeExtensionMessageTest::testCreate() HandshakeExtensionMessage::create(reinterpret_cast(in.c_str()), in.size()); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } try { // malformed dencoded message @@ -115,9 +114,8 @@ void HandshakeExtensionMessageTest::testCreate() HandshakeExtensionMessage::create(reinterpret_cast(in.c_str()), in.size()); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } try { // 0 length data @@ -125,9 +123,8 @@ void HandshakeExtensionMessageTest::testCreate() HandshakeExtensionMessage::create(reinterpret_cast(in.c_str()), in.size()); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } diff --git a/test/HttpHeaderProcessorTest.cc b/test/HttpHeaderProcessorTest.cc index 38e9f0fc9..09e5e33b4 100644 --- a/test/HttpHeaderProcessorTest.cc +++ b/test/HttpHeaderProcessorTest.cc @@ -124,9 +124,8 @@ void HttpHeaderProcessorTest::testGetHttpResponseHeader_empty() try { proc.getHttpResponseHeader(); CPPUNIT_FAIL("Exception must be thrown."); - } catch(DlRetryEx* ex) { - std::cout << ex->getMsg() << std::endl; - delete ex; + } catch(DlRetryEx& ex) { + std::cout << ex.stackTrace() << std::endl; } } @@ -150,9 +149,8 @@ void HttpHeaderProcessorTest::testGetHttpResponseHeader_insufficientStatusLength try { proc.getHttpResponseHeader(); CPPUNIT_FAIL("Exception must be thrown."); - } catch(DlRetryEx* ex) { - std::cout << ex->getMsg() << std::endl; - delete ex; + } catch(DlRetryEx& ex) { + std::cout << ex.stackTrace() << std::endl; } } @@ -170,9 +168,8 @@ void HttpHeaderProcessorTest::testBeyondLimit() try { proc.update(hd2); CPPUNIT_FAIL("Exception must be thrown."); - } catch(DlAbortEx* ex) { - std::cout << ex->getMsg() << std::endl; - delete ex; + } catch(DlAbortEx& ex) { + std::cout << ex.stackTrace() << std::endl; } } diff --git a/test/HttpResponseTest.cc b/test/HttpResponseTest.cc index bcf02fc44..4d52cdbe6 100644 --- a/test/HttpResponseTest.cc +++ b/test/HttpResponseTest.cc @@ -249,8 +249,7 @@ void HttpResponseTest::testValidateResponse() try { httpResponse.validateResponse(); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - delete e; + } catch(Exception& e) { } httpHeader->setResponseStatus("505"); @@ -258,8 +257,7 @@ void HttpResponseTest::testValidateResponse() try { httpResponse.validateResponse(); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - delete e; + } catch(Exception& e) { } httpHeader->setResponseStatus("304"); @@ -267,16 +265,14 @@ void HttpResponseTest::testValidateResponse() try { httpResponse.validateResponse(); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - delete e; + } catch(Exception& e) { } httpHeader->put("Location", "http://localhost/archives/aria2-1.0.0.tar.bz2"); try { httpResponse.validateResponse(); - } catch(Exception* e) { - delete e; + } catch(Exception& e) { CPPUNIT_FAIL("exception must not be thrown."); } } @@ -300,9 +296,8 @@ void HttpResponseTest::testValidateResponse_good_range() try { httpResponse.validateResponse(); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; CPPUNIT_FAIL("exception must not be thrown."); } } @@ -327,8 +322,7 @@ void HttpResponseTest::testValidateResponse_bad_range() try { httpResponse.validateResponse(); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - delete e; + } catch(Exception& e) { } } @@ -353,8 +347,7 @@ void HttpResponseTest::testValidateResponse_chunked() // if transfer-encoding is specified, then range validation is skipped. try { httpResponse.validateResponse(); - } catch(Exception* e) { - delete e; + } catch(Exception& e) { CPPUNIT_FAIL("exception must not be thrown."); } } diff --git a/test/Makefile.am b/test/Makefile.am index 60d36ec0e..aefcd2b2e 100644 --- a/test/Makefile.am +++ b/test/Makefile.am @@ -50,7 +50,8 @@ aria2c_SOURCES = AllTest.cc\ MultiFileAllocationIteratorTest.cc\ FixedNumberRandomizer.h\ ProtocolDetectorTest.cc\ - StringFormatTest.cc + StringFormatTest.cc\ + ExceptionTest.cc if ENABLE_MESSAGE_DIGEST aria2c_SOURCES += MessageDigestHelperTest.cc\ diff --git a/test/Makefile.in b/test/Makefile.in index e89011cf6..48d646274 100644 --- a/test/Makefile.in +++ b/test/Makefile.in @@ -188,7 +188,7 @@ am__aria2c_SOURCES_DIST = AllTest.cc SocketCoreTest.cc \ FileTest.cc OptionTest.cc DefaultDiskWriterTest.cc \ FeatureConfigTest.cc SpeedCalcTest.cc MultiDiskAdaptorTest.cc \ MultiFileAllocationIteratorTest.cc FixedNumberRandomizer.h \ - ProtocolDetectorTest.cc StringFormatTest.cc \ + ProtocolDetectorTest.cc StringFormatTest.cc ExceptionTest.cc \ MessageDigestHelperTest.cc \ IteratableChunkChecksumValidatorTest.cc \ IteratableChecksumValidatorTest.cc BtAllowedFastMessageTest.cc \ @@ -352,7 +352,8 @@ am_aria2c_OBJECTS = AllTest.$(OBJEXT) SocketCoreTest.$(OBJEXT) \ SpeedCalcTest.$(OBJEXT) MultiDiskAdaptorTest.$(OBJEXT) \ MultiFileAllocationIteratorTest.$(OBJEXT) \ ProtocolDetectorTest.$(OBJEXT) StringFormatTest.$(OBJEXT) \ - $(am__objects_1) $(am__objects_2) $(am__objects_3) + ExceptionTest.$(OBJEXT) $(am__objects_1) $(am__objects_2) \ + $(am__objects_3) aria2c_OBJECTS = $(am_aria2c_OBJECTS) am__DEPENDENCIES_1 = aria2c_DEPENDENCIES = ../src/libaria2c.a $(am__DEPENDENCIES_1) @@ -588,8 +589,8 @@ aria2c_SOURCES = AllTest.cc SocketCoreTest.cc array_funTest.cc \ FileTest.cc OptionTest.cc DefaultDiskWriterTest.cc \ FeatureConfigTest.cc SpeedCalcTest.cc MultiDiskAdaptorTest.cc \ MultiFileAllocationIteratorTest.cc FixedNumberRandomizer.h \ - ProtocolDetectorTest.cc StringFormatTest.cc $(am__append_1) \ - $(am__append_2) $(am__append_3) + ProtocolDetectorTest.cc StringFormatTest.cc ExceptionTest.cc \ + $(am__append_1) $(am__append_2) $(am__append_3) #aria2c_CXXFLAGS = ${CPPUNIT_CFLAGS} -I../src -I../lib -Wall -D_FILE_OFFSET_BITS=64 #aria2c_LDFLAGS = ${CPPUNIT_LIBS} @@ -746,6 +747,7 @@ distclean-compile: @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DefaultPieceStorageTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DictionaryTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DownloadHandlerFactoryTest.Po@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ExceptionTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/FeatureConfigTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/FileEntryTest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/FileTest.Po@am__quote@ diff --git a/test/MetaFileUtilTest.cc b/test/MetaFileUtilTest.cc index d42a4f096..4ff2a4106 100644 --- a/test/MetaFileUtilTest.cc +++ b/test/MetaFileUtilTest.cc @@ -38,8 +38,7 @@ void MetaFileUtilTest::testBdecoding() { std::string str = "5:abcd"; MetaFileUtil::bdecoding(str); CPPUNIT_FAIL("DlAbortEx exception must be thrown."); - } catch(DlAbortEx* ex) { - delete ex; + } catch(DlAbortEx& ex) { } catch(...) { CPPUNIT_FAIL("DlAbortEx exception must be thrown."); } @@ -48,8 +47,7 @@ void MetaFileUtilTest::testBdecoding() { std::string str = "i1234"; MetaFileUtil::bdecoding(str); CPPUNIT_FAIL("DlAbortEx exception must be thrown."); - } catch(DlAbortEx* ex) { - delete ex; + } catch(DlAbortEx& ex) { } catch(...) { CPPUNIT_FAIL("DlAbortEx exception must be thrown."); } @@ -58,8 +56,7 @@ void MetaFileUtilTest::testBdecoding() { const std::string str = "5abcd"; MetaFileUtil::bdecoding(str); CPPUNIT_FAIL("DlAbortEx exception must be thrown."); - } catch(DlAbortEx* ex) { - delete ex; + } catch(DlAbortEx& ex) { } catch(...) { CPPUNIT_FAIL("DlAbortEx exception must be thrown."); } @@ -68,8 +65,7 @@ void MetaFileUtilTest::testBdecoding() { const std::string str = "d"; MetaFileUtil::bdecoding(str); CPPUNIT_FAIL("DlAbortEx exception must be thrown."); - } catch(DlAbortEx* ex) { - delete ex; + } catch(DlAbortEx& ex) { } catch(...) { CPPUNIT_FAIL("DlAbortEx exception must be thrown."); } diff --git a/test/MetalinkProcessorTest.cc b/test/MetalinkProcessorTest.cc index 45e46c2ad..07a189bf7 100644 --- a/test/MetalinkProcessorTest.cc +++ b/test/MetalinkProcessorTest.cc @@ -146,9 +146,8 @@ void MetalinkProcessorTest::testParseFile() #endif // ENABLE_MESSAGE_DIGEST - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -164,9 +163,8 @@ void MetalinkProcessorTest::testParseFromBinaryStream() std::deque >::iterator entryItr = m->entries.begin(); SharedHandle entry1 = *entryItr; CPPUNIT_ASSERT_EQUAL(std::string("aria2-0.5.2.tar.bz2"), entry1->getPath()); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -179,9 +177,8 @@ void MetalinkProcessorTest::testMalformedXML() try { SharedHandle m = proc->parseFromBinaryStream(dw); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -194,9 +191,8 @@ void MetalinkProcessorTest::testMalformedXML2() try { SharedHandle m = proc->parseFromBinaryStream(dw); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -226,9 +222,8 @@ void MetalinkProcessorTest::testBadSize() CPPUNIT_ASSERT_EQUAL(std::string("en-US"), e->language); CPPUNIT_ASSERT_EQUAL(std::string("Linux-x86"), e->os); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -254,9 +249,8 @@ void MetalinkProcessorTest::testBadMaxConn() std::deque >::iterator entryItr = m->entries.begin(); SharedHandle e = *entryItr; CPPUNIT_ASSERT_EQUAL(43743838ULL, e->getLength()); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -287,9 +281,8 @@ void MetalinkProcessorTest::testNoName() std::deque >::iterator entryItr = m->entries.begin(); SharedHandle e = *entryItr; CPPUNIT_ASSERT_EQUAL(std::string("aria2-0.5.2.tar.bz2"), e->getPath()); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -319,9 +312,8 @@ void MetalinkProcessorTest::testBadURLPrefs() CPPUNIT_ASSERT_EQUAL(0, r->preference); CPPUNIT_ASSERT_EQUAL(1, r->maxConnections); CPPUNIT_ASSERT_EQUAL(std::string("JP"), r->location); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -351,9 +343,8 @@ void MetalinkProcessorTest::testBadURLMaxConn() CPPUNIT_ASSERT_EQUAL(100, r->preference); CPPUNIT_ASSERT_EQUAL(-1, r->maxConnections); CPPUNIT_ASSERT_EQUAL(std::string("JP"), r->location); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -388,9 +379,8 @@ void MetalinkProcessorTest::testUnsupportedType() CPPUNIT_ASSERT_EQUAL(MetalinkResource::TYPE_NOT_SUPPORTED, r2->type); SharedHandle r3 = e->resources[2]; CPPUNIT_ASSERT_EQUAL(MetalinkResource::TYPE_HTTP, r3->type); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -421,9 +411,8 @@ void MetalinkProcessorTest::testMultiplePieces() CPPUNIT_ASSERT_EQUAL(std::string("sha1"), c->getAlgo()); CPPUNIT_ASSERT_EQUAL((size_t)1024, c->getChecksumLength()); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -453,9 +442,8 @@ void MetalinkProcessorTest::testBadPieceNo() SharedHandle c = e->chunkChecksum; CPPUNIT_ASSERT_EQUAL(std::string("sha256"), c->getAlgo()); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -484,9 +472,8 @@ void MetalinkProcessorTest::testBadPieceLength() SharedHandle c = e->chunkChecksum; CPPUNIT_ASSERT_EQUAL(std::string("sha256"), c->getAlgo()); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } @@ -515,9 +502,8 @@ void MetalinkProcessorTest::testUnsupportedType_piece() SharedHandle c = e->chunkChecksum; CPPUNIT_ASSERT_EQUAL(std::string("sha256"), c->getAlgo()); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); - delete e; + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } #endif // ENABLE_MESSAGE_DIGEST @@ -541,11 +527,8 @@ void MetalinkProcessorTest::testLargeFileSize() SharedHandle m = proc->parseFromBinaryStream(dw); SharedHandle e = m->entries[0]; CPPUNIT_ASSERT_EQUAL(9223372036854775807ULL, e->getLength()); - } catch(Exception* e) { - std::cerr << *e << std::endl; - std::string m = e->getMsg(); - delete e; - CPPUNIT_FAIL(m); + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } diff --git a/test/MultiDiskAdaptorTest.cc b/test/MultiDiskAdaptorTest.cc index dc23c6a9e..2c5176707 100644 --- a/test/MultiDiskAdaptorTest.cc +++ b/test/MultiDiskAdaptorTest.cc @@ -97,8 +97,8 @@ void MultiDiskAdaptorTest::testWriteData() { readFile("file3.txt", buf, 2); buf[2] = '\0'; CPPUNIT_ASSERT_EQUAL(std::string("12"), std::string(buf)); - } catch(Exception* e) { - CPPUNIT_FAIL(e->getMsg()); + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } diff --git a/test/MultiFileAllocationIteratorTest.cc b/test/MultiFileAllocationIteratorTest.cc index 887366704..b8c808ae4 100644 --- a/test/MultiFileAllocationIteratorTest.cc +++ b/test/MultiFileAllocationIteratorTest.cc @@ -149,11 +149,8 @@ void MultiFileAllocationIteratorTest::testAllocate() CPPUNIT_ASSERT_EQUAL((uint64_t)length5, File(dir+"/"+topDir+"/"+fname5).size()); CPPUNIT_ASSERT_EQUAL(0ULL, File(dir+"/"+topDir+"/"+fname6).size()); - } catch(Exception* e) { - std::cerr << *e << std::endl; - std::string m = e->getMsg(); - delete e; - CPPUNIT_FAIL(m); + } catch(Exception& e) { + CPPUNIT_FAIL(e.stackTrace()); } } diff --git a/test/NetrcTest.cc b/test/NetrcTest.cc index 0da4bab1c..3af084f4f 100644 --- a/test/NetrcTest.cc +++ b/test/NetrcTest.cc @@ -86,9 +86,8 @@ void NetrcTest::testParse_fileNotFound() try { netrc.parse(""); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -106,9 +105,8 @@ void NetrcTest::testParse_malformedNetrc() try { netrc.parse("malformed.netrc"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } diff --git a/test/OptionHandlerTest.cc b/test/OptionHandlerTest.cc index c33c7fe3e..207b90c26 100644 --- a/test/OptionHandlerTest.cc +++ b/test/OptionHandlerTest.cc @@ -71,9 +71,8 @@ void OptionHandlerTest::testBooleanOptionHandler() try { handler.parse(&option, "hello"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -96,9 +95,8 @@ void OptionHandlerTest::testNumberOptionHandler_min() try { handler.parse(&option, "0"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -112,9 +110,8 @@ void OptionHandlerTest::testNumberOptionHandler_max() try { handler.parse(&option, "101"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -129,16 +126,14 @@ void OptionHandlerTest::testNumberOptionHandler_min_max() try { handler.parse(&option, "0"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } try { handler.parse(&option, "101"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -157,22 +152,19 @@ void OptionHandlerTest::testUnitNumberOptionHandler() try { handler.parse(&option, "K"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { handler.parse(&option, "M"); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { handler.parse(&option, ""); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } } @@ -187,9 +179,8 @@ void OptionHandlerTest::testParameterOptionHandler_1argInit() try { handler.parse(&option, "value3"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -206,9 +197,8 @@ void OptionHandlerTest::testParameterOptionHandler_2argsInit() try { handler.parse(&option, "value3"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -229,9 +219,8 @@ void OptionHandlerTest::testParameterOptionHandler_listInit() try { handler.parse(&option, "value3"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -266,9 +255,8 @@ void OptionHandlerTest::testFloatNumberOptionHandler_min() try { handler.parse(&option, "-0.1"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -281,9 +269,8 @@ void OptionHandlerTest::testFloatNumberOptionHandler_max() try { handler.parse(&option, "10.1"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -298,16 +285,14 @@ void OptionHandlerTest::testFloatNumberOptionHandler_min_max() try { handler.parse(&option, "-0.1"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } try { handler.parse(&option, "10.1"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } @@ -344,37 +329,32 @@ void OptionHandlerTest::testHttpProxyOptionHandler() try { handler.parse(&option, "bar"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } try { handler.parse(&option, "bar:"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } try { handler.parse(&option, ":"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } try { handler.parse(&option, ":80"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } try { handler.parse(&option, "foo:bar"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } diff --git a/test/ParameterizedStringParserTest.cc b/test/ParameterizedStringParserTest.cc index 4d0cd79c5..4b835ed6c 100644 --- a/test/ParameterizedStringParserTest.cc +++ b/test/ParameterizedStringParserTest.cc @@ -70,9 +70,8 @@ void ParameterizedStringParserTest::testParse_select_empty() try { SharedHandle ls = ParameterizedStringParser().parse("{}"); CPPUNIT_FAIL("exception must be thrown."); - } catch(FatalException* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(FatalException& e) { + std::cerr << e.stackTrace() << std::endl; } catch(...) { CPPUNIT_FAIL("unexpected exception thrown."); } @@ -83,9 +82,8 @@ void ParameterizedStringParserTest::testParse_select_missingParen() try { SharedHandle ls = ParameterizedStringParser().parse("{alpha"); CPPUNIT_FAIL("exception must be thrown."); - } catch(FatalException* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(FatalException& e) { + std::cerr << e.stackTrace() << std::endl; } catch(...) { CPPUNIT_FAIL("unexpected exception was thrown."); } @@ -139,9 +137,8 @@ void ParameterizedStringParserTest::testParse_loop_empty() try { SharedHandle ls = ParameterizedStringParser().parse("[]"); CPPUNIT_FAIL("exception must be thrown."); - } catch(FatalException* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(FatalException& e) { + std::cerr << e.stackTrace() << std::endl; } catch(...) { CPPUNIT_FAIL("unexpected exception was thrown."); } @@ -152,9 +149,8 @@ void ParameterizedStringParserTest::testParse_loop_missingParen() try { SharedHandle ls = ParameterizedStringParser().parse("["); CPPUNIT_FAIL("exception must be thrown."); - } catch(FatalException* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(FatalException& e) { + std::cerr << e.stackTrace() << std::endl; } catch(...) { CPPUNIT_FAIL("unexpected exception was thrown."); } @@ -165,9 +161,8 @@ void ParameterizedStringParserTest::testParse_loop_missingStep() try { SharedHandle ls = ParameterizedStringParser().parse("[1-10:]"); CPPUNIT_FAIL("exception must be thrown."); - } catch(FatalException* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(FatalException& e) { + std::cerr << e.stackTrace() << std::endl; } catch(...) { CPPUNIT_FAIL("unexpected exception was thrown."); } @@ -178,9 +173,8 @@ void ParameterizedStringParserTest::testParse_loop_missingRange() try { SharedHandle ls = ParameterizedStringParser().parse("[1-]"); CPPUNIT_FAIL("exception must be thrown."); - } catch(FatalException* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(FatalException& e) { + std::cerr << e.stackTrace() << std::endl; } catch(...) { CPPUNIT_FAIL("unexpected exception was thrown."); } @@ -202,9 +196,8 @@ void ParameterizedStringParserTest::testParse_loop_mixedChar() try { ParameterizedStringParser().parse("[1-z:2]"); CPPUNIT_FAIL("exception must be thrown."); - } catch(FatalException* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(FatalException& e) { + std::cerr << e.stackTrace() << std::endl; } catch(...) { CPPUNIT_FAIL("FatalException must be thrown."); } @@ -215,9 +208,8 @@ void ParameterizedStringParserTest::testParse_loop_mixedCase() try { ParameterizedStringParser().parse("[a-Z:2]"); CPPUNIT_FAIL("exception must be thrown."); - } catch(FatalException* e) { - std::cerr << e->getMsg() << std::endl; - delete e; + } catch(FatalException& e) { + std::cerr << e.stackTrace() << std::endl; } catch(...) { CPPUNIT_FAIL("FatalException must be thrown."); } diff --git a/test/SocketCoreTest.cc b/test/SocketCoreTest.cc index da0862ccf..7a66e82fb 100644 --- a/test/SocketCoreTest.cc +++ b/test/SocketCoreTest.cc @@ -53,9 +53,8 @@ void SocketCoreTest::testWriteAndReadDatagram() readbuffer[rlength] = '\0'; CPPUNIT_ASSERT_EQUAL(message2, std::string(readbuffer)); } - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; CPPUNIT_FAIL("exception thrown"); } } diff --git a/test/StringFormatTest.cc b/test/StringFormatTest.cc index 642836a5c..8e7e36bea 100644 --- a/test/StringFormatTest.cc +++ b/test/StringFormatTest.cc @@ -9,27 +9,27 @@ namespace aria2 { class StringFormatTest:public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(StringFormatTest); - CPPUNIT_TEST(testGetString); + CPPUNIT_TEST(testStr); CPPUNIT_TEST_SUITE_END(); public: void setUp() {} void tearDown() {} - void testGetString(); + void testStr(); }; CPPUNIT_TEST_SUITE_REGISTRATION(StringFormatTest); -void StringFormatTest::testGetString() +void StringFormatTest::testStr() { int major = 1; int minor = 0; int release = 7; StringFormat fmt("aria2-%d.%d.%d-%s", major, minor, release, "beta"); - CPPUNIT_ASSERT_EQUAL(std::string("aria2-1.0.7-beta"), fmt.toString()); + CPPUNIT_ASSERT_EQUAL(std::string("aria2-1.0.7-beta"), fmt.str()); } } // namespace aria2 diff --git a/test/UTPexExtensionMessageTest.cc b/test/UTPexExtensionMessageTest.cc index ff6135e0e..480e9d8a7 100644 --- a/test/UTPexExtensionMessageTest.cc +++ b/test/UTPexExtensionMessageTest.cc @@ -190,9 +190,8 @@ void UTPexExtensionMessageTest::testCreate() reinterpret_cast(in.c_str()), in.size()); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e << std::endl; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace() << std::endl; } } diff --git a/test/UtilTest.cc b/test/UtilTest.cc index a370b759d..795a3c341 100644 --- a/test/UtilTest.cc +++ b/test/UtilTest.cc @@ -321,37 +321,32 @@ void UtilTest::testGetRealSize() try { Util::getRealSize(""); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::getRealSize("foo"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::getRealSize("-1"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::getRealSize("9223372036854775807K"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::getRealSize("9223372036854775807M"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } } @@ -444,9 +439,8 @@ void UtilTest::testMkdirs() try { Util::mkdirs(file); CPPUNIT_FAIL("exception must be thrown."); - } catch(DlAbortEx* ex) { - std::cerr << ex->getMsg() << std::endl; - delete ex; + } catch(DlAbortEx& ex) { + std::cerr << ex.stackTrace() << std::endl; } } @@ -493,37 +487,32 @@ void UtilTest::testParseIntRange_invalidRange() try { IntSequence seq = Util::parseIntRange("-1"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { IntSequence seq = Util::parseIntRange("2147483648"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { IntSequence seq = Util::parseIntRange("2147483647-2147483648"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { IntSequence seq = Util::parseIntRange("1-2x"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { IntSequence seq = Util::parseIntRange("3x-4"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } } @@ -534,30 +523,26 @@ void UtilTest::testParseInt() try { Util::parseInt("2147483648"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::parseInt("-2147483649"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::parseInt("12x"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::parseInt(""); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } } @@ -567,16 +552,14 @@ void UtilTest::testParseUInt() try { Util::parseUInt("-1"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::parseUInt("4294967296"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } } @@ -588,30 +571,26 @@ void UtilTest::testParseLLInt() try { Util::parseLLInt("9223372036854775808"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::parseLLInt("-9223372036854775809"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::parseLLInt("12x"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::parseLLInt(""); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } } @@ -622,16 +601,14 @@ void UtilTest::testParseULLInt() try { Util::parseUInt("-1"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } try { Util::parseLLInt("18446744073709551616"); CPPUNIT_FAIL("exception must be thrown."); - } catch(Exception* e) { - std::cerr << *e; - delete e; + } catch(Exception& e) { + std::cerr << e.stackTrace(); } }