Commit message: Change BasicIO read/write methods to use size_t
CVE: CVE-2019-13504
Vulnerability description: There is an out-of-bounds read in Exiv2::MrwImage::readMetadata in mrwimage.cpp in Exiv2 through 0.27.2.

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffReader::readTiffEntry(TiffEntryBase* object)
    {
        assert(object != 0);

        byte* p = object->start();
        assert(p >= pData_);

        if (p + 12 > pLast_) {
#ifndef SUPPRESS_WARNINGS
            EXV_ERROR << "Entry in directory " << groupName(object->group())
                      << "requests access to memory beyond the data buffer. "
                      << "Skipping entry.\n";
#endif
            return;
        }
        // Component already has tag
        p += 2;
        TiffType tiffType = getUShort(p, byteOrder());
        TypeId typeId = toTypeId(tiffType, object->tag(), object->group());
        long typeSize = TypeInfo::typeSize(typeId);
        if (0 == typeSize) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Directory " << groupName(object->group())
                        << ", entry 0x" << std::setw(4)
                        << std::setfill('0') << std::hex << object->tag()
                        << " has unknown Exif (TIFF) type " << std::dec << tiffType
                        << "; setting type size 1.\n";
#endif
            typeSize = 1;
        }
        p += 2;
        uint32_t count = getULong(p, byteOrder());
        if (count >= 0x10000000) {
#ifndef SUPPRESS_WARNINGS
            EXV_ERROR << "Directory " << groupName(object->group())
                      << ", entry 0x" << std::setw(4)
                      << std::setfill('0') << std::hex << object->tag()
                      << " has invalid size "
                      << std::dec << count << "*" << typeSize
                      << "; skipping entry.\n";
#endif
            return;
        }
        p += 4;
        uint32_t isize= 0; // size of Exif.Sony1.PreviewImage

        if (count > std::numeric_limits<uint32_t>::max() / typeSize) {
            throw Error(kerArithmeticOverflow);
        }
        uint32_t size = typeSize * count;
        uint32_t offset = getLong(p, byteOrder());
        byte* pData = p;
        if (   size > 4
            && (   baseOffset() + offset >= size_
                || static_cast<int32_t>(baseOffset()) + offset <= 0)) {
                // #1143
                if ( object->tag() == 0x2001 && std::string(groupName(object->group())) == "Sony1" ) {
                    isize=size;
                } else {
#ifndef SUPPRESS_WARNINGS
            EXV_ERROR << "Offset of directory " << groupName(object->group())
                      << ", entry 0x" << std::setw(4)
                      << std::setfill('0') << std::hex << object->tag()
                      << " is out of bounds: "
                      << "Offset = 0x" << std::setw(8)
                      << std::setfill('0') << std::hex << offset
                      << "; truncating the entry\n";
#endif
                }
                size = 0;
        }
        if (size > 4) {
            // setting pData to pData_ + baseOffset() + offset can result in pData pointing to invalid memory,
            // as offset can be arbitrarily large
            if ((static_cast<uintptr_t>(baseOffset()) > std::numeric_limits<uintptr_t>::max() - static_cast<uintptr_t>(offset))
             || (static_cast<uintptr_t>(baseOffset() + offset) > std::numeric_limits<uintptr_t>::max() - reinterpret_cast<uintptr_t>(pData_)))
            {
                throw Error(kerCorruptedMetadata); // #562 don't throw kerArithmeticOverflow
            }
            if (pData_ + static_cast<uintptr_t>(baseOffset()) + static_cast<uintptr_t>(offset) > pLast_) {
                throw Error(kerCorruptedMetadata);
            }
            pData = const_cast<byte*>(pData_) + baseOffset() + offset;

        // check for size being invalid
            if (size > static_cast<uint32_t>(pLast_ - pData)) {
#ifndef SUPPRESS_WARNINGS
                EXV_ERROR << "Upper boundary of data for "
                          << "directory " << groupName(object->group())
                          << ", entry 0x" << std::setw(4)
                          << std::setfill('0') << std::hex << object->tag()
                          << " is out of bounds: "
                          << "Offset = 0x" << std::setw(8)
                          << std::setfill('0') << std::hex << offset
                          << ", size = " << std::dec << size
                          << ", exceeds buffer size by "
                          // cast to make MSVC happy
                          << static_cast<uint32_t>(pData + size - pLast_)
                          << " Bytes; truncating the entry\n";
#endif
                size = 0;
            }
        }
        Value::UniquePtr v = Value::create(typeId);
        enforce(v.get() != nullptr, kerCorruptedMetadata);
        if ( !isize ) {
            v->read(pData, size, byteOrder());
        } else {
            // #1143 Write a "hollow" buffer for the preview image
            //       Sadly: we don't know the exact location of the image in the source (it's near offset)
            //       And neither TiffReader nor TiffEntryBase have access to the BasicIo object being processed
            byte* buffer = (byte*) ::malloc(isize);
            ::memset(buffer,0,isize);
            v->read(buffer,isize, byteOrder());
            ::free(buffer);
        }

        object->setValue(std::move(v));
        object->setData(pData, size);
        object->setOffset(offset);
        object->setIdx(nextIdx(object->group()));

    } // TiffReader::readTiffEntry

Project: exiv2
File: types.cpp

    uint16_t getUShort(const byte* buf, ByteOrder byteOrder)
    {
        return getUShort(makeSliceUntil(buf, 2), byteOrder);
    }

Project: exiv2
File: convert.cpp

        bool operator==(const std::pair<const char*, const char*> &fromTo) const
            { return 0 == strcmp(from_, fromTo.first) && 0 == strcmp(to_, fromTo.second); }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::visitDataEntry(TiffDataEntry* object)
    {
        encodeTiffComponent(object);
    }

Project: exiv2
File: convert.cpp

    void copyExifToXmp(const ExifData& exifData, XmpData& xmpData)
    {
        Converter converter(const_cast<ExifData&>(exifData), xmpData);
        converter.cnvToXmp();
    }

Project: exiv2
File: actions.cpp

    std::unique_ptr<Adjust> Adjust::clone() const
    {
        return std::unique_ptr<Adjust>(clone_());
    }

Project: exiv2
File: convert.cpp

    bool mb2wc(UINT cp, std::string& str)
    {
        if (str.empty())
            return true;
        int len = MultiByteToWideChar(cp, 0, str.c_str(), (int)str.size(), 0, 0);
        if (len == 0) {
#ifdef DEBUG
            EXV_DEBUG << "mb2wc: Failed to determine required size of output buffer.\n";
#endif
            return false;
        }
        std::vector<std::string::value_type> out;
        out.reserve(len * 2);
        int ret = MultiByteToWideChar(cp, 0, str.c_str(), (int)str.size(), (LPWSTR)out.data(), len * 2);
        if (ret == 0) {
#ifdef DEBUG
            EXV_DEBUG << "mb2wc: Failed to convert the input string to a wide character string.\n";
#endif
            return false;
        }
        str.assign(out.data(), static_cast<size_t>(len) * 2);
        return true;
    }

Project: exiv2
File: makernote_int.cpp

    Casio2MnHeader::~Casio2MnHeader()
    {
    }

Project: exiv2
File: makernote_int.cpp

    uint32_t FujiMnHeader::ifdOffset() const
    {
        return start_;
    }

Project: exiv2
File: pngimage.cpp

    void PngImage::doWriteMetadata(BasicIo& outIo)
    {
        if (!io_->isopen())
            throw Error(kerInputDataReadFailed);
        if (!outIo.isopen())
            throw Error(kerImageWriteFailed);

#ifdef DEBUG
        std::cout << "Exiv2::PngImage::doWriteMetadata: Writing PNG file " << io_->path() << "\n";
        std::cout << "Exiv2::PngImage::doWriteMetadata: tmp file created " << outIo.path() << "\n";
#endif

        if (!isPngType(*io_, true)) {
            throw Error(kerNoImageInInputData);
        }

        // Write PNG Signature.
        if (outIo.write(pngSignature, 8) != 8)
            throw Error(kerImageWriteFailed);

        DataBuf cheaderBuf(8);  // Chunk header : 4 bytes (data size) + 4 bytes (chunk type).

        while (!io_->eof()) {
            // Read chunk header.

            std::memset(cheaderBuf.pData_, 0x00, cheaderBuf.size_);
            size_t bufRead = io_->read(cheaderBuf.pData_, cheaderBuf.size_);
            if (io_->error())
                throw Error(kerFailedToReadImageData);
            if (bufRead != cheaderBuf.size_)
                throw Error(kerInputDataReadFailed);

            // Decode chunk data length.

            uint32_t dataOffset = getULong(cheaderBuf.pData_, bigEndian);
            if (dataOffset > 0x7FFFFFFF)
                throw Exiv2::Error(kerFailedToReadImageData);

            // Read whole chunk : Chunk header + Chunk data (not fixed size - can be null) + CRC (4 bytes).

            DataBuf chunkBuf(8 + dataOffset + 4);           // Chunk header (8 bytes) + Chunk data + CRC (4 bytes).
            memcpy(chunkBuf.pData_, cheaderBuf.pData_, 8);  // Copy header.
            bufRead = io_->read(chunkBuf.pData_ + 8, dataOffset + 4);  // Extract chunk data + CRC
            if (io_->error())
                throw Error(kerFailedToReadImageData);
            if (bufRead != (long)(dataOffset + 4))
                throw Error(kerInputDataReadFailed);

            char szChunk[5];
            memcpy(szChunk, cheaderBuf.pData_ + 4, 4);
            szChunk[4] = 0;

            if (!memcmp(cheaderBuf.pData_ + 4, "IEND", 4)) {
                // Last chunk found: we write it and done.
#ifdef DEBUG
                std::cout << "Exiv2::PngImage::doWriteMetadata: Write IEND chunk (length: " << dataOffset << ")\n";
#endif
                if (outIo.write(chunkBuf.pData_, chunkBuf.size_) != chunkBuf.size_)
                    throw Error(kerImageWriteFailed);
                return;
            } else if (!memcmp(cheaderBuf.pData_ + 4, "IHDR", 4)) {
#ifdef DEBUG
                std::cout << "Exiv2::PngImage::doWriteMetadata: Write IHDR chunk (length: " << dataOffset << ")\n";
#endif
                if (outIo.write(chunkBuf.pData_, chunkBuf.size_) != chunkBuf.size_)
                    throw Error(kerImageWriteFailed);

                // Write all updated metadata here, just after IHDR.
                if (!comment_.empty()) {
                    // Update Comment data to a new PNG chunk
                    std::string chunk = PngChunk::makeMetadataChunk(comment_, mdComment);
                    if (outIo.write((const byte*)chunk.data(), chunk.size()) != chunk.size()) {
                        throw Error(kerImageWriteFailed);
                    }
                }

                if (exifData_.count() > 0) {
                    // Update Exif data to a new PNG chunk
                    Blob blob;
                    ExifParser::encode(blob, littleEndian, exifData_);
                    if (blob.size() > 0) {
                        const std::string exifHeader{"Exif\0\0", 6};
                        std::string rawExif = exifHeader + std::string((const char*)blob.data(), blob.size());
                        std::string chunk = PngChunk::makeMetadataChunk(rawExif, mdExif);
                        if (outIo.write((const byte*)chunk.data(), chunk.size()) != chunk.size()) {
                            throw Error(kerImageWriteFailed);
                        }
                    }
                }

                if (iptcData_.count() > 0) {
                    // Update IPTC data to a new PNG chunk
                    DataBuf newPsData = Photoshop::setIptcIrb(0, 0, iptcData_);
                    if (newPsData.size_ > 0) {
                        std::string rawIptc((const char*)newPsData.pData_, newPsData.size_);
                        std::string chunk = PngChunk::makeMetadataChunk(rawIptc, mdIptc);
                        if (outIo.write((const byte*)chunk.data(), chunk.size()) != chunk.size()) {
                            throw Error(kerImageWriteFailed);
                        }
                    }
                }

                if (iccProfileDefined()) {
                    DataBuf compressed;
                    if (zlibToCompressed(iccProfile_.pData_, (long)iccProfile_.size_, compressed)) {
                        const byte* nullComp = (const byte*)"\0\0";
                        const byte* type = (const byte*)"iCCP";
                        const uint32_t nameLength = static_cast<uint32_t>(profileName_.size());
                        const uint32_t chunkLength = nameLength + 2 + (uint32_t)compressed.size_;
                        byte length[4];
                        ul2Data(length, chunkLength, bigEndian);

                        // calculate CRC
                        uLong tmp = crc32(0L, Z_NULL, 0);
                        tmp = crc32(tmp, (const Bytef*)type, 4);
                        tmp = crc32(tmp, (const Bytef*)profileName_.data(), nameLength);
                        tmp = crc32(tmp, (const Bytef*)nullComp, 2);
                        tmp = crc32(tmp, (const Bytef*)compressed.pData_, (uInt)compressed.size_);
                        byte crc[4];
                        ul2Data(crc, tmp, bigEndian);

                        if (outIo.write(length, 4) != 4 || outIo.write(type, 4) != 4 ||
                            outIo.write(reinterpret_cast<const byte*>(profileName_.data()), nameLength) != nameLength ||
                            outIo.write(nullComp, 2) != 2 ||
                            outIo.write(compressed.pData_, compressed.size_) != compressed.size_ ||
                            outIo.write(crc, 4) != 4) {
                            throw Error(kerImageWriteFailed);
                        }
#ifdef DEBUG
                        std::cout << "Exiv2::PngImage::doWriteMetadata: build iCCP"
                                  << " chunk (length: " << compressed.size_ + chunkLength << ")" << std::endl;
#endif
                    }
                }

                if (writeXmpFromPacket() == false) {
                    if (XmpParser::encode(xmpPacket_, xmpData_) > 1) {
#ifndef SUPPRESS_WARNINGS
                        EXV_ERROR << "Failed to encode XMP metadata.\n";
#endif
                    }
                }
                if (xmpPacket_.size() > 0) {
                    // Update XMP data to a new PNG chunk
                    std::string chunk = PngChunk::makeMetadataChunk(xmpPacket_, mdXmp);
                    if (outIo.write((const byte*)chunk.data(), chunk.size()) != chunk.size()) {
                        throw Error(kerImageWriteFailed);
                    }
                }
            } else if (!memcmp(cheaderBuf.pData_ + 4, "tEXt", 4) || !memcmp(cheaderBuf.pData_ + 4, "zTXt", 4) ||
                       !memcmp(cheaderBuf.pData_ + 4, "iTXt", 4) || !memcmp(cheaderBuf.pData_ + 4, "iCCP", 4)) {
                DataBuf key = PngChunk::keyTXTChunk(chunkBuf, true);
                if (compare("Raw profile type exif", key, 21) || compare("Raw profile type APP1", key, 21) ||
                    compare("Raw profile type iptc", key, 21) || compare("Raw profile type xmp", key, 20) ||
                    compare("XML:com.adobe.xmp", key, 17) || compare("icc", key, 3) ||  // see test/data/imagemagick.png
                    compare("ICC", key, 3) || compare("Description", key, 11)) {
#ifdef DEBUG
                    std::cout << "Exiv2::PngImage::doWriteMetadata: strip " << szChunk
                              << " chunk (length: " << dataOffset << ")" << std::endl;
#endif
                } else {
#ifdef DEBUG
                    std::cout << "Exiv2::PngImage::doWriteMetadata: write " << szChunk
                              << " chunk (length: " << dataOffset << ")" << std::endl;
#endif
                    if (outIo.write(chunkBuf.pData_, chunkBuf.size_) != chunkBuf.size_)
                        throw Error(kerImageWriteFailed);
                }
            } else {
                // Write all others chunk as well.
#ifdef DEBUG
                std::cout << "Exiv2::PngImage::doWriteMetadata:  copy " << szChunk << " chunk (length: " << dataOffset
                          << ")" << std::endl;
#endif
                if (outIo.write(chunkBuf.pData_, chunkBuf.size_) != chunkBuf.size_)
                    throw Error(kerImageWriteFailed);
            }
        }

    }  // PngImage::doWriteMetadata

Project: exiv2
File: tiffcomposite_int.cpp

    TiffBinaryElement* TiffBinaryElement::doClone() const
    {
        return new TiffBinaryElement(*this);
    }

Project: exiv2
File: tiff-test.cpp

int main(int argc, char* const argv[])
try {
    if (argc != 2) {
        std::cout << "Usage: " << argv[0] << " file\n";
        return 1;
    }

    const char* path = argv[1];
    mini1(path);
    mini9(path);

    return 0;
}

Project: exiv2
File: jpgimage.cpp

    void JpegBase::writeMetadata()
    {
        if (io_->open() != 0) {
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        }
        IoCloser closer(*io_);
        BasicIo::UniquePtr tempIo(new MemIo);
        assert (tempIo.get() != 0);

        doWriteMetadata(*tempIo); // may throw
        io_->close();
        io_->transfer(*tempIo); // may throw
    } // JpegBase::writeMetadata

Project: exiv2
File: exif.cpp

    Exifdatum& Exifdatum::operator=(const uint32_t& value)
    {
        return Exiv2::setValue(*this, value);
    }

Project: exiv2
File: xmp.cpp

    const char* Xmpdatum::familyName() const
    {
        return p_->key_.get() == 0 ? "" : p_->key_->familyName();
    }

Project: exiv2
File: exif.cpp

    long Exifdatum::toLong(long n) const
    {
        return value_.get() == 0 ? -1 : value_->toLong(n);
    }

Project: exiv2
File: xmpsidecar.cpp

    bool isXmpType(BasicIo& iIo, bool advance)
    {
        /*
          Check if the file starts with an optional XML declaration followed by
          either an XMP header (<?xpacket ... ?>) or an <x:xmpmeta> element.

          In addition, in order for empty XmpSidecar objects as created by
          Exiv2 to pass the test, just an XML header is also considered ok.
         */
        const int32_t len = 80;
        byte buf[len];
        iIo.read(buf, xmlHdrCnt + 1);
        if (   iIo.eof()
            && 0 == strncmp(reinterpret_cast<const char*>(buf), xmlHeader, xmlHdrCnt)) {
            return true;
        }
        if (iIo.error() || iIo.eof()) {
            return false;
        }
        iIo.read(buf + xmlHdrCnt + 1, len - xmlHdrCnt - 1);
        if (iIo.error() || iIo.eof()) {
            return false;
        }
        // Skip leading BOM
        int32_t start = 0;
        if (0 == strncmp(reinterpret_cast<const char*>(buf), "\xef\xbb\xbf", 3)) {
            start = 3;
        }
        bool rc = false;
        std::string head(reinterpret_cast<const char*>(buf + start), len - start);
        if (head.substr(0, 5)  == "<?xml") {
            // Forward to the next tag
            for (unsigned i = 5; i < head.size(); ++i) {
                if (head[i] == '<') {
                    head = head.substr(i);
                    break;
                }
            }
        }
        if (   head.size() > 9
            && (   head.substr(0, 9)  == "<?xpacket"
                || head.substr(0, 10) == "<x:xmpmeta")) {
            rc = true;
        }
        if (!advance || !rc) {
            iIo.seek(-(len - start), BasicIo::cur); // Swallow the BOM
        }
        return rc;

    }

Project: exiv2
File: makernote_int.cpp

    SonyMnHeader::~SonyMnHeader()
    {
    }

Project: exiv2
File: actions.cpp

    int Print::printTag(const Exiv2::ExifData& exifData, EasyAccessFct easyAccessFct, const std::string& label) const
    {
        int rc = 0;
        if (!label.empty()) {
            printLabel(label);
        }
        auto md = easyAccessFct(exifData);
        if (md != exifData.end()) {
            md->write(std::cout, &exifData);
            rc = 1;
        }
        if (!label.empty())
            std::cout << std::endl;
        return rc;
    }

Project: exiv2
File: types.cpp

    std::string ws2s(const std::wstring& s)
    {
        int len;
        int slength = (int)s.length() + 1;
        len = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0);
        char* buf = new char[len];
        WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, buf, len, 0, 0);
        std::string r(buf);
        delete[] buf;
        return r;
    }

Project: exiv2
File: exif.cpp

    long sumToLong(const Exiv2::Exifdatum& md)
    {
        long sum = 0;
        for (int i = 0; i < md.count(); ++i) {
            sum += md.toLong(i);
        }
        return sum;
    }

Project: exiv2
File: actions.cpp

    Rename* Rename::clone_() const
    {
        return new Rename(*this);
    }

Project: exiv2
File: basicio.cpp

    void XPathIo::ReadStdin() {
        if (isatty(fileno(stdin)))
            throw Error(kerInvalidIccProfile);

#ifdef _O_BINARY
        // convert stdin to binary
        if (_setmode(_fileno(stdin), _O_BINARY) == -1)
            throw Error(kerInvalidXMP);
#endif

        char readBuf[100*1024];
        std::streamsize readBufSize = 0;
        do {
            std::cin.read(readBuf, sizeof(readBuf));
            readBufSize = std::cin.gcount();
            if (readBufSize > 0) {
                write((byte*)readBuf, (long)readBufSize);
            }
        } while(readBufSize);
    }

Project: exiv2
File: psdimage.cpp

    std::string PsdImage::mimeType() const
    {
        return "image/x-photoshop";
    }

Project: exiv2
File: iptc.cpp

    Iptcdatum& Iptcdatum::operator=(const Value& value)
    {
        setValue(&value);
        return *this;
    }

Project: exiv2
File: convert.cpp

    void copyXmpToExif(const XmpData& xmpData, ExifData& exifData)
    {
        Converter converter(exifData, const_cast<XmpData&>(xmpData));
        converter.cnvFromXmp();
    }

Project: exiv2
File: value.cpp

    float DataValue::toFloat(long n) const
    {
        ok_ = true;
        return value_[n];
    }

Project: exiv2
File: tiffcomposite_int.cpp

    void TiffMnEntry::doEncode(TiffEncoder& encoder, const Exifdatum* datum)
    {
        encoder.encodeMnEntry(this, datum);
    } // TiffMnEntry::doEncode

Project: exiv2
File: value.cpp

    AsciiValue::AsciiValue()
        : StringValueBase(asciiString)
    {
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffDataEntry* TiffDataEntry::doClone() const
    {
        return new TiffDataEntry(*this);
    }

Project: exiv2
File: convert.cpp

    void Converter::cnvXmpArray(const char* from, const char* to)
    {
        if (!prepareExifTarget(to)) return;
        Exiv2::XmpData::iterator pos = xmpData_->findKey(XmpKey(from));
        if (pos == xmpData_->end()) return;
        std::ostringstream array;
        for (int i = 0; i < pos->count(); ++i) {
            std::string value = pos->toString(i);
            if (!pos->value().ok()) {
#ifndef SUPPRESS_WARNINGS
                EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
                return;
            }
            array << value;
            if (i != pos->count() - 1) array << " ";
        }
        (*exifData_)[to] = array.str();
        if (erase_) xmpData_->erase(pos);
    }

Project: exiv2
File: makernote_int.cpp

    uint32_t FujiMnHeader::baseOffset(uint32_t mnOffset) const
    {
        return mnOffset;
    }

Project: exiv2
File: image.cpp

    void Image::printStructure(std::ostream&, PrintStructureOption,int /*depth*/)
    {
        throw Error(kerUnsupportedImageType, io_->path());
    }

Project: exiv2
File: pngimage.cpp

    void PngImage::printStructure(std::ostream& out, PrintStructureOption option, int depth)
    {
        if (io_->open() != 0) {
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        }
        if (!isPngType(*io_, true)) {
            throw Error(kerNotAnImage, "PNG");
        }

        char chType[5];
        chType[0] = 0;
        chType[4] = 0;

        if (option == kpsBasic || option == kpsXMP || option == kpsIccProfile || option == kpsRecursive) {
            const std::string xmpKey = "XML:com.adobe.xmp";
            const std::string exifKey = "Raw profile type exif";
            const std::string app1Key = "Raw profile type APP1";
            const std::string iptcKey = "Raw profile type iptc";
            const std::string iccKey = "icc";
            const std::string softKey = "Software";
            const std::string commKey = "Comment";
            const std::string descKey = "Description";

            bool bPrint = option == kpsBasic || option == kpsRecursive;
            if (bPrint) {
                out << "STRUCTURE OF PNG FILE: " << io_->path() << std::endl;
                out << " address | chunk |  length | data                           | checksum" << std::endl;
            }

            const long imgSize = (long)io_->size();
            DataBuf cheaderBuf(8);

            while (!io_->eof() && ::strcmp(chType, "IEND")) {
                size_t address = io_->tell();

                std::memset(cheaderBuf.pData_, 0x0, cheaderBuf.size_);
                size_t bufRead = io_->read(cheaderBuf.pData_, cheaderBuf.size_);
                if (io_->error())
                    throw Error(kerFailedToReadImageData);
                if (bufRead != cheaderBuf.size_)
                    throw Error(kerInputDataReadFailed);

                // Decode chunk data length.
                const uint32_t dataOffset = Exiv2::getULong(cheaderBuf.pData_, Exiv2::bigEndian);
                for (int i = 4; i < 8; i++) {
                    chType[i - 4] = cheaderBuf.pData_[i];
                }

                // test that we haven't hit EOF, or wanting to read excessive data
                long restore = io_->tell();
                if (restore == -1 || dataOffset > uint32_t(0x7FFFFFFF) ||
                    static_cast<long>(dataOffset) > imgSize - restore) {
                    throw Exiv2::Error(kerFailedToReadImageData);
                }

                DataBuf   buff(dataOffset);
                bufRead = io_->read(buff.pData_,dataOffset);
                enforce(bufRead == static_cast<long>(dataOffset), kerFailedToReadImageData);
                io_->seek(restore, BasicIo::beg);

                // format output
                const int iMax = 30;
                const uint32_t blen = dataOffset > iMax ? iMax : dataOffset;
                std::string dataString = "";
                // if blen == 0 => slice construction fails
                if (blen > 0) {
                    std::stringstream ss;
                    ss << Internal::binaryToString(makeSlice(buff, 0, blen));
                    dataString = ss.str();
                }
                while (dataString.size() < iMax)
                    dataString += ' ';
                dataString = dataString.substr(0, iMax);

                if (bPrint) {
                    io_->seek(dataOffset, BasicIo::cur);  // jump to checksum
                    byte checksum[4];
                    bufRead = io_->read(checksum,4);
                    enforce(bufRead == 4, kerFailedToReadImageData);
                    io_->seek(restore, BasicIo::beg)   ;// restore file pointer

                    out << Internal::stringFormat("%8d | %-5s |%8d | ", (uint32_t)address, chType, dataOffset)
                        << dataString
                        << Internal::stringFormat(" | 0x%02x%02x%02x%02x", checksum[0], checksum[1], checksum[2],
                                                  checksum[3])
                        << std::endl;
                }

                // chunk type
                bool tEXt = std::strcmp(chType, "tEXt") == 0;
                bool zTXt = std::strcmp(chType, "zTXt") == 0;
                bool iCCP = std::strcmp(chType, "iCCP") == 0;
                bool iTXt = std::strcmp(chType, "iTXt") == 0;

                // for XMP, ICC etc: read and format data
                bool bXMP = option == kpsXMP && findi(dataString, xmpKey) == 0;
                bool bICC = option == kpsIccProfile && findi(dataString, iccKey) == 0;
                bool bExif =
                    option == kpsRecursive && (findi(dataString, exifKey) == 0 || findi(dataString, app1Key) == 0);
                bool bIptc = option == kpsRecursive && findi(dataString, iptcKey) == 0;
                bool bSoft = option == kpsRecursive && findi(dataString, softKey) == 0;
                bool bComm = option == kpsRecursive && findi(dataString, commKey) == 0;
                bool bDesc = option == kpsRecursive && findi(dataString, descKey) == 0;
                bool bDump = bXMP || bICC || bExif || bIptc || bSoft || bComm || bDesc;

                if (bDump) {
                    DataBuf dataBuf;
                    byte* data = new byte[dataOffset + 1];
                    data[dataOffset] = 0;
                    bufRead = io_->read(data,dataOffset);
                    enforce(bufRead == static_cast<long>(dataOffset), kerFailedToReadImageData);
                    io_->seek(restore, BasicIo::beg);
                    uint32_t  name_l = (uint32_t) std::strlen((const char*)data)+1; // leading string length
                    enforce(name_l <= dataOffset, kerCorruptedMetadata);

                    uint32_t  start  = name_l;

                    // decode the chunk
                    bool bGood = false;
                    if (tEXt) {
                        bGood = tEXtToDataBuf(data + name_l, dataOffset - name_l, dataBuf);
                    }
                    if (zTXt || iCCP) {
                        bGood = zlibToDataBuf(data + name_l + 1, dataOffset - name_l - 1,
                                              dataBuf);  // +1 = 'compressed' flag
                    }
                    if (iTXt) {
                        bGood = (start + 3) < dataOffset;  // good if not a nul chunk
                    }

                    // format is content dependent
                    if (bGood) {
                        bool bLF = false;
                        if (bXMP) {
                            while (!data[start] && start < dataOffset)
                                start++;          // skip leading nul bytes
                            out << data + start;  // output the xmp
                        }

                        if (bExif || bIptc) {
                            DataBuf parsedBuf = PngChunk::readRawProfile(dataBuf, tEXt);
#if DEBUG
                            std::cerr << Exiv2::Internal::binaryToString(parsedBuf.pData_,
                                                                         parsedBuf.size_ > 50 ? 50 : parsedBuf.size_, 0)
                                      << std::endl;
#endif
                            if (parsedBuf.size_) {
                                if (bExif) {
                                    // create memio object with the data, then print the structure
                                    BasicIo::UniquePtr p =
                                        BasicIo::UniquePtr(new MemIo(parsedBuf.pData_ + 6, parsedBuf.size_ - 6));
                                    printTiffStructure(*p, out, option, depth);
                                }
                                if (bIptc) {
                                    IptcData::printStructure(out, makeSlice(parsedBuf.pData_, 0, parsedBuf.size_),
                                                             depth);
                                }
                            }
                        }

                        if (bSoft && dataBuf.size_ > 0) {
                            DataBuf s(dataBuf.size_ + 1);                     // allocate buffer with an extra byte
                            memcpy(s.pData_, dataBuf.pData_, dataBuf.size_);  // copy in the dataBuf
                            s.pData_[dataBuf.size_] = 0;                      // nul terminate it
                            const char* str = (const char*)s.pData_;          // give it name
                            out << Internal::indent(depth) << (const char*)buff.pData_ << ": " << str;
                            bLF = true;
                        }

                        if (bICC || bComm) {
                            out.write((const char*)dataBuf.pData_, dataBuf.size_);
                            bLF = bComm;
                        }

                        if (bDesc && iTXt) {
                            DataBuf decoded = PngChunk::decodeTXTChunk(buff, PngChunk::iTXt_Chunk);
                            out.write((const char*)decoded.pData_, decoded.size_);
                            bLF = true;
                        }

                        if (bLF)
                            out << std::endl;
                    }
                    delete[] data;
                }
                io_->seek(dataOffset + 4, BasicIo::cur);  // jump past checksum
                if (io_->error())
                    throw Error(kerFailedToReadImageData);
            }
        }
    }

Project: exiv2
File: pngchunk_int.cpp

        std::string PngChunk::makeMetadataChunk(const std::string& metadata, MetadataId type)
        {
            std::string chunk;
            std::string rawProfile;

            switch (type) {
                case mdComment:
                    chunk = makeUtf8TxtChunk("Description", metadata, true);
                    break;
                case mdExif:
                    rawProfile = writeRawProfile(metadata, "exif");
                    chunk = makeAsciiTxtChunk("Raw profile type exif", rawProfile, true);
                    break;
                case mdIptc:
                    rawProfile = writeRawProfile(metadata, "iptc");
                    chunk = makeAsciiTxtChunk("Raw profile type iptc", rawProfile, true);
                    break;
                case mdXmp:
                    chunk = makeUtf8TxtChunk("XML:com.adobe.xmp", metadata, false);
                    break;
                case mdIccProfile:
                    break;
                case mdNone:
                    assert(false);
            }

            return chunk;

        }  // PngChunk::makeMetadataChunk

Project: exiv2
File: actions.cpp

    std::unique_ptr<Task> Task::clone() const
    {
        return std::unique_ptr<Task>(clone_());
    }

Project: exiv2
File: image.cpp

    ByteOrder Image::byteOrder() const
    {
        return byteOrder_;
    }

Project: exiv2
File: image.cpp

    uint32_t Image::byteSwap(uint32_t value,bool bSwap) const
    {
        uint32_t result = 0;
        result |= (value & 0x000000FF) << 24;
        result |= (value & 0x0000FF00) << 8;
        result |= (value & 0x00FF0000) >> 8;
        result |= (value & 0xFF000000) >> 24;
        return bSwap ? result : value;
    }

Project: exiv2
File: tiffimage_int.cpp

    TiffComponent::UniquePtr TiffParserWorker::parse(
        const byte*              pData,
              uint32_t           size,
              uint32_t           root,
              TiffHeaderBase*    pHeader
    )
    {
        if (pData == 0 || size == 0)
            return nullptr;
        if (!pHeader->read(pData, size) || pHeader->offset() >= size) {
            throw Error(kerNotAnImage, "TIFF");
        }
        TiffComponent::UniquePtr rootDir = TiffCreator::create(root, ifdIdNotSet);
        if (0 != rootDir.get()) {
            rootDir->setStart(pData + pHeader->offset());
            TiffRwState state(pHeader->byteOrder(), 0);
            TiffReader reader(pData, size, rootDir.get(), state);
            rootDir->accept(reader);
            reader.postProcess();
        }
        return rootDir;

    } // TiffParserWorker::parse

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffIfdMakernote::doSize() const
    {
        return sizeHeader() + ifd_.size();
    } // TiffIfdMakernote::doSize

Project: exiv2
File: preview.cpp

        virtual bool readDimensions() { return true; }

Project: exiv2
File: xmp.cpp

    Exiv2::XmpKey::UniquePtr makeXmpKey(const std::string& schemaNs,
                                      const std::string& propPath)
    {
        std::string property;
        std::string::size_type idx = propPath.find(':');
        if (idx == std::string::npos) {
            throw Exiv2::Error(Exiv2::kerPropertyNameIdentificationFailed, propPath, schemaNs);
        }
        // Don't worry about out_of_range, XMP parser takes care of this
        property = propPath.substr(idx + 1);
        std::string prefix = Exiv2::XmpProperties::prefix(schemaNs);
        if (prefix.empty()) {
            throw Exiv2::Error(Exiv2::kerNoPrefixForNamespace, propPath, schemaNs);
        }
        return Exiv2::XmpKey::UniquePtr(new Exiv2::XmpKey(prefix, property));
    } // makeXmpKey

Project: exiv2
File: convert.cpp

    void Converter::cnvXmpGPSVersion(const char* from, const char* to)
    {
        Exiv2::XmpData::iterator pos = xmpData_->findKey(XmpKey(from));
        if (pos == xmpData_->end()) return;
        if (!prepareExifTarget(to)) return;
        std::string value = pos->toString();
        if (!pos->value().ok()) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
            return;
        }

        for (unsigned i = 0; i < value.length(); ++i) {
            if (value[i] == '.') value[i] = ' ';
        }
        (*exifData_)[to] = value;
        if (erase_) xmpData_->erase(pos);

    }

Project: exiv2
File: makernote_int.cpp

    std::string getExifModel(Exiv2::Internal::TiffComponent* const pRoot)
    {
        Exiv2::Internal::TiffFinder finder(0x0110, Exiv2::Internal::ifd0Id); // Exif.Image.Model
        pRoot->accept(finder);
        Exiv2::Internal::TiffEntryBase* te = dynamic_cast<Exiv2::Internal::TiffEntryBase*>(finder.result());
        if (!te || !te->pValue() || te->pValue()->count() == 0) return std::string();
        return te->pValue()->toString();
    }

Project: exiv2
File: jpgimage.cpp

    void JpegBase::readMetadata()
    {
        int rc = 0; // Todo: this should be the return value

        if (io_->open() != 0) throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        IoCloser closer(*io_);
        // Ensure that this is the correct image type
        if (!isThisType(*io_, true)) {
            if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
            throw Error(kerNotAJpeg);
        }
        clearMetadata();
        int search = 6 ; // Exif, ICC, XMP, Comment, IPTC, SOF
        const long bufMinSize = 36;
        DataBuf buf(bufMinSize);
        Blob psBlob;
        bool foundCompletePsData = false;
        bool foundExifData = false;
        bool foundXmpData = false;
        bool foundIccData = false;

        // Read section marker
        int marker = advanceToMarker();
        if (marker < 0) throw Error(kerNotAJpeg);

        while (marker != sos_ && marker != eoi_ && search > 0) {
            // Read size and signature (ok if this hits EOF)
            std::memset(buf.pData_, 0x0, buf.size_);
            size_t bufRead = io_->read(buf.pData_, bufMinSize);
            if (io_->error())
                throw Error(kerFailedToReadImageData);
            if (bufRead < 2)
                throw Error(kerNotAJpeg);
            uint16_t size = getUShort(buf.pData_, bigEndian);

            if (   !foundExifData
                && marker == app1_ && memcmp(buf.pData_ + 2, exifId_, 6) == 0) {
                if (size < 8) {
                    rc = 1;
                    break;
                }
                // Seek to beginning and read the Exif data
                io_->seek(8 - bufRead, BasicIo::cur);
                DataBuf rawExif(size - 8);
                io_->read(rawExif.pData_, rawExif.size_);
                if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
                ByteOrder bo = ExifParser::decode(exifData_, rawExif.pData_, (uint32_t)rawExif.size_);
                setByteOrder(bo);
                if (rawExif.size_ > 0 && byteOrder() == invalidByteOrder) {
#ifndef SUPPRESS_WARNINGS
                    EXV_WARNING << "Failed to decode Exif metadata.\n";
#endif
                    exifData_.clear();
                }
                --search;
                foundExifData = true;
            }
            else if (   !foundXmpData
                     && marker == app1_ && memcmp(buf.pData_ + 2, xmpId_, 29) == 0) {
                if (size < 31) {
                    rc = 6;
                    break;
                }
                // Seek to beginning and read the XMP packet
                io_->seek(31 - bufRead, BasicIo::cur);
                DataBuf xmpPacket(size - 31);
                io_->read(xmpPacket.pData_, xmpPacket.size_);
                if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
                xmpPacket_.assign(reinterpret_cast<char*>(xmpPacket.pData_), xmpPacket.size_);
                if (xmpPacket_.size() > 0 && XmpParser::decode(xmpData_, xmpPacket_)) {
#ifndef SUPPRESS_WARNINGS
                    EXV_WARNING << "Failed to decode XMP metadata.\n";
#endif
                }
                --search;
                foundXmpData = true;
            }
            else if (   !foundCompletePsData
                     && marker == app13_ && memcmp(buf.pData_ + 2, Photoshop::ps3Id_, 14) == 0) {
                if (size < 16) {
                    rc = 2;
                    break;
                }
                // Read the rest of the APP13 segment
                io_->seek(16 - bufRead, BasicIo::cur);
                DataBuf psData(size - 16);
                io_->read(psData.pData_, psData.size_);
                if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
#ifdef DEBUG
                std::cerr << "Found app13 segment, size = " << size << "\n";
                //hexdump(std::cerr, psData.pData_, psData.size_);
#endif
                // Append to psBlob
                append(psBlob, psData.pData_, (uint32_t)psData.size_);
                // Check whether psBlob is complete
                if (psBlob.size() > 0 && Photoshop::valid(&psBlob[0], (long) psBlob.size())) {
                    --search;
                    foundCompletePsData = true;
                }
            }
            else if (marker == com_ && comment_.empty())
            {
                if (size < 2) {
                    rc = 3;
                    break;
                }
                // JPEGs can have multiple comments, but for now only read
                // the first one (most jpegs only have one anyway). Comments
                // are simple single byte ISO-8859-1 strings.
                io_->seek(2 - bufRead, BasicIo::cur);
                DataBuf comment(size - 2);
                io_->read(comment.pData_, comment.size_);
                if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
                comment_.assign(reinterpret_cast<char*>(comment.pData_), comment.size_);
                while (   comment_.length()
                       && comment_.at(comment_.length()-1) == '\0') {
                    comment_.erase(comment_.length()-1);
                }
                --search;
            }
            else if ( marker == app2_ && memcmp(buf.pData_ + 2, iccId_,11)==0) {
                if (size < 2+14) {
                    rc = 8;
                    break;
                }
                // ICC profile
                if ( ! foundIccData  ) {
                    foundIccData = true ;
                    --search ;
                }
                int chunk  = (int)    buf.pData_[2+12];
                int chunks = (int)    buf.pData_[2+13];
                // ICC1v43_2010-12.pdf header is 14 bytes
                // header = "ICC_PROFILE\0" (12 bytes)
                // chunk/chunks are a single byte
                // Spec 7.2 Profile bytes 0-3 size
                uint32_t s = getULong(buf.pData_ + (2+14) , bigEndian);
#ifdef DEBUG
                std::cerr << "Found ICC Profile chunk " << chunk
                          << " of "    << chunks
                          << (chunk==1 ? " size: " : "" ) << (chunk==1 ? s : 0)
                          << std::endl  ;
#endif
                io_->seek(-(int64_t)bufRead, BasicIo::cur); // back up to start of buffer (after marker)
                io_->seek(    14+2, BasicIo::cur); // step header
                // read in profile
                // #1286 profile can be padded
                long icc_size = size-2-14;
                if (chunk==1 && chunks==1) {
                  enforce(s <= static_cast<uint32_t>(icc_size), kerInvalidIccProfile);
                  icc_size = s;
                }
                DataBuf icc(icc_size);
                io_->read( icc.pData_,icc.size_);

                if ( !iccProfileDefined() ) { // first block of profile
                    setIccProfile(icc,chunk==chunks);
                } else {                       // extend existing profile
                    DataBuf profile(Safe::add(iccProfile_.size_, icc.size_));
                    if ( iccProfile_.size_ ) {
                        ::memcpy(profile.pData_,iccProfile_.pData_,iccProfile_.size_);
                    }
                    ::memcpy(profile.pData_+iccProfile_.size_,icc.pData_,icc.size_);
                    setIccProfile(profile,chunk==chunks);
                }
            }
            else if (  pixelHeight_ == 0 && inRange2(marker,sof0_,sof3_,sof5_,sof15_) ) {
                // We hit a SOFn (start-of-frame) marker
                if (size < 8) {
                    rc = 7;
                    break;
                }
                pixelHeight_ = getUShort(buf.pData_ + 3, bigEndian);
                pixelWidth_ = getUShort(buf.pData_ + 5, bigEndian);
                if (pixelHeight_ != 0) --search;
                // Skip the remainder of the segment
                io_->seek(size-bufRead, BasicIo::cur);
            }
            else {
                if (size < 2) {
                    rc = 4;
                    break;
                }
                // Skip the remainder of the unknown segment
                if (io_->seek(size - bufRead, BasicIo::cur)) throw Error(kerFailedToReadImageData);
            }
            // Read the beginning of the next segment
            marker = advanceToMarker();
            if (marker < 0) {
                rc = 5;
                break;
            }
        } // while there are segments to process

        if (psBlob.size() > 0) {
            // Find actual IPTC data within the psBlob
            Blob iptcBlob;
            const byte *record = 0;
            uint32_t sizeIptc = 0;
            uint32_t sizeHdr = 0;
            const byte* pCur = &psBlob[0];
            const byte* pEnd = pCur + psBlob.size();
            while (   pCur < pEnd
                   && 0 == Photoshop::locateIptcIrb(pCur, static_cast<long>(pEnd - pCur),
                                                    &record, &sizeHdr, &sizeIptc)) {
#ifdef DEBUG
                std::cerr << "Found IPTC IRB, size = " << sizeIptc << "\n";
#endif
                if (sizeIptc) {
                    append(iptcBlob, record + sizeHdr, sizeIptc);
                }
                pCur = record + sizeHdr + sizeIptc + (sizeIptc & 1);
            }
            if (   iptcBlob.size() > 0
                && IptcParser::decode(iptcData_,
                                      &iptcBlob[0],
                                      static_cast<uint32_t>(iptcBlob.size()))) {
#ifndef SUPPRESS_WARNINGS
                EXV_WARNING << "Failed to decode IPTC metadata.\n";
#endif
                iptcData_.clear();
            }
        } // psBlob.size() > 0

        if (rc != 0) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << "JPEG format error, rc = " << rc << "\n";
#endif
        }
    } // JpegBase::readMetadata

Project: exiv2
File: makernote_int.cpp

    DataBuf nikonCrypt(uint16_t tag, const byte* pData, uint32_t size, TiffComponent* const pRoot)
    {
        DataBuf buf;

        if (size < 4) return buf;
        const NikonArrayIdx* nci = find(nikonArrayIdx, NikonArrayIdx::Key(tag, reinterpret_cast<const char*>(pData), size));
        if (nci == 0 || nci->start_ == NA || size <= nci->start_) return buf;

        // Find Exif.Nikon3.ShutterCount
        TiffFinder finder(0x00a7, nikon3Id);
        pRoot->accept(finder);
        TiffEntryBase* te = dynamic_cast<TiffEntryBase*>(finder.result());
        if (!te || !te->pValue() || te->pValue()->count() == 0) return buf;
        uint32_t count = static_cast<uint32_t>(te->pValue()->toLong());

        // Find Exif.Nikon3.SerialNumber
        finder.init(0x001d, nikon3Id);
        pRoot->accept(finder);
        te = dynamic_cast<TiffEntryBase*>(finder.result());
        if (!te || !te->pValue() || te->pValue()->count() == 0) return buf;
        bool ok(false);
        uint32_t serial = stringTo<uint32_t>(te->pValue()->toString(), ok);
        if (!ok) {
            std::string model = getExifModel(pRoot);
            if (model.empty()) return buf;
            if (model.find("D50") != std::string::npos) {
                serial = 0x22;
            }
            else {
                serial = 0x60;
            }
        }
        buf.alloc(size);
        memcpy(buf.pData_, pData, buf.size_);
        ncrypt(buf.pData_ + nci->start_, buf.size_ - nci->start_, count, serial);
        return buf;
    }

Project: exiv2
File: exif.cpp

    ExifData::const_iterator ExifData::findKey(const ExifKey& key) const
    {
        return std::find_if(exifMetadata_.begin(), exifMetadata_.end(),
                            FindExifdatumByKey(key.key()));
    }

Project: exiv2
File: actions.cpp

    FixCom* FixCom::clone_() const
    {
        return new FixCom(*this);
    }

Project: exiv2
File: value.cpp

    XmpArrayValue::UniquePtr XmpArrayValue::clone() const
    {
        return UniquePtr(clone_());
    }

Project: exiv2
File: actions.cpp

    int Adjust::run(const std::string& path) try {
        adjustment_ = Params::instance().adjustment_;
        yearAdjustment_ = Params::instance().yodAdjust_[Params::yodYear].adjustment_;
        monthAdjustment_ = Params::instance().yodAdjust_[Params::yodMonth].adjustment_;
        dayAdjustment_ = Params::instance().yodAdjust_[Params::yodDay].adjustment_;

        if (!Exiv2::fileExists(path, true)) {
            std::cerr << path << ": " << _("Failed to open the file\n");
            return -1;
        }
        Timestamp ts;
        if (Params::instance().preserve_)
            ts.read(path);

        Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open(path);
        image->readMetadata();
        Exiv2::ExifData& exifData = image->exifData();
        if (exifData.empty()) {
            std::cerr << path << ": " << _("No Exif data found in the file\n");
            return -3;
        }
        int rc = adjustDateTime(exifData, "Exif.Image.DateTime", path);
        rc += adjustDateTime(exifData, "Exif.Photo.DateTimeOriginal", path);
        rc += adjustDateTime(exifData, "Exif.Image.DateTimeOriginal", path);
        rc += adjustDateTime(exifData, "Exif.Photo.DateTimeDigitized", path);

        if (rc == 0) {
            image->writeMetadata();
            if (Params::instance().preserve_)
                ts.touch(path);
        }
        return rc ? 1 : 0;
    } catch (const Exiv2::AnyError& e) {

Project: exiv2
File: crwimage.cpp

    std::string CrwImage::mimeType() const
    {
        return "image/x-canon-crw";
    }

Project: exiv2
File: crwimage_int.cpp

    void CrwMap::encode0x080a(const Image&      image,
                              const CrwMapping* pCrwMapping,
                                    CiffHeader* pHead)
    {
        assert(pCrwMapping != 0);
        assert(pHead != 0);

        const ExifKey k1("Exif.Image.Make");
        const ExifKey k2("Exif.Image.Model");
        const ExifData::const_iterator ed1 = image.exifData().findKey(k1);
        const ExifData::const_iterator ed2 = image.exifData().findKey(k2);
        const ExifData::const_iterator edEnd = image.exifData().end();

        size_t size = 0;
        if (ed1 != edEnd) size += ed1->size();
        if (ed2 != edEnd) size += ed2->size();
        if (size != 0) {
            DataBuf buf(size);
            if (ed1 != edEnd) ed1->copy(buf.pData_, pHead->byteOrder());
            if (ed2 != edEnd) ed2->copy(buf.pData_ + ed1->size(), pHead->byteOrder());
            pHead->add(pCrwMapping->crwTagId_, pCrwMapping->crwDir_, buf);
        }
        else {
            pHead->remove(pCrwMapping->crwTagId_, pCrwMapping->crwDir_);
        }
    } // CrwMap::encode0x080a

Project: exiv2
File: jp2image.cpp

    void Jp2Image::writeMetadata()
    {
        if (io_->open() != 0)
        {
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        }
        IoCloser closer(*io_);
        BasicIo::UniquePtr tempIo(new MemIo);
        assert (tempIo.get() != 0);

        doWriteMetadata(*tempIo); // may throw
        io_->close();
        io_->transfer(*tempIo); // may throw

    } // Jp2Image::writeMetadata

Project: exiv2
File: tiffimage.cpp

    TiffHeaderBase::~TiffHeaderBase()
    {
    }

Project: exiv2
File: image.cpp

    BasicIo::UniquePtr ImageFactory::createIo(const std::string& path, bool useCurl)
    {
        Protocol fProt = fileProtocol(path);

#ifdef EXV_USE_SSH
        if (fProt == pSsh || fProt == pSftp) {
            return BasicIo::UniquePtr(new SshIo(path)); // may throw
        }
#endif

#ifdef EXV_USE_CURL
        if (useCurl && (fProt == pHttp || fProt == pHttps || fProt == pFtp)) {
            return BasicIo::UniquePtr(new CurlIo(path)); // may throw
        }
#endif

        if (fProt == pHttp)
            return BasicIo::UniquePtr(new HttpIo(path)); // may throw
        if (fProt == pFileUri)
            return BasicIo::UniquePtr(new FileIo(pathOfFileUrl(path)));
        if (fProt == pStdin || fProt == pDataUri)
            return BasicIo::UniquePtr(new XPathIo(path)); // may throw

        return BasicIo::UniquePtr(new FileIo(path));

        (void)(useCurl);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffSubIfd::doSize() const
    {
        return static_cast<uint32_t>(ifds_.size()) * 4;
    } // TiffSubIfd::doSize

Project: exiv2
File: tiffimage.cpp

    void TiffCreator::getPath(TiffPath& tiffPath,
                              uint32_t  extendedTag,
                              IfdId     group,
                              uint32_t  root)
    {
        const TiffTreeStruct* ts = 0;
        do {
            tiffPath.push(TiffPathItem(extendedTag, group));
            ts = find(tiffTreeStruct_, TiffTreeStruct::Key(root, group));
            assert(ts != 0);
            extendedTag = ts->parentExtTag_;
            group = ts->parentGroup_;
        } while (!(ts->root_ == root && ts->group_ == ifdIdNotSet));

    } // TiffCreator::getPath

Project: exiv2
File: exif.cpp

    Exiv2::DataBuf TiffThumbnail::copy(const Exiv2::ExifData& exifData) const
    {
        Exiv2::ExifData thumb;
        // Copy all Thumbnail (IFD1) tags from exifData to Image (IFD0) tags in thumb
        for (Exiv2::ExifData::const_iterator i = exifData.begin(); i != exifData.end(); ++i) {
            if (i->groupName() == "Thumbnail") {
                std::string key = "Exif.Image." + i->tagName();
                thumb.add(Exiv2::ExifKey(key), &i->value());
            }
        }

        Exiv2::MemIo io;
        Exiv2::IptcData emptyIptc;
        Exiv2::XmpData  emptyXmp;
        Exiv2::TiffParser::encode(io, 0, 0, Exiv2::littleEndian, thumb, emptyIptc, emptyXmp);
        return io.read((long) io.size());
    }

Project: exiv2
File: image.cpp

    Image::UniquePtr ImageFactory::open(const std::string& path, bool useCurl)
    {
        Image::UniquePtr image = open(ImageFactory::createIo(path, useCurl)); // may throw
        if (image.get() == 0)
            throw Error(kerFileContainsUnknownImageType, path);
        return image;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffMnEntry::doCount() const
    {
        if (!mn_) {
            return TiffEntryBase::doCount();
        }
        // Count of IFD makernote in tag Exif.Photo.MakerNote is the size of the
        // Makernote in bytes
        assert(tiffType() == ttUndefined || tiffType() == ttUnsignedByte || tiffType() == ttSignedByte);
        return mn_->size();
    }

Project: exiv2
File: image.cpp

    const char* Image::typeName(uint16_t tag) const
    {
        //! List of TIFF image tags
        const char* result = nullptr;
        switch (tag ) {
            case Exiv2::unsignedByte     : result = "BYTE"      ; break;
            case Exiv2::asciiString      : result = "ASCII"     ; break;
            case Exiv2::unsignedShort    : result = "SHORT"     ; break;
            case Exiv2::unsignedLong     : result = "LONG"      ; break;
            case Exiv2::unsignedRational : result = "RATIONAL"  ; break;
            case Exiv2::signedByte       : result = "SBYTE"     ; break;
            case Exiv2::undefined        : result = "UNDEFINED" ; break;
            case Exiv2::signedShort      : result = "SSHORT"    ; break;
            case Exiv2::signedLong       : result = "SLONG"     ; break;
            case Exiv2::signedRational   : result = "SRATIONAL" ; break;
            case Exiv2::tiffFloat        : result = "FLOAT"     ; break;
            case Exiv2::tiffDouble       : result = "DOUBLE"    ; break;
            case Exiv2::tiffIfd          : result = "IFD"       ; break;
            default                      : result = "unknown"   ; break;
        }
        return result;
    }

Project: exiv2
File: image.cpp

    ImageType ImageFactory::getType(const std::string& path)
    {
        FileIo fileIo(path);
        return getType(fileIo);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffDirectory::writeDirEntry(IoWrapper&     ioWrapper,
                                          ByteOrder      byteOrder,
                                          int32_t        offset,
                                          TiffComponent* pTiffComponent,
                                          uint32_t       valueIdx,
                                          uint32_t       dataIdx,
                                          uint32_t&      imageIdx) const
    {
        assert(pTiffComponent);
        TiffEntryBase* pDirEntry = dynamic_cast<TiffEntryBase*>(pTiffComponent);
        assert(pDirEntry);
        byte buf[8];
        us2Data(buf,     pDirEntry->tag(),      byteOrder);
        us2Data(buf + 2, pDirEntry->tiffType(), byteOrder);
        ul2Data(buf + 4, pDirEntry->count(),    byteOrder);
        ioWrapper.write(buf, 8);
        if (pDirEntry->size() > 4) {
            pDirEntry->setOffset(offset + static_cast<int32_t>(valueIdx));
            l2Data(buf, pDirEntry->offset(), byteOrder);
            ioWrapper.write(buf, 4);
        }
        else {
            const uint32_t len = pDirEntry->write(ioWrapper,
                                                  byteOrder,
                                                  offset,
                                                  valueIdx,
                                                  dataIdx,
                                                  imageIdx);
            assert(len <= 4);
            if (len < 4) {
                memset(buf, 0x0, 4);
                ioWrapper.write(buf, 4 - len);
            }
        }
        return 12;
    } // TiffDirectory::writeDirEntry

Project: exiv2
File: actions.cpp

    Adjust* Adjust::clone_() const
    {
        return new Adjust(*this);
    }

Project: exiv2
File: pngchunk_int.cpp

        void PngChunk::zlibUncompress(const byte* compressedText, unsigned int compressedTextSize, DataBuf& arr)
        {
            uLongf uncompressedLen = compressedTextSize * 2;  // just a starting point
            int zlibResult;
            int dos = 0;

            do {
                arr.alloc(uncompressedLen);
                zlibResult = uncompress((Bytef*)arr.pData_, &uncompressedLen, compressedText, compressedTextSize);
                if (zlibResult == Z_OK) {
                    assert((uLongf)arr.size_ >= uncompressedLen);
                    arr.size_ = uncompressedLen;
                } else if (zlibResult == Z_BUF_ERROR) {
                    // the uncompressedArray needs to be larger
                    uncompressedLen *= 2;
                    // DoS protection. can't be bigger than 64k
                    if (uncompressedLen > 131072) {
                        if (++dos > 1)
                            break;
                        uncompressedLen = 131072;
                    }
                } else {
                    // something bad happened
                    throw Error(kerFailedToReadImageData);
                }
            } while (zlibResult == Z_BUF_ERROR);

            if (zlibResult != Z_OK) {
                throw Error(kerFailedToReadImageData);
            }
        }  // PngChunk::zlibUncompress

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffFinder::visitIfdMakernote(TiffIfdMakernote* object)
    {
        findObject(object);
    }

Project: exiv2
File: bigtiffimage.cpp

            Format format() const
            {
                assert(isValid());
                return version_ == 0x2A? StandardTiff: BigTiff;
            }

Project: exiv2
File: value.cpp

    long DataValue::toLong(long n) const
    {
        ok_ = true;
        return value_[n];
    }

Project: exiv2
File: convert.cpp

        bool erase() const { return erase_; }

Project: exiv2
File: xmp.cpp

    Exiv2::XmpValue::XmpStruct xmpStruct(const XMP_OptionBits& opt)
    {
        Exiv2::XmpValue::XmpStruct var(Exiv2::XmpValue::xsNone);
        if (XMP_PropIsStruct(opt)) {
            var = Exiv2::XmpValue::xsStruct;
        }
        return var;
    }

Project: exiv2
File: types.cpp

    std::wstring s2ws(const std::string& s)
    {
        int len;
        int slength = (int)s.length() + 1;
        len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
        wchar_t* buf = new wchar_t[len];
        MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
        std::wstring r(buf);
        delete[] buf;
        return r;
    }

Project: exiv2
File: value.cpp

    CommentValue* CommentValue::clone_() const
    {
        return new CommentValue(*this);
    }

Project: exiv2
File: crwimage_int.cpp

    CiffComponent* CiffDirectory::doFindComponent(uint16_t crwTagId,
                                                  uint16_t crwDir) const
    {
        CiffComponent* cc = nullptr;
        const Components::const_iterator b = components_.begin();
        const Components::const_iterator e = components_.end();
        for (Components::const_iterator i = b; i != e; ++i) {
            cc = (*i)->findComponent(crwTagId, crwDir);
            if (cc) return cc;
        }
        return 0;
    } // CiffDirectory::doFindComponent

Project: exiv2
File: exif.cpp

    Exifdatum& Exifdatum::operator=(const uint16_t& value)
    {
        return Exiv2::setValue(*this, value);
    }

Project: exiv2
File: makernote_int.cpp

    size_t FujiMnHeader::write(IoWrapper& ioWrapper,
                                 ByteOrder /*byteOrder*/) const
    {
        ioWrapper.write(signature_, sizeOfSignature());
        return sizeOfSignature();
    } // FujiMnHeader::write

Project: exiv2
File: preview.cpp

    PreviewProperties LoaderTiff::getProperties() const
    {
        PreviewProperties prop = Loader::getProperties();
        prop.mimeType_ = "image/tiff";
        prop.extension_ = ".tif";
#ifdef EXV_UNICODE_PATH
        prop.wextension_ = EXV_WIDEN(".tif");
#endif
        return prop;
    }

Project: exiv2
File: bigtiffimage.cpp

                std::string mimeType() const
                {
                    return std::string();
                }

Project: exiv2
File: value.cpp

    Value::UniquePtr Value::create(TypeId typeId)
    {
        UniquePtr value;
        switch (typeId) {
        case invalidTypeId:
        case signedByte:
        case unsignedByte:
            value = UniquePtr(new DataValue(typeId));
            break;
        case asciiString:
            value = UniquePtr(new AsciiValue);
            break;
        case unsignedShort:
            value = UniquePtr(new ValueType<uint16_t>);
            break;
        case unsignedLong:
        case tiffIfd:
            value = UniquePtr(new ValueType<uint32_t>(typeId));
            break;
        case unsignedRational:
            value = UniquePtr(new ValueType<URational>);
            break;
        case undefined:
            value = UniquePtr(new DataValue);
            break;
        case signedShort:
            value = UniquePtr(new ValueType<int16_t>);
            break;
        case signedLong:
            value = UniquePtr(new ValueType<int32_t>);
            break;
        case signedRational:
            value = UniquePtr(new ValueType<Rational>);
            break;
        case tiffFloat:
            value = UniquePtr(new ValueType<float>);
            break;
        case tiffDouble:
            value = UniquePtr(new ValueType<double>);
            break;
        case string:
            value = UniquePtr(new StringValue);
            break;
        case date:
            value = UniquePtr(new DateValue);
            break;
        case time:
            value = UniquePtr(new TimeValue);
            break;
        case comment:
            value = UniquePtr(new CommentValue);
            break;
        case xmpText:
            value = UniquePtr(new XmpTextValue);
            break;
        case xmpBag:
        case xmpSeq:
        case xmpAlt:
            value = UniquePtr(new XmpArrayValue(typeId));
            break;
        case langAlt:
            value = UniquePtr(new LangAltValue);
            break;
        default:
            value = UniquePtr(new DataValue(typeId));
            break;
        }
        return value;
    } // Value::create

Project: exiv2
File: value.cpp

    Rational XmpTextValue::toRational(long /*n*/) const
    {
        return parseRational(value_, ok_);
    }

Project: exiv2
File: actions.cpp

    bool Print::keyTag(const std::string& key)
    {
        bool result = Params::instance().keys_.empty();
        for (auto k = Params::instance().keys_.begin(); !result && k != Params::instance().keys_.end(); ++k) {
            result = key.compare(*k) == 0;
        }
        return result;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::visitSizeEntry(TiffSizeEntry* object)
    {
        encodeTiffComponent(object);
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::visitIfdMakernote(TiffIfdMakernote* object)
    {
        assert(object != 0);

        ExifData::iterator pos = exifData_.findKey(ExifKey("Exif.MakerNote.ByteOrder"));
        if (pos != exifData_.end()) {
            // Set Makernote byte order
            ByteOrder bo = stringToByteOrder(pos->toString());
            if (bo != invalidByteOrder && bo != object->byteOrder()) {
                object->setByteOrder(bo);
                setDirty();
            }
            if (del_)
                exifData_.erase(pos);
        }
        if (del_) {
            // Remove remaining synthesized tags
            static const char* synthesizedTags[] = {
                "Exif.MakerNote.Offset",
            };
            for (unsigned int i = 0; i < EXV_COUNTOF(synthesizedTags); ++i) {
                pos = exifData_.findKey(ExifKey(synthesizedTags[i]));
                if (pos != exifData_.end())
                    exifData_.erase(pos);
            }
        }
        // Modify encoder for Makernote peculiarities, byte order
        byteOrder_ = object->byteOrder();

    } // TiffEncoder::visitIfdMakernote

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::visitImageEntry(TiffImageEntry* object)
    {
        encodeTiffComponent(object);
    }

Project: exiv2
File: exif.cpp

    WriteMethod ExifParser::encode(
              Blob&     blob,
        const byte*     pData,
              uint32_t  size,
              ByteOrder byteOrder,
        const ExifData& exifData
    )
    {
        ExifData ed = exifData;

        // Delete IFD0 tags that are "not recorded" in compressed images
        // Reference: Exif 2.2 specs, 4.6.8 Tag Support Levels, section A
        static const char* filteredIfd0Tags[] = {
            "Exif.Image.PhotometricInterpretation",
            "Exif.Image.StripOffsets",
            "Exif.Image.RowsPerStrip",
            "Exif.Image.StripByteCounts",
            "Exif.Image.JPEGInterchangeFormat",
            "Exif.Image.JPEGInterchangeFormatLength",
            "Exif.Image.SubIFDs"
        };
        for (unsigned int i = 0; i < EXV_COUNTOF(filteredIfd0Tags); ++i) {
            ExifData::iterator pos = ed.findKey(ExifKey(filteredIfd0Tags[i]));
            if (pos != ed.end()) {
#ifdef DEBUG
                std::cerr << "Warning: Exif tag " << pos->key() << " not encoded\n";
#endif
                ed.erase(pos);
            }
        }

        // Delete IFDs which do not occur in JPEGs
        static const IfdId filteredIfds[] = {
            subImage1Id,
            subImage2Id,
            subImage3Id,
            subImage4Id,
            subImage5Id,
            subImage6Id,
            subImage7Id,
            subImage8Id,
            subImage9Id,
            subThumb1Id,
            panaRawId,
            ifd2Id,
            ifd3Id
        };
        for (unsigned int i = 0; i < EXV_COUNTOF(filteredIfds); ++i) {
#ifdef DEBUG
            std::cerr << "Warning: Exif IFD " << filteredIfds[i] << " not encoded\n";
#endif
            eraseIfd(ed, filteredIfds[i]);
        }

        // IPTC and XMP are stored elsewhere, not in the Exif APP1 segment.
        IptcData emptyIptc;
        XmpData  emptyXmp;

        // Encode and check if the result fits into a JPEG Exif APP1 segment
        MemIo mio1;
        std::unique_ptr<TiffHeaderBase> header(new TiffHeader(byteOrder, 0x00000008, false));
        WriteMethod wm = TiffParserWorker::encode(mio1,
                                                  pData,
                                                  size,
                                                  ed,
                                                  emptyIptc,
                                                  emptyXmp,
                                                  Tag::root,
                                                  TiffMapping::findEncoder,
                                                  header.get(),
                                                  0);
        if (mio1.size() <= 65527) {
            append(blob, mio1.mmap(), (uint32_t) mio1.size());
            return wm;
        }

        // If it doesn't fit, remove additional tags

        // Delete preview tags if the preview is larger than 32kB.
        // Todo: Enhance preview classes to be able to write and delete previews and use that instead.
        // Table must be sorted by preview, the first tag in each group is the size
        static const PreviewTags filteredPvTags[] = {
            { pttLen, "Exif.Minolta.ThumbnailLength"                  },
            { pttTag, "Exif.Minolta.ThumbnailOffset"                  },
            { pttLen, "Exif.Minolta.Thumbnail"                        },
            { pttLen, "Exif.NikonPreview.JPEGInterchangeFormatLength" },
            { pttIfd, "NikonPreview"                                  },
            { pttLen, "Exif.Olympus.ThumbnailLength"                  },
            { pttTag, "Exif.Olympus.ThumbnailOffset"                  },
            { pttLen, "Exif.Olympus.ThumbnailImage"                   },
            { pttLen, "Exif.Olympus.Thumbnail"                        },
            { pttLen, "Exif.Olympus2.ThumbnailLength"                 },
            { pttTag, "Exif.Olympus2.ThumbnailOffset"                 },
            { pttLen, "Exif.Olympus2.ThumbnailImage"                  },
            { pttLen, "Exif.Olympus2.Thumbnail"                       },
            { pttLen, "Exif.OlympusCs.PreviewImageLength"             },
            { pttTag, "Exif.OlympusCs.PreviewImageStart"              },
            { pttTag, "Exif.OlympusCs.PreviewImageValid"              },
            { pttLen, "Exif.Pentax.PreviewLength"                     },
            { pttTag, "Exif.Pentax.PreviewOffset"                     },
            { pttTag, "Exif.Pentax.PreviewResolution"                 },
            { pttLen, "Exif.PentaxDng.PreviewLength"                  },
            { pttTag, "Exif.PentaxDng.PreviewOffset"                  },
            { pttTag, "Exif.PentaxDng.PreviewResolution"              },
            { pttLen, "Exif.SamsungPreview.JPEGInterchangeFormatLength" },
            { pttIfd, "SamsungPreview"                                },
            { pttLen, "Exif.Thumbnail.StripByteCounts"                },
            { pttIfd, "Thumbnail"                                     },
            { pttLen, "Exif.Thumbnail.JPEGInterchangeFormatLength"    },
            { pttIfd, "Thumbnail"                                     }
        };
        bool delTags = false;
        ExifData::iterator pos;
        for (unsigned int i = 0; i < EXV_COUNTOF(filteredPvTags); ++i) {
            switch (filteredPvTags[i].ptt_) {
            case pttLen:
                delTags = false;
                pos = ed.findKey(ExifKey(filteredPvTags[i].key_));
                if (pos != ed.end() && sumToLong(*pos) > 32768) {
                    delTags = true;
#ifndef SUPPRESS_WARNINGS
                    EXV_WARNING << "Exif tag " << pos->key() << " not encoded\n";
#endif
                    ed.erase(pos);
                }
                break;
            case pttTag:
                if (delTags) {
                    pos = ed.findKey(ExifKey(filteredPvTags[i].key_));
                    if (pos != ed.end()) {
#ifndef SUPPRESS_WARNINGS
                        EXV_WARNING << "Exif tag " << pos->key() << " not encoded\n";
#endif
                        ed.erase(pos);
                    }
                }
                break;
            case pttIfd:
                if (delTags) {
#ifndef SUPPRESS_WARNINGS
                    EXV_WARNING << "Exif IFD " << filteredPvTags[i].key_ << " not encoded\n";
#endif
                    eraseIfd(ed, Internal::groupId(filteredPvTags[i].key_));
                }
                break;
            }
        }

        // Delete unknown tags larger than 4kB and known tags larger than 20kB.
        for (ExifData::iterator tag_iter = ed.begin(); tag_iter != ed.end(); ) {
            if ( (tag_iter->size() > 4096 && tag_iter->tagName().substr(0, 2) == "0x") ||
                  tag_iter->size() > 20480) {
#ifndef SUPPRESS_WARNINGS
                EXV_WARNING << "Exif tag " << tag_iter->key() << " not encoded\n";
#endif
                tag_iter = ed.erase(tag_iter);
            }
            else {
                ++tag_iter;
            }
        }

        // Encode the remaining Exif tags again, don't care if it fits this time
        MemIo mio2;
        wm = TiffParserWorker::encode(mio2,
                                      pData,
                                      size,
                                      ed,
                                      emptyIptc,
                                      emptyXmp,
                                      Tag::root,
                                      TiffMapping::findEncoder,
                                      header.get(),
                                      0);
        append(blob, mio2.mmap(), (uint32_t) mio2.size());
#ifdef DEBUG
        if (wm == wmIntrusive) {
            std::cerr << "SIZE OF EXIF DATA IS " << std::dec << mio2.size() << " BYTES\n";
        }
        else {
            std::cerr << "SIZE DOESN'T MATTER, NON-INTRUSIVE WRITING USED\n";
        }
#endif
        return wm;

    }

Project: exiv2
File: preview.cpp

    std::wstring PreviewImage::wextension() const
    {
        return properties_.wextension_;
    }

Project: exiv2
File: iptc.cpp

    bool cmpIptcdataByRecord(const Iptcdatum& lhs, const Iptcdatum& rhs)
    {
        return lhs.record() < rhs.record();
    }

Project: exiv2
File: tiffvisitor_int.cpp

        bool operator()(const Exiv2::Exifdatum& md) const
        {
            return idx_ == md.idx() && 0 == strcmp(md.groupName().c_str(), groupName_);
        }

Project: exiv2
File: actions.cpp

    int Erase::eraseIptcData(Exiv2::Image* image) const
    {
        if (Params::instance().verbose_ && image->iptcData().count() > 0) {
            std::cout << _("Erasing IPTC data from the file") << std::endl;
        }
        image->clearIptcData();
        return 0;
    }

Project: exiv2
File: makernote_int.cpp

    bool PanasonicMnHeader::read(const byte* pData,
                                 uint32_t    size,
                                 ByteOrder   /*byteOrder*/)
    {
        if (!pData || size < sizeOfSignature()) return false;
        if (0 != memcmp(pData, signature_, 9)) return false;
        buf_.alloc(sizeOfSignature());
        std::memcpy(buf_.pData_, pData, buf_.size_);
        start_ = sizeOfSignature();
        return true;
    } // PanasonicMnHeader::read

Project: exiv2
File: value.cpp

    AsciiValue::~AsciiValue()
    {
    }

Project: exiv2
File: makernote_int.cpp

    bool TiffMnRegistry::operator==(IfdId key) const
    {
        return mnGroup_ == key;
    }

Project: exiv2
File: value.cpp

    long LangAltValue::toLong(long /*n*/) const
    {
        ok_ = false;
        return 0;
    }

Project: exiv2
File: xmp.cpp

    Value::UniquePtr Xmpdatum::getValue() const
    {
        return p_->value_.get() == 0 ? nullptr : p_->value_->clone();
    }

Project: exiv2
File: iptc.cpp

    Iptcdatum::Iptcdatum(const Iptcdatum& rhs)
        : Metadatum(rhs)
    {
        if (rhs.key_.get() != 0) key_ = rhs.key_->clone(); // deep copy
        if (rhs.value_.get() != 0) value_ = rhs.value_->clone(); // deep copy
    }

Project: exiv2
File: tiffimage.cpp

    std::string TiffImage::mimeType() const
    {
        if (!mimeType_.empty()) return mimeType_;

        mimeType_ = std::string("image/tiff");
        std::string key = "Exif." + primaryGroup() + ".Compression";
        ExifData::const_iterator md = exifData_.findKey(ExifKey(key));
        if (md != exifData_.end() && md->count() > 0) {
            const MimeTypeList* i = find(mimeTypeList, static_cast<int>(md->toLong()));
            if (i) mimeType_ = std::string(i->mimeType_);
        }
        return mimeType_;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    bool TiffEncoder::isImageTag(uint16_t tag, IfdId group) const
    {
        if (!isNewImage_ && pHeader_->isImageTag(tag, group, pPrimaryGroups_)) {
            return true;
        }
        return false;
    }

Project: exiv2
File: bigtiffimage.cpp

                void printIFD(std::ostream& out, PrintStructureOption option, uint64_t dir_offset, int depth)
                {
                    BasicIo& io = Image::io();

                    depth++;
                    bool bFirst  = true;

                    // buffer
                    bool bPrint = true;

                    do
                    {
                        // Read top of directory
                        io.seek(dir_offset, BasicIo::beg);

                        const uint64_t entries = readData(header_.format() == Header::StandardTiff? 2: 8);
                        const bool tooBig = entries > 500;

                        if ( bFirst && bPrint )
                        {
                            out << Internal::indent(depth) << "STRUCTURE OF BIGTIFF FILE " << io.path() << std::endl;
                            if (tooBig)
                                out << Internal::indent(depth) << "entries = " << entries << std::endl;
                        }

                        if (tooBig)
                            break;

                        // Read the dictionary
                        for ( uint64_t i = 0; i < entries; i ++ )
                        {
                            if ( bFirst && bPrint )
                                out << Internal::indent(depth)
                                    << " address |    tag                           |     "
                                    << " type |    count |    offset | value\n";

                            bFirst = false;

                            const uint16_t tag   = (uint16_t) readData(2);
                            const uint16_t type  = (uint16_t) readData(2);
                            const uint64_t count = readData(dataSize_);
                            const DataBuf  data  = io.read(dataSize_);        // Read data as raw value. what should be done about it will be decided depending on type

                            std::string sp = "" ; // output spacer

                            //prepare to print the value
                            // TODO: figure out what's going on with kount
                            const uint64_t kount  = isStringType(type)? (count > 32 ? 32 : count) // restrict long arrays
                                                            : count > 5              ? 5
                                                            : count
                                                            ;
                            const uint32_t pad    = isStringType(type) ? 1 : 0;
                            const uint32_t size   = isStringType(type) ? 1
                                                  : is2ByteType(type)  ? 2
                                                  : is4ByteType(type)  ? 4
                                                  : is8ByteType(type)  ? 8
                                                  : 1;

                            // #55 and #56 memory allocation crash test/data/POC8

                            // size * count > std::numeric_limits<uint64_t>::max()
                            // =>
                            // size > std::numeric_limits<uint64_t>::max() / count
                            // (don't perform that check when count == 0 => will cause a division by zero exception)
                            if (count != 0) {
                                if (size > std::numeric_limits<uint64_t>::max() / count) {
                                    throw Error(kerInvalidMalloc);             // we got number bigger than 2^64
                                }
                            }
                                                             // more than we can handle

                            if (size * count > std::numeric_limits<uint64_t>::max() - pad)
                                throw Error(kerInvalidMalloc);             // again more than 2^64

                            const uint64_t allocate = size*count + pad;
                            if ( allocate > io.size() ) {
                                throw Error(kerInvalidMalloc);
                            }

                            DataBuf buf(static_cast<long>(allocate));

                            const uint64_t offset = header_.format() == Header::StandardTiff?
                                    byteSwap4(data, 0, doSwap_):
                                    byteSwap8(data, 0, doSwap_);

                            // big data? Use 'data' as pointer to real data
                            const bool usePointer = (size_t) count*size > (size_t) dataSize_;

                            if ( usePointer )                          // read into buffer
                            {
                                size_t   restore = io.tell();          // save
                                io.seek(offset, BasicIo::beg);         // position
                                io.read(buf.pData_, (long) count * size);     // read
                                io.seek(restore, BasicIo::beg);        // restore
                            }
                            else  // use 'data' as data :)
                                std::memcpy(buf.pData_, data.pData_, (size_t) count * size);     // copy data

                            if ( bPrint )
                            {
                                const uint64_t entrySize = header_.format() == Header::StandardTiff? 12: 20;
                                const uint64_t address = dir_offset + 2 + i * entrySize;

                                out << Internal::indent(depth)
                                    << Internal::stringFormat("%8u | %#06x %-25s |%10s |%9u |",
                                        static_cast<size_t>(address), tag, tagName(tag).c_str(), typeName(type), count)
                                    <<(usePointer ? Internal::stringFormat("%10u | ",(size_t)offset)
                                                  : Internal::stringFormat("%10s | ",""))
                                    ;
                                if ( isShortType(type) )
                                {
                                    for ( size_t k = 0 ; k < kount ; k++ )
                                    {
                                        out << sp << byteSwap2(buf, k*size, doSwap_);
                                        sp = " ";
                                    }
                                }
                                else if ( isLongType(type) )
                                {
                                    for ( size_t k = 0 ; k < kount ; k++ )
                                    {
                                        out << sp << byteSwap4(buf, k*size, doSwap_);
                                        sp = " ";
                                    }
                                }
                                else if ( isLongLongType(type) )
                                {
                                    for ( size_t k = 0 ; k < kount ; k++ )
                                    {
                                        out << sp << byteSwap8(buf, k*size, doSwap_);
                                        sp = " ";
                                    }
                                }
                                else if ( isRationalType(type) )
                                {
                                    for ( size_t k = 0 ; k < kount ; k++ )
                                    {
                                        uint32_t a = byteSwap4(buf, k*size+0, doSwap_);
                                        uint32_t b = byteSwap4(buf, k*size+4, doSwap_);
                                        out << sp << a << "/" << b;
                                        sp = " ";
                                    }
                                }
                                else if ( isStringType(type) )
                                    out << sp << Internal::binaryToString(makeSlice(buf, 0, static_cast<size_t>(kount)));

                                sp = kount == count ? "" : " ...";
                                out << sp << std::endl;

                                if ( option == kpsRecursive &&
                                        (tag == 0x8769 /* ExifTag */ || tag == 0x014a/*SubIFDs*/ || type == tiffIfd || type == tiffIfd8) )
                                {
                                    for ( size_t k = 0 ; k < count ; k++ )
                                    {
                                        const size_t restore = io.tell();
                                        const uint64_t ifdOffset = type == tiffIfd8?
                                            byteSwap8(buf, k*size, doSwap_):
                                            byteSwap4(buf, k*size, doSwap_);

                                        printIFD(out, option, ifdOffset, depth);
                                        io.seek(restore, BasicIo::beg);
                                    }
                                }
                                else if ( option == kpsRecursive && tag == 0x83bb /* IPTCNAA */ )
                                {
                                    if (Safe::add(count, offset) > io.size()) {
                                        throw Error(kerCorruptedMetadata);
                                    }

                                    const size_t restore = io.tell();
                                    io.seek(offset, BasicIo::beg);  // position
                                    std::vector<byte> bytes(static_cast<size_t>(count)) ;  // allocate memory
                                    // TODO: once we have C++11 use bytes.data()
                                    const size_t read_bytes = io.read(&bytes[0], static_cast<long>(count));
                                    io.seek(restore, BasicIo::beg);
                                    // TODO: once we have C++11 use bytes.data()
                                    IptcData::printStructure(out, makeSliceUntil(&bytes[0], read_bytes), depth);

                                }
                                else if ( option == kpsRecursive && tag == 0x927c /* MakerNote */ && count > 10)
                                {
                                    size_t   restore = io.tell();  // save

                                    long jump= 10           ;
                                    byte     bytes[20]          ;
                                    const char* chars = (const char*) &bytes[0] ;
                                    io.seek(dir_offset, BasicIo::beg);  // position
                                    io.read(bytes,jump    )     ;  // read
                                    bytes[jump]=0               ;
                                    if ( ::strcmp("Nikon",chars) == 0 )
                                    {
                                      // tag is an embedded tiff
                                      std::vector<byte> nikon_bytes(static_cast<size_t>(count - jump));

                                      io.read(&nikon_bytes.at(0), (long)nikon_bytes.size());
                                      MemIo memIo(&nikon_bytes.at(0), (long)count - jump); // create a file
                                      std::cerr << "Nikon makernote" << std::endl;
                                      // printTiffStructure(memIo,out,option,depth);
                                      // TODO: fix it
                                    }
                                    else
                                    {
                                        // tag is an IFD
                                        io.seek(0, BasicIo::beg);  // position
                                        std::cerr << "makernote" << std::endl;
                                        printIFD(out,option,offset,depth);
                                    }

                                    io.seek(restore,BasicIo::beg); // restore
                                }
                            }
                        }

                        const uint64_t nextDirOffset = readData(dataSize_);

                        dir_offset = tooBig ? 0 : nextDirOffset;
                        out.flush();
                    } while (dir_offset != 0);

                    if ( bPrint )
                        out << Internal::indent(depth) << "END " << io.path() << std::endl;
                }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffFinder::findObject(TiffComponent* object)
    {
        if (object->tag() == tag_ && object->group() == group_) {
            tiffComponent_ = object;
            setGo(geTraverse, false);
        }
    }

Project: exiv2
File: xmp.cpp

    size_t Xmpdatum::typeSize() const
    {
        return 0;
    }

Project: exiv2
File: value.cpp

    CommentValue::~CommentValue()
    {
    }

Project: exiv2
File: makernote_int.cpp

    PanasonicMnHeader::~PanasonicMnHeader()
    {
    }

Project: exiv2
File: crwimage.cpp

    void CrwImage::writeMetadata()
    {
#ifdef DEBUG
        std::cerr << "Writing CRW file " << io_->path() << "\n";
#endif
        // Read existing image
        DataBuf buf;
        if (io_->open() == 0) {
            IoCloser closer(*io_);
            // Ensure that this is the correct image type
            if (isCrwType(*io_, false)) {
                // Read the image into a memory buffer
                buf.alloc((long) io_->size());
                io_->read(buf.pData_, buf.size_);
                if (io_->error() || io_->eof()) {
                    buf.reset();
                }
            }
        }

        Blob blob;
        CrwParser::encode(blob, buf.pData_, (uint32_t)buf.size_, this);

        // Write new buffer to file
        MemIo::UniquePtr tempIo(new MemIo);
        assert(tempIo.get() != 0);
        tempIo->write((blob.size() > 0 ? &blob[0] : 0), static_cast<long>(blob.size()));
        io_->close();
        io_->transfer(*tempIo); // may throw

    } // CrwImage::writeMetadata

Project: exiv2
File: actions.cpp

    std::unique_ptr<Task> TaskFactory::create(TaskType type)
    {
        auto i = registry_.find(type);
        if (i != registry_.end() && i->second != 0) {
            Task* t = i->second;
            return t->clone();
        }
        return nullptr;
    }

Project: exiv2
File: value.cpp

    std::string LangAltValue::toString(long /*n*/) const
    {
        return toString(x_default);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffBinaryElement::TiffBinaryElement(uint16_t tag, IfdId group)
        : TiffEntryBase(tag, group),
        elByteOrder_(invalidByteOrder)
    {
        elDef_.idx_ = 0;
        elDef_.tiffType_ = ttUndefined;
        elDef_.count_ = 0;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffDecoder::visitDirectory(TiffDirectory* /*object*/)
    {
        // Nothing to do
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffReader::postProcess()
    {
        setMnState(); // All components to be post-processed must be from the Makernote
        postProc_ = true;
        for (PostList::const_iterator pos = postList_.begin(); pos != postList_.end(); ++pos) {
            (*pos)->accept(*this);
        }
        postProc_ = false;
        setOrigState();
    }

Project: exiv2
File: types.cpp

    Slice<const byte*> makeSlice(const DataBuf& buf, size_t begin, size_t end)
    {
        checkDataBufBounds(buf, end);
        return Slice<const byte*>(buf.pData_, begin, end);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    void TiffBinaryElement::doAccept(TiffVisitor& visitor)
    {
        visitor.visitBinaryElement(this);
    } // TiffBinaryElement::doAccept

Project: exiv2
File: types.cpp

    Exiv2::DataBuf::operator DataBufRef() { return DataBufRef(release()); }

Project: exiv2
File: image.cpp

    AccessMode ImageFactory::checkMode(ImageType type, MetadataId metadataId)
    {
        const Registry* r = find(registry, type);
        if (!r)
            throw Error(kerUnsupportedImageType, static_cast<int>(type));
        AccessMode am = amNone;
        switch (metadataId) {
        case mdNone:
            break;
        case mdExif:
            am = r->exifSupport_;
            break;
        case mdIptc:
            am = r->iptcSupport_;
            break;
        case mdXmp:
            am = r->xmpSupport_;
            break;
        case mdComment:
            am = r->commentSupport_;
            break;
        case mdIccProfile: break;

        // no default: let the compiler complain
        }
        return am;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent* TiffComponent::doAddNext(UniquePtr /*tiffComponent*/)
    {
        return 0;
    } // TiffComponent::doAddNext

Project: exiv2
File: makernote_int.cpp

    bool Nikon2MnHeader::read(const byte* pData,
                              uint32_t    size,
                              ByteOrder   /*byteOrder*/)
    {
        if (!pData || size < sizeOfSignature()) return false;
        if (0 != memcmp(pData, signature_, 6)) return false;
        buf_.alloc(sizeOfSignature());
        std::memcpy(buf_.pData_, pData, buf_.size_);
        start_ = sizeOfSignature();
        return true;
    } // Nikon2MnHeader::read

Project: exiv2
File: basicio.cpp

    std::string XPathIo::writeDataToFile(const std::string& orgPath) {
        Protocol prot = fileProtocol(orgPath);

        // generating the name for temp file.
        std::time_t timestamp = std::time(nullptr);
        std::stringstream ss;
        ss << timestamp << XPathIo::TEMP_FILE_EXT;
        std::string path = ss.str();
        std::ofstream fs(path.c_str(), std::ios::out | std::ios::binary | std::ios::trunc);

        if (prot == pStdin) {
            if (isatty(fileno(stdin)))
                throw Error(kerInvalidIccProfile);
#if defined(_MSC_VER) || defined(__MINGW__)
            // convert stdin to binary
            if (_setmode(_fileno(stdin), _O_BINARY) == -1)
                throw Error(kerInvalidXMP);
#endif
            // read stdin and write to the temp file.
            char readBuf[100*1024];
            std::streamsize readBufSize = 0;
            do {
                std::cin.read(readBuf, sizeof(readBuf));
                readBufSize = std::cin.gcount();
                if (readBufSize > 0) {
                    fs.write (readBuf, readBufSize);
                }
            } while(readBufSize);
        } else if (prot == pDataUri) {
            // read data uri and write to the temp file.
            size_t base64Pos = orgPath.find("base64,");
            if (base64Pos == std::string::npos)
                throw Error(kerErrorMessage, "No base64 data");

            std::string data = orgPath.substr(base64Pos+7);
            char* decodeData = new char[data.length()];
            long size = base64decode(data.c_str(), decodeData, data.length());
            if (size > 0)
                fs.write(decodeData, size);
            else
                throw Error(kerErrorMessage, "Unable to decode base 64.");
            delete[] decodeData;
        }

        fs.close();
        return path;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    TiffDecoder::TiffDecoder(
        ExifData&            exifData,
        IptcData&            iptcData,
        XmpData&             xmpData,
        TiffComponent* const pRoot,
        FindDecoderFct       findDecoderFct
    )
        : exifData_(exifData),
          iptcData_(iptcData),
          xmpData_(xmpData),
          pRoot_(pRoot),
          findDecoderFct_(findDecoderFct),
          decodedIptc_(false)
    {
        assert(pRoot != 0);

        exifData_.clear();
        iptcData_.clear();
        xmpData_.clear();

        // Find camera make
        TiffFinder finder(0x010f, ifd0Id);
        pRoot_->accept(finder);
        TiffEntryBase* te = dynamic_cast<TiffEntryBase*>(finder.result());
        if (te && te->pValue()) {
            make_ = te->pValue()->toString();
        }
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffImageEntry::doWriteData(IoWrapper& ioWrapper,
                                         ByteOrder byteOrder,
                                         int32_t   /*offset*/,
                                         uint32_t  /*dataIdx*/,
                                         uint32_t& /*imageIdx*/) const
    {
        uint32_t len = 0;
        // For makernotes, write TIFF image data to the data area
        if (group() > mnId) { // Todo: FIX THIS HACK!!!
            len = writeImage(ioWrapper, byteOrder);
        }
        return len;
    } // TiffImageEntry::doWriteData

Project: exiv2
File: value.cpp

    std::string DataValue::toString(long n) const
    {
        std::ostringstream os;
        os << static_cast<int>(value_[n]);
        ok_ = !os.fail();
        return os.str();
    }

Project: exiv2
File: actions.cpp

    int Print::printPreviewList()
    {
        if (!Exiv2::fileExists(path_, true)) {
            std::cerr << path_ << ": " << _("Failed to open the file\n");
            return -1;
        }
        Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open(path_);
        assert(image.get() != 0);
        image->readMetadata();
        bool const manyFiles = Params::instance().files_.size() > 1;
        int cnt = 0;
        Exiv2::PreviewManager pm(*image);
        Exiv2::PreviewPropertiesList list = pm.getPreviewProperties();
        for (auto pos = list.begin(); pos != list.end(); ++pos) {
            if (manyFiles) {
                std::cout << std::setfill(' ') << std::left << std::setw(20) << path_ << "  ";
            }
            std::cout << _("Preview") << " " << ++cnt << ": " << pos->mimeType_ << ", ";
            if (pos->width_ != 0 && pos->height_ != 0) {
                std::cout << pos->width_ << "x" << pos->height_ << " " << _("pixels") << ", ";
            }
            std::cout << pos->size_ << " " << _("bytes") << "\n";
        }
        return 0;
    }

Project: exiv2
File: image.cpp

    const XmpData& Image::xmpData() const
    {
        return xmpData_;
    }

Project: exiv2
File: crwimage_int.cpp

    void CrwMap::encode0x1810(const Image&      image,
                              const CrwMapping* pCrwMapping,
                                    CiffHeader* pHead)
    {
        assert(pCrwMapping != 0);
        assert(pHead != 0);

        const ExifKey kX("Exif.Photo.PixelXDimension");
        const ExifKey kY("Exif.Photo.PixelYDimension");
        const ExifKey kO("Exif.Image.Orientation");
        const ExifData &exivData = image.exifData();
        const ExifData::const_iterator edX = exivData.findKey(kX);
        const ExifData::const_iterator edY = exivData.findKey(kY);
        const ExifData::const_iterator edO = exivData.findKey(kO);
        const ExifData::const_iterator edEnd = exivData.end();

        CiffComponent* cc = pHead->findComponent(pCrwMapping->crwTagId_,
                                                 pCrwMapping->crwDir_);
        if (edX != edEnd || edY != edEnd || edO != edEnd) {
            size_t size = 28;
            if (cc && cc->size() > size)
                size = cc->size();
            DataBuf buf(size);
            std::memset(buf.pData_, 0x0, buf.size_);
            if (cc) std::memcpy(buf.pData_ + 8, cc->pData() + 8, cc->size() - 8);
            if (edX != edEnd && edX->size() == 4) {
                edX->copy(buf.pData_, pHead->byteOrder());
            }
            if (edY != edEnd && edY->size() == 4) {
                edY->copy(buf.pData_ + 4, pHead->byteOrder());
            }
            int32_t d = 0;
            if (edO != edEnd && edO->count() > 0 && edO->typeId() == unsignedShort) {
                d = RotationMap::degrees(static_cast<uint16_t>(edO->toLong()));
            }
            l2Data(buf.pData_ + 12, d, pHead->byteOrder());
            pHead->add(pCrwMapping->crwTagId_, pCrwMapping->crwDir_, buf);
        }
        else {
            pHead->remove(pCrwMapping->crwTagId_, pCrwMapping->crwDir_);
        }
    } // CrwMap::encode0x1810

Project: exiv2
File: pgfimage.cpp

    static uint32_t byteSwap_(Exiv2::DataBuf& buf,size_t offset,bool bSwap)
    {
        uint32_t v;
        char*    p = (char*) &v;
        int      i;
        for ( i = 0 ; i < 4 ; i++ ) p[i] = buf.pData_[offset+i];
        uint32_t result = byteSwap_(v,bSwap);
        p               = (char*) &result;
        for ( i = 0 ; i < 4 ; i++ ) buf.pData_[offset+i] = p[i];
        return result;
    }

Project: exiv2
File: rafimage.cpp

    void RafImage::readMetadata()
    {
#ifdef DEBUG
        std::cerr << "Reading RAF file " << io_->path() << "\n";
#endif
        if (io_->open() != 0) throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        IoCloser closer(*io_);
        // Ensure that this is the correct image type
        if (!isRafType(*io_, false)) {
            if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);
            throw Error(kerNotAnImage, "RAF");
        }

        clearMetadata();

        if (io_->seek(84,BasicIo::beg) != 0) throw Error(kerFailedToReadImageData);
        byte jpg_img_offset [4];
        if (io_->read(jpg_img_offset, 4) != 4) throw Error(kerFailedToReadImageData);
        byte jpg_img_length [4];
        if (io_->read(jpg_img_length, 4) != 4) throw Error(kerFailedToReadImageData);
        uint32_t jpg_img_off_u32 = Exiv2::getULong((const byte *) jpg_img_offset, bigEndian);
        uint32_t jpg_img_len_u32 = Exiv2::getULong((const byte *) jpg_img_length, bigEndian);

        enforce(Safe::add(jpg_img_off_u32, jpg_img_len_u32) <= io_->size(), kerCorruptedMetadata);

#if LONG_MAX < UINT_MAX
        enforce(jpg_img_off_u32 <= static_cast<uint32_t>(std::numeric_limits<long>::max()),
                kerCorruptedMetadata);
        enforce(jpg_img_len_u32 <= static_cast<uint32_t>(std::numeric_limits<long>::max()),
                kerCorruptedMetadata);
#endif

        long jpg_img_off = static_cast<long>(jpg_img_off_u32);
        long jpg_img_len = static_cast<long>(jpg_img_len_u32);

        enforce(jpg_img_len >= 12, kerCorruptedMetadata);

        DataBuf buf(jpg_img_len - 12);
        if (io_->seek(jpg_img_off + 12,BasicIo::beg) != 0) throw Error(kerFailedToReadImageData);
        io_->read(buf.pData_, buf.size_);
        if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData);

        io_->seek(0,BasicIo::beg); // rewind

        ByteOrder bo = TiffParser::decode(exifData_,
                                          iptcData_,
                                          xmpData_,
                                          buf.pData_,
                                          static_cast<std::uint32_t>(buf.size_));

        exifData_["Exif.Image2.JPEGInterchangeFormat"] = getULong(jpg_img_offset, bigEndian);
        exifData_["Exif.Image2.JPEGInterchangeFormatLength"] = getULong(jpg_img_length, bigEndian);

        setByteOrder(bo);
    } // RafImage::readMetadata

Project: exiv2
File: value.cpp

    LangAltValue* LangAltValue::clone_() const
    {
        return new LangAltValue(*this);
    }

Project: exiv2
File: preview.cpp

    PreviewManager::PreviewManager(const Image& image)
        : image_(image)
    {
    }

Project: exiv2
File: types.cpp

    DataBuf::DataBuf(const DataBufRef &rhs) : pData_(rhs.p.first), size_(rhs.p.second) {}

Project: exiv2
File: value.cpp

    std::ostream& CommentValue::write(std::ostream& os) const
    {
        CharsetId csId = charsetId();
        if (csId != undefined) {
            os << "charset=\"" << CharsetInfo::name(csId) << "\" ";
        }
        return os << comment();
    }

Project: exiv2
File: pngchunk_int.cpp

        void PngChunk::parseChunkContent(Image* pImage, const byte* key, size_t keySize, const DataBuf arr)
        {
            // We look if an ImageMagick EXIF raw profile exist.

            if (keySize >= 21 &&
                (memcmp("Raw profile type exif", key, 21) == 0 || memcmp("Raw profile type APP1", key, 21) == 0) &&
                pImage->exifData().empty()) {
                DataBuf exifData = readRawProfile(arr, false);
                const size_t length = exifData.size_;

                if (length > 0) {
                    // Find the position of Exif header in bytes array.
                    bool foundPos{false};
                    size_t pos{0};
                    const std::array<byte, 6> exifHeader{0x45, 0x78, 0x69, 0x66, 0x00, 0x00};
                    const auto& it =
                        std::search(exifData.cbegin(), exifData.cend(), exifHeader.cbegin(), exifHeader.cend());
                    if (it != exifData.cend()) {
                        pos = it - exifData.cbegin() + exifHeader.size();
                        foundPos = true;
                    }

                    // If found it, store only these data at from this place.
                    if (foundPos) {
#ifdef DEBUG
                        std::cout << "Exiv2::PngChunk::parseChunkContent: Exif header found at position " << pos
                                  << "\n";
#endif
                        ByteOrder bo = TiffParser::decode(pImage->exifData(), pImage->iptcData(), pImage->xmpData(),
                                                          exifData.pData_ + pos, (uint32_t)(length - pos));
                        pImage->setByteOrder(bo);
                    } else {
#ifndef SUPPRESS_WARNINGS
                        EXV_WARNING << "Failed to decode Exif metadata.\n";
#endif
                        pImage->exifData().clear();
                    }
                }
            }

            // We look if an ImageMagick IPTC raw profile exist.

            if (keySize >= 21 && memcmp("Raw profile type iptc", key, 21) == 0 && pImage->iptcData().empty()) {
                DataBuf psData = readRawProfile(arr, false);
                if (psData.size_ > 0) {
                    Blob iptcBlob;
                    const byte* record = 0;
                    uint32_t sizeIptc = 0;
                    uint32_t sizeHdr = 0;

                    const byte* pEnd = psData.pData_ + psData.size_;
                    const byte* pCur = psData.pData_;
                    while (pCur < pEnd && 0 == Photoshop::locateIptcIrb(pCur, static_cast<long>(pEnd - pCur), &record,
                                                                        &sizeHdr, &sizeIptc)) {
                        if (sizeIptc) {
#ifdef DEBUG
                            std::cerr << "Found IPTC IRB, size = " << sizeIptc << "\n";
#endif
                            append(iptcBlob, record + sizeHdr, sizeIptc);
                        }
                        pCur = record + sizeHdr + sizeIptc;
                        pCur += (sizeIptc & 1);
                    }
                    if (iptcBlob.size() > 0 &&
                        IptcParser::decode(pImage->iptcData(), &iptcBlob[0], static_cast<uint32_t>(iptcBlob.size()))) {
#ifndef SUPPRESS_WARNINGS
                        EXV_WARNING << "Failed to decode IPTC metadata.\n";
#endif
                        pImage->clearIptcData();
                    }
                    // If there is no IRB, try to decode the complete chunk data
                    if (iptcBlob.empty() && IptcParser::decode(pImage->iptcData(), psData.pData_, psData.size_)) {
#ifndef SUPPRESS_WARNINGS
                        EXV_WARNING << "Failed to decode IPTC metadata.\n";
#endif
                        pImage->clearIptcData();
                    }
                }  // if (psData.size_ > 0)
            }

            // We look if an ImageMagick XMP raw profile exist.

            if (keySize >= 20 && memcmp("Raw profile type xmp", key, 20) == 0 && pImage->xmpData().empty()) {
                DataBuf xmpBuf = readRawProfile(arr, false);
                const size_t length = xmpBuf.size_;

                if (length > 0) {
                    std::string& xmpPacket = pImage->xmpPacket();
                    xmpPacket.assign(reinterpret_cast<char*>(xmpBuf.pData_), length);
                    std::string::size_type idx = xmpPacket.find_first_of('<');
                    if (idx != std::string::npos && idx > 0) {
#ifndef SUPPRESS_WARNINGS
                        EXV_WARNING << "Removing " << idx << " characters from the beginning of the XMP packet\n";
#endif
                        xmpPacket = xmpPacket.substr(idx);
                    }
                    if (XmpParser::decode(pImage->xmpData(), xmpPacket)) {
#ifndef SUPPRESS_WARNINGS
                        EXV_WARNING << "Failed to decode XMP metadata.\n";
#endif
                    }
                }
            }

            // We look if an Adobe XMP string exist.

            if (keySize >= 17 && memcmp("XML:com.adobe.xmp", key, 17) == 0 && pImage->xmpData().empty()) {
                if (arr.size_ > 0) {
                    std::string& xmpPacket = pImage->xmpPacket();
                    xmpPacket.assign(reinterpret_cast<char*>(arr.pData_), arr.size_);
                    std::string::size_type idx = xmpPacket.find_first_of('<');
                    if (idx != std::string::npos && idx > 0) {
#ifndef SUPPRESS_WARNINGS
                        EXV_WARNING << "Removing " << idx << " characters "
                                    << "from the beginning of the XMP packet\n";
#endif
                        xmpPacket = xmpPacket.substr(idx);
                    }
                    if (XmpParser::decode(pImage->xmpData(), xmpPacket)) {
#ifndef SUPPRESS_WARNINGS
                        EXV_WARNING << "Failed to decode XMP metadata.\n";
#endif
                    }
                }
            }

            // We look if a comments string exist. Note than we use only 'Description' keyword which
            // is dedicaced to store long comments. 'Comment' keyword is ignored.

            if (keySize >= 11 && memcmp("Description", key, 11) == 0 && pImage->comment().empty()) {
                pImage->setComment(std::string(reinterpret_cast<char*>(arr.pData_), arr.size_));
            }

        }  // PngChunk::parseChunkContent

Project: exiv2
File: makernote_int.cpp

    uint32_t PentaxDngMnHeader::ifdOffset() const
    {
        return sizeOfSignature();
    }

Project: exiv2
File: exif.cpp

    ExifData::iterator ExifData::findKey(const ExifKey& key)
    {
        return std::find_if(exifMetadata_.begin(), exifMetadata_.end(),
                            FindExifdatumByKey(key.key()));
    }

Project: exiv2
File: value.cpp

    DateValue::~DateValue()
    {
    }

Project: exiv2
File: image.cpp

        bool operator==(const ImageType& imageType) const
        { return imageType == imageType_; }

Project: exiv2
File: actions.cpp

    std::unique_ptr<FixIso> FixIso::clone() const
    {
        return std::unique_ptr<FixIso>(clone_());
    }

Project: exiv2
File: preview.cpp

    const byte* PreviewImage::pData() const
    {
        return pData_;
    }

Project: exiv2
File: value.cpp

    int TimeValue::scanTime3(const char* buf, const char* format)
    {
        int rc = 1;
        Time t;
        int scanned = sscanf(buf, format, &t.hour, &t.minute, &t.second);
        if (   scanned  == 3
            && t.hour   >= 0 && t.hour   < 24
            && t.minute >= 0 && t.minute < 60
            && t.second >= 0 && t.second < 60) {
            time_ = t;
            rc = 0;
        }
        return rc;
    }

Project: exiv2
File: actions.cpp

    int Timestamp::read(struct tm* tm)
    {
        int rc = 1;
        time_t t = mktime(tm);  // interpret tm according to current timezone settings
        if (t != (time_t)-1) {
            rc = 0;
            actime_ = t;
            modtime_ = t;
        }
        return rc;
    }

Project: exiv2
File: jpgimage.cpp

    bool isJpegType(BasicIo& iIo, bool advance)
    {
        bool result = true;
        byte tmpBuf[2];
        iIo.read(tmpBuf, 2);
        if (iIo.error() || iIo.eof()) return false;

        if (0xff != tmpBuf[0] || JpegImage::soi_ != tmpBuf[1]) {
            result = false;
        }
        if (!advance || !result ) iIo.seek(-2, BasicIo::cur);
        return result;
    }

Project: exiv2
File: value.cpp

    void DateValue::setDate(const Date& src)
    {
        date_.year = src.year;
        date_.month = src.month;
        date_.day = src.day;
    }

Project: exiv2
File: actions.cpp

    std::unique_ptr<Print> Print::clone() const
    {
        return std::unique_ptr<Print>(clone_());
    }

Project: exiv2
File: basicio.cpp

    MemIo::MemIo(const byte* data, size_t size)
        : p_(new Impl(data, size))
    {
    }

Project: exiv2
File: image.cpp

    bool Image::isPrintICC(uint16_t type, Exiv2::PrintStructureOption option)
    {
        return type == 0x8773 && option == kpsIccProfile;
    }

Project: exiv2
File: makernote_int.cpp

    size_t PentaxMnHeader::size() const
    {
        return header_.size_;
    }

Project: exiv2
File: image.cpp

    ExifData& Image::exifData()
    {
        return exifData_;
    }

Project: exiv2
File: pngchunk_int.cpp

        DataBuf PngChunk::keyTXTChunk(const DataBuf& data, bool stripHeader)
        {
            // From a tEXt, zTXt, or iTXt chunk,
            // we get the key, it's a null terminated string at the chunk start
            const size_t offset = stripHeader ? 8 : 0;
            if (data.size_ <= offset)
                throw Error(kerFailedToReadImageData);
            const byte* key = data.pData_ + offset;

            // Find null string at end of key.
            size_t keysize = 0;
            while (key[keysize] != 0) {
                keysize++;
                // look if keysize is valid.
                if (keysize + offset >= data.size_)
                    throw Error(kerFailedToReadImageData);
            }

            return DataBuf(key, keysize);

        }  // PngChunk::keyTXTChunk

Project: exiv2
File: makernote_int.cpp

    bool Casio2MnHeader::read(const byte* pData,
                            uint32_t    size,
                            ByteOrder   /*byteOrder*/)
    {
        if (!pData || size < sizeOfSignature()) return false;
        if (0 != memcmp(pData, signature_, sizeOfSignature())) return false;
        buf_.alloc(sizeOfSignature());
        std::memcpy(buf_.pData_, pData, buf_.size_);
        start_ = sizeOfSignature();
        return true;
    } // Casio2MnHeader::read

Project: exiv2
File: exif.cpp

    size_t Exifdatum::typeSize() const
    {
        return TypeInfo::typeSize(typeId());
    }

Project: exiv2
File: makernote_int.cpp

    MnHeader::~MnHeader()
    {
    }

Project: exiv2
File: makernote_int.cpp

    TiffComponent* newSonyMn(uint16_t    tag,
                             IfdId       group,
                             IfdId       /*mnGroup*/,
                             const byte* pData,
                             uint32_t    size,
                             ByteOrder   /*byteOrder*/)
    {
        // If there is no "SONY DSC " string we assume it's a simple IFD Makernote
        if (size < 12 ||   std::string(reinterpret_cast<const char*>(pData), 12)
                        != std::string("SONY DSC \0\0\0", 12)) {
            // Require at least an IFD with 1 entry
            if (size < 18) return 0;
            return newSony2Mn2(tag, group, sony2Id);
        }
        // Require at least the header and an IFD with 1 entry, but without a next pointer
        if (size < SonyMnHeader::sizeOfSignature() + 14) return 0;
        return newSony1Mn2(tag, group, sony1Id);
    }

Project: exiv2
File: pgfimage.cpp

    bool isPgfType(BasicIo& iIo, bool advance)
    {
        const int32_t len = 3;
        byte buf[len];
        iIo.read(buf, len);
        if (iIo.error() || iIo.eof())
        {
            return false;
        }
        int rc = memcmp(buf, pgfSignature, 3);
        if (!advance || rc != 0)
        {
            iIo.seek(-len, BasicIo::cur);
        }

        return rc == 0;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffIfdMakernote::doSizeData() const
    {
        assert(false);
        return 0;
    } // TiffIfdMakernote::doSizeData

Project: exiv2
File: makernote_int.cpp

    uint32_t Nikon2MnHeader::ifdOffset() const
    {
        return start_;
    }

Project: exiv2
File: preview.cpp

    DataBuf PreviewImage::copy() const
    {
        return DataBuf(pData_, size_);
    }

Project: exiv2
File: exif.cpp

    Exifdatum& Exifdatum::operator=(const std::string& value)
    {
        setValue(value);
        return *this;
    }

Project: exiv2
File: convert.cpp

        void setErase(bool onoff =true) { erase_ = onoff; }

Project: exiv2
File: bigtiffimage.cpp

            Header(): byteOrder_(invalidByteOrder), version_(-1), data_size_(0), dir_offset_(0) {}

Project: exiv2
File: tiffcomposite_int.cpp

    TiffEntryBase::TiffEntryBase(uint16_t tag, IfdId group, TiffType tiffType)
        : TiffComponent(tag, group),
          tiffType_(tiffType), count_(0), offset_(0),
          size_(0), pData_(0), isMalloced_(false), idx_(0),
          pValue_(0)
    {
    }

Project: exiv2
File: value.cpp

    std::ostream& LangAltValue::write(std::ostream& os) const
    {
        bool        first     = true;

        // Write the default entry first
        ValueType::const_iterator i = value_.find(x_default);
        if (i != value_.end()) {
            os << "lang=\"" << i->first << "\" " << i->second;
            first = false;
        }

        // Write the others
        for (i = value_.begin(); i != value_.end(); ++i) {
            if (i->first != x_default ) {
                if (!first) os << ", ";
                os << "lang=\"" << i->first << "\" " << i->second;
                first = false;
            }
        }
        return os;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent::~TiffComponent()
    {
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffReader::readDataEntryBase(TiffDataEntryBase* object)
    {
        assert(object != 0);

        readTiffEntry(object);
        TiffFinder finder(object->szTag(), object->szGroup());
        pRoot_->accept(finder);
        TiffEntryBase* te = dynamic_cast<TiffEntryBase*>(finder.result());
        if (te && te->pValue()) {
            object->setStrips(te->pValue(), pData_, size_, baseOffset());
        }
    }

Project: exiv2
File: xmp.cpp

        bool operator()(const Exiv2::Xmpdatum& xmpdatum) const
            { return key_ == xmpdatum.key(); }

Project: exiv2
File: exif.cpp

    float Exifdatum::toFloat(long n) const
    {
        return value_.get() == 0 ? -1 : value_->toFloat(n);
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::visitBinaryArray(TiffBinaryArray* object)
    {
        if (object->cfg() == 0 || !object->decoded()) {
            encodeTiffComponent(object);
        }
    }

Project: exiv2
File: value.cpp

    int CommentValue::read(const byte* buf, size_t len, ByteOrder byteOrder)
    {
        byteOrder_ = byteOrder;
        return StringValueBase::read(buf, len, byteOrder);
    }

Project: exiv2
File: convert.cpp

    void Converter::cnvFromXmp()
    {
        for (unsigned int i = 0; i < EXV_COUNTOF(conversion_); ++i) {
            const Conversion& c = conversion_[i];
            if (   (c.metadataId_ == mdExif && exifData_)
                || (c.metadataId_ == mdIptc && iptcData_)) {
                EXV_CALL_MEMBER_FN(*this, c.key2ToKey1_)(c.key2_, c.key1_);
            }
        }
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffIfdMakernote::doCount() const
    {
        return ifd_.count();
    } // TiffIfdMakernote::doCount

Project: exiv2
File: basicio.cpp

    DataBuf readFile(const std::string& path)
    {
        FileIo file(path);
        if (file.open("rb") != 0) {
            throw Error(kerFileOpenFailed, path, "rb", strError());
        }
        struct stat st;
        if (0 != ::stat(path.c_str(), &st)) {
            throw Error(kerCallFailed, path, strError(), "::stat");
        }
        DataBuf buf(st.st_size);
        size_t len = file.read(buf.pData_, buf.size_);
        if (len != buf.size_) {
            throw Error(kerCallFailed, path, strError(), "FileIo::read");
        }
        return buf;
    }

Project: exiv2
File: value.cpp

    DateValue::DateValue()
        : Value(date)
    {
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffEntryBase::doWrite(IoWrapper& ioWrapper,
                                    ByteOrder byteOrder,
                                    int32_t   /*offset*/,
                                    uint32_t  /*valueIdx*/,
                                    uint32_t  /*dataIdx*/,
                                    uint32_t& /*imageIdx*/)
    {
        if (!pValue_) return 0;

        DataBuf buf(pValue_->size());
        pValue_->copy(buf.pData_, byteOrder);
        ioWrapper.write(buf.pData_, buf.size_);
        return (uint32_t)buf.size_;
    } // TiffEntryBase::doWrite

Project: exiv2
File: bigtiffimage.cpp

            bool isValid() const
            {
                return version_ != -1;
            }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::visitEntry(TiffEntry* object)
    {
        encodeTiffComponent(object);
    }

Project: exiv2
File: actions.cpp

    static std::string temporaryPath()
    {
        static int count = 0;

#if defined(_MSC_VER) || defined(__MINGW__)
        EnterCriticalSection(&cs);
        char lpTempPathBuffer[MAX_PATH];
        GetTempPath(MAX_PATH, lpTempPathBuffer);
        std::string tmp(lpTempPathBuffer);
        tmp += "\\";
        HANDLE process = 0;
        DWORD pid = ::GetProcessId(process);
#else
        pid_t pid = ::getpid();
        pthread_mutex_lock(&cs);
        std::string tmp = "/tmp/";
#endif
        char sCount[12];
        sprintf(sCount, "_%d", ++count);

        std::string result = tmp + Exiv2::toString(pid) + sCount;
        if (Exiv2::fileExists(result))
            std::remove(result.c_str());

#if defined(_MSC_VER) || defined(__MINGW__)
        LeaveCriticalSection(&cs);
#else
        pthread_mutex_unlock(&cs);
#endif

        return result;
    }

Project: exiv2
File: xmp.cpp

    Xmpdatum::Impl::Impl(const Impl& rhs)
    {
        if (rhs.key_.get() != 0) key_ = rhs.key_->clone(); // deep copy
        if (rhs.value_.get() != 0) value_ = rhs.value_->clone(); // deep copy
    }

Project: exiv2
File: makernote_int.cpp

    uint32_t Casio2MnHeader::ifdOffset() const
    {
        return start_;
    }

Project: exiv2
File: tiffimage.cpp

    TiffImage::TiffImage(BasicIo::UniquePtr io, bool /*create*/)
        : Image(ImageType::tiff, mdExif | mdIptc | mdXmp, std::move(io)),
          pixelWidth_(0), pixelHeight_(0)
    {
    } // TiffImage::TiffImage

Project: exiv2
File: actions.cpp

    TaskFactory::TaskFactory()
        : registry_{
              {adjust, new Adjust}, {print, new Print},     {rename, new Rename},
              {erase, new Erase},   {extract, new Extract}, {insert, new Insert},
              {modify, new Modify}, {fixiso, new FixIso},   {fixcom, new FixCom},
          }
    {
    }

Project: exiv2
File: exif.cpp

    void ExifData::add(const ExifKey& key, const Value* pValue)
    {
        add(Exifdatum(key, pValue));
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffFinder::visitDirectory(TiffDirectory* object)
    {
        findObject(object);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent* TiffMnEntry::doAddChild(TiffComponent::UniquePtr tiffComponent)
    {
        TiffComponent* tc = 0;
        if (mn_) {
            tc =  mn_->addChild(std::move(tiffComponent));
        }
        return tc;
    } // TiffMnEntry::doAddChild

Project: exiv2
File: makernote_int.cpp

    uint32_t Olympus2MnHeader::ifdOffset() const
    {
        return sizeOfSignature();
    }

Project: exiv2
File: convert.cpp

    void Converter::cnvIptcValue(const char* from, const char* to)
    {
        Exiv2::IptcData::iterator pos = iptcData_->findKey(IptcKey(from));
        if (pos == iptcData_->end()) return;
        if (!prepareXmpTarget(to)) return;
        while (pos != iptcData_->end()) {
            if (pos->key() == from) {
                std::string value = pos->toString();
                if (!pos->value().ok()) {
#ifndef SUPPRESS_WARNINGS
                    EXV_WARNING << "Failed to convert " << from << " to " << to << "\n";
#endif
                    ++pos;
                    continue;
                }
                if (iptcCharset_) convertStringCharset(value, iptcCharset_, "UTF-8");
                (*xmpData_)[to] = value;
                if (erase_) {
                    pos = iptcData_->erase(pos);
                    continue;
                }
            }
            ++pos;
        }
    }

Project: exiv2
File: makernote_int.cpp

    OlympusMnHeader::~OlympusMnHeader()
    {
    }

Project: exiv2
File: image.cpp

    void Image::clearMetadata()
    {
        clearExifData();
        clearIptcData();
        clearXmpPacket();
        clearXmpData();
        clearComment();
        clearIccProfile();
    }

Project: exiv2
File: tiffvisitor_int.cpp

    ByteOrder TiffReader::byteOrder() const
    {
        assert(pState_);
        return pState_->byteOrder();
    }

Project: exiv2
File: makernote_int.cpp

    constexpr uint32_t Olympus2MnHeader::sizeOfSignature()
    {
        return sizeof(signature_);
    }

Project: exiv2
File: actions.cpp

    bool Print::grepTag(const std::string& key)
    {
        bool result = Params::instance().greps_.empty();
        for (auto g = Params::instance().greps_.begin(); !result && g != Params::instance().greps_.end(); ++g)
        {
            std::smatch m;
            result = std::regex_search(key, m, *g);
        }
        return result;
    }

Project: exiv2
File: preview.cpp

    Loader::UniquePtr createLoaderXmpJpeg(PreviewId id, const Image &image, int parIdx)
    {
        return Loader::UniquePtr(new LoaderXmpJpeg(id, image, parIdx));
    }

Project: exiv2
File: value.cpp

    long StringValueBase::size() const
    {
        return static_cast<long>(value_.size());
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffIfdMakernote::doWriteImage(IoWrapper& ioWrapper,
                                            ByteOrder byteOrder) const
    {
        if (this->byteOrder() != invalidByteOrder) {
            byteOrder = this->byteOrder();
        }
        uint32_t len = ifd_.writeImage(ioWrapper, byteOrder);
        return len;
    } // TiffIfdMakernote::doWriteImage

Project: exiv2
File: value.cpp

    float XmpArrayValue::toFloat(long n) const
    {
        return parseFloat(value_[n], ok_);
    }

Project: exiv2
File: types.cpp

    long TypeInfo::typeSize(TypeId typeId)
    {
        const TypeInfoTable* tit = find(typeInfoTable, typeId);
        if (!tit) return 0;
        return tit->size_;
    }

Project: exiv2
File: exif.cpp

    size_t Exifdatum::size() const
    {
        return value_.get() == 0 ? 0 : value_->size();
    }

Project: exiv2
File: iptc.cpp

    uint16_t Iptcdatum::tag() const
    {
        return key_.get() == 0 ? 0 : key_->tag();
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffDecoder::visitDataEntry(TiffDataEntry* object)
    {
        decodeTiffEntry(object);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent* TiffMnEntry::doAddPath(uint16_t tag,
                                          TiffPath& tiffPath,
                                          TiffComponent* const pRoot,
                                          TiffComponent::UniquePtr object)
    {
        assert(!tiffPath.empty());
        const TiffPathItem tpi1 = tiffPath.top();
        tiffPath.pop();
        if (tiffPath.empty()) {
            // If the last element in the path is the makernote tag itself we're done
            return this;
        }
        const TiffPathItem tpi2 = tiffPath.top();
        tiffPath.push(tpi1);
        if (mn_ == 0) {
            mnGroup_ = tpi2.group();
            mn_ = TiffMnCreator::create(tpi1.tag(), tpi1.group(), mnGroup_);
            assert(mn_);
        }
        return mn_->addPath(tag, tiffPath, pRoot, std::move(object));
    } // TiffMnEntry::doAddPath

Project: exiv2
File: iptc.cpp

    void Iptcdatum::setValue(const Value* pValue)
    {
        value_.reset();
        if (pValue) value_ = pValue->clone();
    }

Project: exiv2
File: actions.cpp

    } catch (const Exiv2::AnyError& e) {
        std::cerr << "Exiv2 exception in adjust action for file " << path << ":\n" << e << "\n";
        return 1;
    }

Project: exiv2
File: actions.cpp

    std::unique_ptr<Erase> Erase::clone() const
    {
        return std::unique_ptr<Erase>(clone_());
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffImageEntry::doWrite(IoWrapper& ioWrapper,
                                     ByteOrder byteOrder,
                                     int32_t   offset,
                                     uint32_t  /*valueIdx*/,
                                     uint32_t  dataIdx,
                                     uint32_t& imageIdx)
    {
        uint32_t o2 = imageIdx;
        // For makernotes, write TIFF image data to the data area
        if (group() > mnId) o2 = offset + dataIdx;
#ifdef DEBUG
        std::cerr << "TiffImageEntry, Directory " << groupName(group())
                  << ", entry 0x" << std::setw(4)
                  << std::setfill('0') << std::hex << tag() << std::dec
                  << ": Writing offset " << o2 << "\n";
#endif
        DataBuf buf(static_cast<long>(strips_.size()) * 4);
        memset(buf.pData_, 0x0, buf.size_);
        uint32_t idx = 0;
        for (Strips::const_iterator i = strips_.begin(); i != strips_.end(); ++i) {
            idx += writeOffset(buf.pData_ + idx, o2, tiffType(), byteOrder);
            o2 += i->second;
            o2 += i->second & 1;                // Align strip data to word boundary
            if (!(group() > mnId)) {            // Todo: FIX THIS!! SHOULDN'T USE >
                imageIdx += i->second;
                imageIdx += i->second & 1;      // Align strip data to word boundary
            }
        }
        ioWrapper.write(buf.pData_, buf.size_);
        return (uint32_t)buf.size_;
    } // TiffImageEntry::doWrite

Project: exiv2
File: value.cpp

    std::string Value::toString(long /*n*/) const
    {
        return toString();
    }

Project: exiv2
File: webpimage.cpp

    void WebPImage::decodeChunks(long filesize)
    {
        DataBuf   chunkId(5);
        byte      size_buff[WEBP_TAG_SIZE];
        bool      has_canvas_data = false;

#ifdef DEBUG
        std::cout << "Reading metadata" << std::endl;
#endif

        chunkId.pData_[4] = '\0' ;
        while (!io_->eof() && io_->tell() < filesize) {
            io_->readOrThrow(chunkId.pData_, WEBP_TAG_SIZE);
            io_->readOrThrow(size_buff, WEBP_TAG_SIZE);

            const uint32_t size_u32 = Exiv2::getULong(size_buff, littleEndian);

            // Check that `size_u32` is safe to cast to `long`. The `#if`
            // is needed because this check is redundant on platforms where
            // `long` is 64 bits.  On those platforms, it causes the build
            // to fail due to a compiler warning in clang.
#if LONG_MAX < UINT_MAX
            enforce(size_u32 <= static_cast<size_t>(std::numeric_limits<long>::max()),
                    Exiv2::kerCorruptedMetadata);
#endif
            const long size = static_cast<long>(size_u32);

            // Check that `size` is within bounds.
            enforce(io_->tell() <= filesize, Exiv2::kerCorruptedMetadata);
            enforce(size <= (filesize - io_->tell()), Exiv2::kerCorruptedMetadata);

            DataBuf payload(size);

            if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_canvas_data) {
                enforce(size >= 10, Exiv2::kerCorruptedMetadata);

                has_canvas_data = true;
                byte size_buf[WEBP_TAG_SIZE];

                io_->readOrThrow(payload.pData_, payload.size_);

                // Fetch width
                memcpy(&size_buf, &payload.pData_[4], 3);
                size_buf[3] = 0;
                pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) + 1;

                // Fetch height
                memcpy(&size_buf, &payload.pData_[7], 3);
                size_buf[3] = 0;
                pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) + 1;
            } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_canvas_data) {
                enforce(size >= 10, Exiv2::kerCorruptedMetadata);

                has_canvas_data = true;
                io_->readOrThrow(payload.pData_, payload.size_);
                byte size_buf[WEBP_TAG_SIZE];

                // Fetch width""
                memcpy(&size_buf, &payload.pData_[6], 2);
                size_buf[2] = 0;
                size_buf[3] = 0;
                pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) & 0x3fff;

                // Fetch height
                memcpy(&size_buf, &payload.pData_[8], 2);
                size_buf[2] = 0;
                size_buf[3] = 0;
                pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) & 0x3fff;
            } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_canvas_data) {
                enforce(size >= 5, Exiv2::kerCorruptedMetadata);

                has_canvas_data = true;
                byte size_buf_w[2];
                byte size_buf_h[3];

                io_->readOrThrow(payload.pData_, payload.size_);

                // Fetch width
                memcpy(&size_buf_w, &payload.pData_[1], 2);
                size_buf_w[1] &= 0x3F;
                pixelWidth_ = Exiv2::getUShort(size_buf_w, littleEndian) + 1;

                // Fetch height
                memcpy(&size_buf_h, &payload.pData_[2], 3);
                size_buf_h[0] = ((size_buf_h[0] >> 6) & 0x3) | ((size_buf_h[1]  & 0x3F) << 0x2);
                size_buf_h[1] = ((size_buf_h[1] >> 6) & 0x3) | ((size_buf_h[2] & 0xF) << 0x2);
                pixelHeight_ = Exiv2::getUShort(size_buf_h, littleEndian) + 1;
            } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_canvas_data) {
                enforce(size >= 12, Exiv2::kerCorruptedMetadata);

                has_canvas_data = true;
                byte size_buf[WEBP_TAG_SIZE];

                io_->readOrThrow(payload.pData_, payload.size_);

                // Fetch width
                memcpy(&size_buf, &payload.pData_[6], 3);
                size_buf[3] = 0;
                pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) + 1;

                // Fetch height
                memcpy(&size_buf, &payload.pData_[9], 3);
                size_buf[3] = 0;
                pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) + 1;
            } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP)) {
                io_->readOrThrow(payload.pData_, payload.size_);
                this->setIccProfile(payload);
            } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF)) {
                io_->readOrThrow(payload.pData_, payload.size_);

                // 4 meaningful bytes + 2 padding bytes
                byte  exifLongHeader[]   = { 0xFF, 0x01, 0xFF, 0xE1, 0x00, 0x00 };
                byte  exifShortHeader[]  = { 0x45, 0x78, 0x69, 0x66, 0x00, 0x00 };
                byte  exifTiffLEHeader[] = { 0x49, 0x49, 0x2A };       // "MM*"
                byte  exifTiffBEHeader[] = { 0x4D, 0x4D, 0x00, 0x2A }; // "II\0*"
                byte* rawExifData = nullptr;
                long  offset = 0;
                bool  s_header = false;
                bool  le_header = false;
                bool  be_header = false;
                long  pos = getHeaderOffset (payload.pData_, (long)payload.size_, (byte*)&exifLongHeader, 4);

                if (pos == -1) {
                    pos = getHeaderOffset (payload.pData_, (long)payload.size_, (byte*)&exifLongHeader, 6);
                    if (pos != -1) {
                        s_header = true;
                    }
                }
                if (pos == -1) {
                    pos = getHeaderOffset (payload.pData_, (long)payload.size_, (byte*)&exifTiffLEHeader, 3);
                    if (pos != -1) {
                        le_header = true;
                    }
                }
                if (pos == -1) {
                    pos = getHeaderOffset (payload.pData_, (long)payload.size_, (byte*)&exifTiffBEHeader, 4);
                    if (pos != -1) {
                        be_header = true;
                    }
                }

                if (s_header) {
                    offset += 6;
                }
                if (be_header || le_header) {
                    offset += 12;
                }

                const uint16_t sizePayload = (uint16_t)(payload.size_ + offset);
                rawExifData = (byte*)malloc(sizePayload);

                byte  sizeBuff[2];
                if (s_header) {
                    us2Data(sizeBuff, (sizePayload - 6), bigEndian);
                    memcpy(rawExifData, (char*)&exifLongHeader, 4);
                    memcpy(rawExifData + 4, (char*)&sizeBuff, 2);
                }

                if (be_header || le_header) {
                    us2Data(sizeBuff, (sizePayload - 6), bigEndian);
                    memcpy(rawExifData, (char*)&exifLongHeader, 4);
                    memcpy(rawExifData + 4, (char*)&sizeBuff, 2);
                    memcpy(rawExifData + 6, (char*)&exifShortHeader, 6);
                }

                memcpy(rawExifData + offset, payload.pData_, payload.size_);

#ifdef DEBUG
                std::cout << "Display Hex Dump [size:" << (unsigned long)sizePayload << "]" << std::endl;
                std::cout << Internal::binaryToHex(rawExifData, sizePayload);
#endif

                if (pos != -1) {
                    XmpData  xmpData;
                    ByteOrder bo = ExifParser::decode(exifData_,
                                                      payload.pData_ + pos,
                                                      static_cast<uint32_t>(payload.size_ - (size_t)pos));
                    setByteOrder(bo);
                }
                else
                {
#ifndef SUPPRESS_WARNINGS
                    EXV_WARNING << "Failed to decode Exif metadata." << std::endl;
#endif
                    exifData_.clear();
                }

                if (rawExifData)
                    free(rawExifData);
            } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP)) {
                io_->readOrThrow(payload.pData_, payload.size_);
                xmpPacket_.assign(reinterpret_cast<char*>(payload.pData_), payload.size_);
                if (xmpPacket_.size() > 0 && XmpParser::decode(xmpData_, xmpPacket_)) {
#ifndef SUPPRESS_WARNINGS
                    EXV_WARNING << "Failed to decode XMP metadata." << std::endl;
#endif
                } else {
#ifdef DEBUG
                    std::cout << "Display Hex Dump [size:" << (unsigned long)payload.size_ << "]" << std::endl;
                    std::cout << Internal::binaryToHex(payload.pData_, payload.size_);
#endif
                }
            } else {
                io_->seek(size, BasicIo::cur);
            }

            if ( io_->tell() % 2 ) io_->seek(+1, BasicIo::cur);
        }
    }

Project: exiv2
File: value.cpp

    int DateValue::read(const std::string& buf)
    {
        // Hard coded to read Iptc style dates
        if (buf.length() < 8) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << Error(kerUnsupportedDateFormat) << "\n";
#endif
            return 1;
        }
        int scanned = sscanf(buf.c_str(), "%4d-%d-%d",
                             &date_.year, &date_.month, &date_.day);
        if (scanned != 3) {
#ifndef SUPPRESS_WARNINGS
            EXV_WARNING << Error(kerUnsupportedDateFormat) << "\n";
#endif
            return 1;
        }
        return 0;
    }

Project: exiv2
File: actions.cpp

    bool Print::printMetadatum(const Exiv2::Metadatum& md, const Exiv2::Image* pImage)
    {
        if (!grepTag(md.key()))
            return false;
        if (!keyTag(md.key()))
            return false;

        if (Params::instance().unknown_ && md.tagName().substr(0, 2) == "0x") {
            return false;
        }

        bool const manyFiles = Params::instance().files_.size() > 1;
        if (manyFiles) {
            std::cout << std::setfill(' ') << std::left << std::setw(20) << path_ << "  ";
        }

        bool first = true;
        if (Params::instance().printItems_ & Params::prTag) {
            if (!first)
                std::cout << " ";
            first = false;
            std::cout << "0x" << std::setw(4) << std::setfill('0') << std::right << std::hex << md.tag();
        }
        if (Params::instance().printItems_ & Params::prSet) {
            if (!first)
                std::cout << " ";
            first = false;
            std::cout << "set";
        }
        if (Params::instance().printItems_ & Params::prGroup) {
            if (!first)
                std::cout << " ";
            first = false;
            std::cout << std::setw(12) << std::setfill(' ') << std::left << md.groupName();
        }
        if (Params::instance().printItems_ & Params::prKey) {
            if (!first)
                std::cout << " ";
            first = false;
            std::cout << std::setfill(' ') << std::left << std::setw(44) << md.key();
        }
        if (Params::instance().printItems_ & Params::prName) {
            if (!first)
                std::cout << " ";
            first = false;
            std::cout << std::setw(27) << std::setfill(' ') << std::left << md.tagName();
        }
        if (Params::instance().printItems_ & Params::prLabel) {
            if (!first)
                std::cout << " ";
            first = false;
            std::cout << std::setw(30) << std::setfill(' ') << std::left << md.tagLabel();
        }
        if (Params::instance().printItems_ & Params::prType) {
            if (!first)
                std::cout << " ";
            first = false;
            std::cout << std::setw(9) << std::setfill(' ') << std::left;
            const char* tn = md.typeName();
            if (tn) {
                std::cout << tn;
            } else {
                std::ostringstream os;
                os << "0x" << std::setw(4) << std::setfill('0') << std::hex << md.typeId();
                std::cout << os.str();
            }
        }
        if (Params::instance().printItems_ & Params::prCount) {
            if (!first)
                std::cout << " ";
            first = false;
            std::cout << std::dec << std::setw(3) << std::setfill(' ') << std::right << md.count();
        }
        if (Params::instance().printItems_ & Params::prSize) {
            if (!first)
                std::cout << " ";
            first = false;
            std::cout << std::dec << std::setw(3) << std::setfill(' ') << std::right << md.size();
        }
        if (Params::instance().printItems_ & Params::prValue && md.size() > 0) {
            if (!first)
                std::cout << "  ";
            first = false;
            if (md.size() > 128 && Params::instance().binary_ &&
                (md.typeId() == Exiv2::undefined || md.typeId() == Exiv2::unsignedByte ||
                 md.typeId() == Exiv2::signedByte)) {
                std::cout << _("(Binary value suppressed)") << std::endl;
                return true;
            }
            bool done = false;
            if (0 == strcmp(md.key().c_str(), "Exif.Photo.UserComment")) {
                const Exiv2::CommentValue* pcv = dynamic_cast<const Exiv2::CommentValue*>(&md.value());
                if (pcv) {
                    Exiv2::CommentValue::CharsetId csId = pcv->charsetId();
                    if (csId != Exiv2::CommentValue::undefined) {
                        std::cout << "charset=\"" << Exiv2::CommentValue::CharsetInfo::name(csId) << "\" ";
                    }
                    std::cout << pcv->comment(Params::instance().charset_.c_str());
                    done = true;
                }
            }
            if (!done) {
                // #1114 - show negative values for SByte
                if (md.typeId() != Exiv2::signedByte) {
                    std::cout << std::dec << md.value();
                } else {
                    long value = md.value().toLong();
                    std::cout << std::dec << (value < 128 ? value : value - 256);
                }
            }
        }
        if (Params::instance().printItems_ & Params::prTrans) {
            if (!first)
                std::cout << "  ";
            first = false;
            if (Params::instance().binary_ &&
                (md.typeId() == Exiv2::undefined || md.typeId() == Exiv2::unsignedByte ||
                 md.typeId() == Exiv2::signedByte) &&
                md.size() > 128) {
                std::cout << _("(Binary value suppressed)") << std::endl;
                return true;
            }
            bool done = false;
            if (0 == strcmp(md.key().c_str(), "Exif.Photo.UserComment")) {
                const Exiv2::CommentValue* pcv = dynamic_cast<const Exiv2::CommentValue*>(&md.value());
                if (pcv) {
                    std::cout << pcv->comment(Params::instance().charset_.c_str());
                    done = true;
                }
            }
            if (!done)
                std::cout << std::dec << md.print(&pImage->exifData());
        }
        if (Params::instance().printItems_ & Params::prHex) {
            if (!first)
                std::cout << std::endl;
            first = false;
            if (Params::instance().binary_ &&
                (md.typeId() == Exiv2::undefined || md.typeId() == Exiv2::unsignedByte ||
                 md.typeId() == Exiv2::signedByte) &&
                md.size() > 128) {
                std::cout << _("(Binary value suppressed)") << std::endl;
                return true;
            }
            Exiv2::DataBuf buf(md.size());
            md.copy(buf.pData_, pImage->byteOrder());
            Exiv2::hexdump(std::cout, buf.pData_, (long)buf.size_);
        }
        std::cout << std::endl;
        return true;
    }

Project: exiv2
File: image.cpp

    bool Image::isLittleEndianPlatform() { return !isBigEndianPlatform(); }

Project: exiv2
File: xmp.cpp

    XmpData::const_iterator XmpData::end() const
    {
        return xmpMetadata_.end();
    }

Project: exiv2
File: actions.cpp

    Insert* Insert::clone_() const
    {
        return new Insert(*this);
    }

Project: exiv2
File: basicio.cpp

        BlockMap() : type_(bNone), data_(nullptr), size_(0)
        {
        }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffCopier::visitSubIfd(TiffSubIfd* object)
    {
        copyObject(object);
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::encodeImageEntry(TiffImageEntry* object, const Exifdatum* datum)
    {
        encodeOffsetEntry(object, datum);

        uint32_t sizeDataArea = object->pValue()->sizeDataArea();

        if (sizeDataArea > 0 && writeMethod() == wmNonIntrusive) {
#ifdef DEBUG
            std::cerr << "\t DATAAREA IS SET (NON-INTRUSIVE WRITING)";
#endif
            setDirty();
        }

        if (sizeDataArea > 0 && writeMethod() == wmIntrusive) {
#ifdef DEBUG
            std::cerr << "\t DATAAREA IS SET (INTRUSIVE WRITING)";
#endif
            // Set pseudo strips (without a data pointer) from the size tag
            ExifKey key(object->szTag(), groupName(object->szGroup()));
            ExifData::const_iterator pos = exifData_.findKey(key);
            const byte* zero = 0;
            if (pos == exifData_.end()) {
#ifndef SUPPRESS_WARNINGS
                EXV_ERROR << "Size tag " << key
                          << " not found. Writing only one strip.\n";
#endif
                object->strips_.clear();
                object->strips_.push_back(std::make_pair(zero, sizeDataArea));
            }
            else {
                uint32_t sizeTotal = 0;
                object->strips_.clear();
                for (long i = 0; i < pos->count(); ++i) {
                    uint32_t len = pos->toLong(i);
                    object->strips_.push_back(std::make_pair(zero, len));
                    sizeTotal += len;
                }
                if (sizeTotal != sizeDataArea) {
#ifndef SUPPRESS_WARNINGS
                    ExifKey key2(object->tag(), groupName(object->group()));
                    EXV_ERROR << "Sum of all sizes of " << key
                              << " != data size of " << key2 << ". "
                              << "This results in an invalid image.\n";
#endif
                    // Todo: How to fix? Write only one strip?
                }
            }
        }

        if (sizeDataArea == 0 && writeMethod() == wmIntrusive) {
#ifdef DEBUG
            std::cerr << "\t USE STRIPS FROM SOURCE TREE IMAGE ENTRY";
#endif
            // Set strips from source tree
            if (pSourceTree_) {
                TiffFinder finder(object->tag(), object->group());
                pSourceTree_->accept(finder);
                TiffImageEntry* ti = dynamic_cast<TiffImageEntry*>(finder.result());
                if (ti) {
                    object->strips_ = ti->strips_;
                }
            }
#ifndef SUPPRESS_WARNINGS
            else {
                ExifKey key2(object->tag(), groupName(object->group()));
                EXV_WARNING << "No image data to encode " << key2 << ".\n";
            }
#endif
        }

    } // TiffEncoder::encodeImageEntry

Project: exiv2
File: makernote_int.cpp

    uint32_t PanasonicMnHeader::ifdOffset() const
    {
        return start_;
    }

Project: exiv2
File: preview.cpp

    LoaderExifJpeg::LoaderExifJpeg(PreviewId id, const Image &image, int parIdx)
        : Loader(id, image)
    {
        offset_ = 0;
        const ExifData &exifData = image_.exifData();
        ExifData::const_iterator pos = exifData.findKey(ExifKey(param_[parIdx].offsetKey_));
        if (pos != exifData.end() && pos->count() > 0) {
            offset_ = pos->toLong();
        }

        size_ = 0;
        pos = exifData.findKey(ExifKey(param_[parIdx].sizeKey_));
        if (pos != exifData.end() && pos->count() > 0) {
            size_ = pos->toLong();
        }

        if (offset_ == 0 || size_ == 0) return;

        if (param_[parIdx].baseOffsetKey_) {
            pos = exifData.findKey(ExifKey(param_[parIdx].baseOffsetKey_));
            if (pos != exifData.end() && pos->count() > 0) {
                offset_ += pos->toLong();
            }
        }

        if (Safe::add(offset_, size_) > static_cast<uint32_t>(image_.io().size()))
            return;

        valid_ = true;
    }

Project: exiv2
File: value.cpp

    LangAltValue::UniquePtr LangAltValue::clone() const
    {
        return UniquePtr(clone_());
    }

Project: exiv2
File: makernote_int.cpp

    bool OlympusMnHeader::read(const byte* pData,
                               uint32_t size,
                               ByteOrder /*byteOrder*/)
    {
        if (!pData || size < sizeOfSignature()) return false;
        header_.alloc(sizeOfSignature());
        std::memcpy(header_.pData_, pData, header_.size_);
        if (   static_cast<uint32_t>(header_.size_) < sizeOfSignature()
            || 0 != memcmp(header_.pData_, signature_, 6)) {
            return false;
        }
        return true;
    } // OlympusMnHeader::read

Project: exiv2
File: makernote_int.cpp

    bool SamsungMnHeader::read(const byte* /*pData*/,
                               uint32_t    /*size*/,
                               ByteOrder   /*byteOrder*/)
    {
        return true;
    } // SamsungMnHeader::read

Project: exiv2
File: tiffimage.cpp

    void OffsetWriter::writeOffsets(BasicIo& io) const
    {
        for (OffsetList::const_iterator it = offsetList_.begin(); it != offsetList_.end(); ++it) {
            io.seek(it->second.origin_, BasicIo::beg);
            byte buf[4] = { 0, 0, 0, 0 };
            l2Data(buf, it->second.target_, it->second.byteOrder_);
            io.write(buf, 4);
        }
    }

Project: exiv2
File: makernote_int.cpp

    constexpr uint32_t FujiMnHeader::sizeOfSignature()
    {
        return sizeof(signature_);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    size_t IoWrapper::write(const byte* pData, size_t wcount)
    {
        if (!wroteHeader_ && wcount > 0) {
            io_.write(pHeader_, size_);
            wroteHeader_ = true;
        }
        return io_.write(pData, wcount);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    void TiffSubIfd::doEncode(TiffEncoder& encoder, const Exifdatum* datum)
    {
        encoder.encodeSubIfd(this, datum);
    } // TiffSubIfd::doEncode

Project: exiv2
File: tiffvisitor_int.cpp

        FindExifdatum2(Exiv2::Internal::IfdId group, int idx)
            : groupName_(Exiv2::Internal::groupName(group)), idx_(idx) {}

Project: exiv2
File: preview.cpp

    uint32_t PreviewImage::width() const
    {
        return properties_.width_;
    }

Project: exiv2
File: image.cpp

    void Image::setIccProfile(Exiv2::DataBuf& iccProfile,bool bTestValid)
    {
        if ( bTestValid ) {
            if ( iccProfile.pData_ && ( iccProfile.size_ < (long) sizeof(long)) ) throw Error(kerInvalidIccProfile);
            const size_t size = iccProfile.pData_ ? getULong(iccProfile.pData_, bigEndian): -1;
            if ( size!= iccProfile.size_ ) throw Error(kerInvalidIccProfile);
        }
        iccProfile_ = iccProfile;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::encodeXmp()
    {
#ifdef EXV_HAVE_XMP_TOOLKIT
        ExifKey xmpKey("Exif.Image.XMLPacket");
        // Remove any existing XMP Exif tag
        ExifData::iterator pos = exifData_.findKey(xmpKey);
        if (pos != exifData_.end()) {
            xmpKey.setIdx(pos->idx());
            exifData_.erase(pos);
        }
        std::string xmpPacket;
        if ( xmpData_.usePacket() ) {
            xmpPacket = xmpData_.xmpPacket();
        } else {
            if (XmpParser::encode(xmpPacket, xmpData_) > 1) {
#ifndef SUPPRESS_WARNINGS
                EXV_ERROR << "Failed to encode XMP metadata.\n";
#endif
            }
        }
        if (!xmpPacket.empty()) {
            // Set the XMP Exif tag to the new value
            Value::UniquePtr value = Value::create(unsignedByte);
            value->read(reinterpret_cast<const byte*>(&xmpPacket[0]),
                        static_cast<long>(xmpPacket.size()),
                        invalidByteOrder);
            Exifdatum xmpDatum(xmpKey, value.get());
            exifData_.add(xmpDatum);
        }
#endif
    } // TiffEncoder::encodeXmp

Project: exiv2
File: xmp.cpp

    XmpData::const_iterator XmpData::findKey(const XmpKey& key) const
    {
        return std::find_if(xmpMetadata_.begin(), xmpMetadata_.end(),
                            FindXmpdatum(key));
    }

Project: exiv2
File: makernote_int.cpp

    constexpr uint32_t Casio2MnHeader::sizeOfSignature()
    {
        return sizeof(signature_);
    }

Project: exiv2
File: exif.cpp

    void ExifParser::encode(Blob &blob, ByteOrder byteOrder, const ExifData &exifData) {
        encode(blob, 0, 0, byteOrder, exifData);
    }

Project: exiv2
File: iptc.cpp

    Value::UniquePtr Iptcdatum::getValue() const
    {
        return value_.get() == 0 ? nullptr : value_->clone();
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffReader::visitDataEntry(TiffDataEntry* object)
    {
        readDataEntryBase(object);
    }

Project: exiv2
File: exif.cpp

    Exiv2::Exifdatum& setValue(Exiv2::Exifdatum& exifDatum, const T& value)
    {
        std::unique_ptr<Exiv2::ValueType<T> > v
            = std::unique_ptr<Exiv2::ValueType<T> >(new Exiv2::ValueType<T>);
        v->value_.push_back(value);
        exifDatum.value_ = std::move(v);
        return exifDatum;
    }

Project: exiv2
File: types.cpp

    bool stringTo<bool>(const std::string& s, bool& ok)
    {
        std::string lcs(s); /* lowercase string */
        for(unsigned i = 0; i < lcs.length(); i++) {
            lcs[i] = std::tolower(s[i]);
        }
        /* handle the same values as xmp sdk */
        if (lcs == "false" || lcs == "f" || lcs == "0") {
            ok = true;
            return false;
        }
        if (lcs == "true" || lcs == "t" || lcs == "1") {
            ok = true;
            return true;
        }
        ok = false;
        return false;
    }

Project: exiv2
File: makernote_int.cpp

    size_t PentaxDngMnHeader::write(IoWrapper& ioWrapper,
                                   ByteOrder /*byteOrder*/) const
    {
        ioWrapper.write(signature_, sizeOfSignature());
        return sizeOfSignature();
    } // PentaxDngMnHeader::write

Project: exiv2
File: pngchunk_int.cpp

        void PngChunk::decodeIHDRChunk(const DataBuf& data, PngImageHeader& h)
        {
            enforce(data.size_ == 13, kerCorruptedMetadata);

            h.width = getLong((const byte*)data.pData_, bigEndian);
            h.height = getLong((const byte*)data.pData_ + 4, bigEndian);
            h.bitDepth = data.pData_[8];
            h.colorType = data.pData_[9];
            h.compressionMethod = data.pData_[10];
            h.filterMethod = data.pData_[11];
            h.interlaceMethod = data.pData_[12];

            enforce(h.colorType == 0 || h.colorType == 2 || h.colorType == 3 || h.colorType == 4 || h.colorType == 6,
                    kerCorruptedMetadata);
            switch (h.colorType) {
                case 0:
                    enforce(
                        h.bitDepth == 1 || h.bitDepth == 2 || h.bitDepth == 4 || h.bitDepth == 8 || h.bitDepth == 16,
                        kerCorruptedMetadata);
                    break;
                case 2:
                    enforce(h.bitDepth == 8 || h.bitDepth == 16, kerCorruptedMetadata);
                    break;
                case 3:
                    enforce(h.bitDepth == 1 || h.bitDepth == 2 || h.bitDepth == 4 || h.bitDepth == 8,
                            kerCorruptedMetadata);
                    break;
                case 4:
                    enforce(h.bitDepth == 8 || h.bitDepth == 16, kerCorruptedMetadata);
                    break;
                case 6:
                    enforce(h.bitDepth == 8 || h.bitDepth == 16, kerCorruptedMetadata);
                    break;
            }
            enforce(h.compressionMethod == 0, kerCorruptedMetadata);
            enforce(h.filterMethod == 0, kerCorruptedMetadata);
            enforce(h.interlaceMethod == 0 || h.interlaceMethod == 1, kerCorruptedMetadata);
        }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent* TiffSubIfd::doAddPath(uint16_t tag,
                                         TiffPath& tiffPath,
                                         TiffComponent* const pRoot,
                                         TiffComponent::UniquePtr object)
    {
        assert(!tiffPath.empty());
        const TiffPathItem tpi1 = tiffPath.top();
        tiffPath.pop();
        if (tiffPath.empty()) {
            // If the last element in the path is the sub-IFD tag itself we're done.
            // But that shouldn't happen - see TiffDirectory::doAddPath
            return this;
        }
        const TiffPathItem tpi2 = tiffPath.top();
        tiffPath.push(tpi1);
        TiffComponent* tc = 0;
        for (Ifds::iterator i = ifds_.begin(); i != ifds_.end(); ++i) {
            if ((*i)->group() == tpi2.group()) {
                tc = *i;
                break;
            }
        }
        if (tc == 0) {
            if (tiffPath.size() == 1 && object.get() != 0) {
                tc = addChild(std::move(object));
            }
            else {
                TiffComponent::UniquePtr atc(new TiffDirectory(tpi1.tag(), tpi2.group()));
                tc = addChild(std::move(atc));
            }
            setCount(static_cast<uint32_t>(ifds_.size()));
        }
        return tc->addPath(tag, tiffPath, pRoot, std::move(object));
    } // TiffSubIfd::doAddPath

Project: exiv2
File: preview.cpp

    std::string PreviewImage::extension() const
    {
        return properties_.extension_;
    }

Project: exiv2
File: preview.cpp

    bool LoaderExifDataJpeg::readDimensions()
    {
        if (!valid()) return false;

        DataBuf buf = getData();
        if (buf.size_ == 0) return false;

        try {
            Image::UniquePtr image = ImageFactory::open(buf.pData_, buf.size_);
            if (image.get() == 0) return false;
            image->readMetadata();

            width_ = image->pixelWidth();
            height_ = image->pixelHeight();
        }
        catch (const AnyError& /* error */ ) {
            return false;
        }

        return true;
    }

Project: exiv2
File: convert.cpp

    bool getTextValue(std::string& value, const XmpData::iterator& pos)
    {
        if (pos->typeId() == langAlt) {
            // get the default language entry without x-default qualifier
            value = pos->toString(0);
            if (!pos->value().ok() && pos->count() == 1) {
                // If there is no default but exactly one entry, take that
                // without the qualifier
                value = pos->toString();
                if (   pos->value().ok()
                    && value.length() > 5 && value.substr(0, 5) == "lang=") {
                    const std::string::size_type first_space_pos = value.find_first_of(' ');
                    if (first_space_pos != std::string::npos) {
                        value = value.substr(first_space_pos + 1);
                    }
                    else {
                        value.clear();
                    }
                }
            }
        }
        else {
            value = pos->toString();
        }
        return pos->value().ok();
    }

Project: exiv2
File: value.cpp

    long TimeValue::size() const
    {
        return 11;
    }

Project: exiv2
File: jpgimage.cpp

    ExvImage::ExvImage(BasicIo::UniquePtr io, bool create)
        : JpegBase(ImageType::exv, std::move(io), create, blank_, sizeof(blank_))
    {
    }

Project: exiv2
File: convert.cpp

    void Converter::syncExifWithXmp()
    {
        Exiv2::XmpData::iterator td = xmpData_->findKey(XmpKey("Xmp.tiff.NativeDigest"));
        Exiv2::XmpData::iterator ed = xmpData_->findKey(XmpKey("Xmp.exif.NativeDigest"));
        if (td != xmpData_->end() && ed != xmpData_->end()) {
            if (td->value().toString() == computeExifDigest(true) &&
                ed->value().toString() == computeExifDigest(false)) {
                // We have both digests and the values match
                // XMP is up-to-date, we should update Exif
                setOverwrite(true);
                setErase(false);

                cnvFromXmp();
                writeExifDigest();
                return;
            }
            else {
                // We have both digests and the values do not match
                // Exif was modified after XMP, we should update XMP
                setOverwrite(true);
                setErase(false);

                cnvToXmp();
                writeExifDigest();
                return;
            }
        }
        else {
            // We don't have both digests, it is probably the first conversion to XMP
            setOverwrite(false); // to be safe
            setErase(false);

            cnvToXmp();
            writeExifDigest();
            return;
        }
    }

Project: exiv2
File: makernote_int.cpp

    PanasonicMnHeader::PanasonicMnHeader(): start_(0)
    {
        read(signature_, sizeOfSignature(), invalidByteOrder);
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffBinaryElement::doCount() const
    {
        return elDef_.count_;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    TiffReader::~TiffReader()
    {
    }

Project: exiv2
File: pngimage.cpp

    void readChunk(DataBuf& buffer, BasicIo& io)
    {
#ifdef DEBUG
        std::cout << "Exiv2::PngImage::readMetadata: Position: " << io.tell() << std::endl;
#endif
        size_t bufRead = io.read(buffer.pData_, buffer.size_);
        if (io.error()) {
            throw Error(kerFailedToReadImageData);
        }
        if (bufRead != buffer.size_) {
            throw Error(kerInputDataReadFailed);
        }
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffVisitor::visitDirectoryEnd(TiffDirectory* /*object*/)
    {
    }

Project: exiv2
File: tiffcomposite_int.cpp

    void TiffEntryBase::encode(TiffEncoder& encoder, const Exifdatum* datum)
    {
        doEncode(encoder, datum);
    } // TiffComponent::encode

Project: exiv2
File: makernote_int.cpp

    TiffComponent* newSigmaMn2(uint16_t tag,
                               IfdId    group,
                               IfdId    mnGroup)
    {
        return new TiffIfdMakernote(tag, group, mnGroup, new SigmaMnHeader);
    }

Project: exiv2
File: makernote_int.cpp

    size_t Nikon2MnHeader::size() const
    {
        return sizeOfSignature();
    }

Project: exiv2
File: iptc.cpp

    IptcData::const_iterator IptcData::findId(uint16_t dataset, uint16_t record) const
    {
        return std::find_if(iptcMetadata_.begin(), iptcMetadata_.end(),
                            FindIptcdatum(dataset, record));
    }

Project: exiv2
File: tiffimage.cpp

    void TiffImage::readMetadata()
    {
#ifdef DEBUG
        std::cerr << "Reading TIFF file " << io_->path() << "\n";
#endif
        if (io_->open() != 0) {
            throw Error(kerDataSourceOpenFailed, io_->path(), strError());
        }

        IoCloser closer(*io_);
        // Ensure that this is the correct image type
        if (!isTiffType(*io_, false)) {
            if (io_->error() || io_->eof())
                throw Error(kerFailedToReadImageData);
            throw Error(kerNotAnImage, "TIFF");
        }
        clearMetadata();

        ByteOrder bo = TiffParser::decode(exifData_,
                                          iptcData_,
                                          xmpData_,
                                          io_->mmap(),
                                          (uint32_t) io_->size());
        setByteOrder(bo);

        // read profile from the metadata
        Exiv2::ExifKey            key("Exif.Image.InterColorProfile");
        Exiv2::ExifData::iterator pos   = exifData_.findKey(key);
        if ( pos != exifData_.end() ) {
            const size_t size = pos->count() * pos->typeSize();
            if (size == 0) {
                throw Error(kerFailedToReadImageData);
            }
            iccProfile_.alloc(size);
            pos->copy(iccProfile_.pData_,bo);
        }

    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffReader::visitImageEntry(TiffImageEntry* object)
    {
        readDataEntryBase(object);
    }

Project: exiv2
File: value.cpp

    const char* CommentValue::detectCharset(std::string& c) const
    {
        // Interpret a BOM if there is one
        if (0 == strncmp(c.data(), "\xef\xbb\xbf", 3)) {
            c = c.substr(3);
            return "UTF-8";
        }
        if (0 == strncmp(c.data(), "\xff\xfe", 2)) {
            c = c.substr(2);
            return "UCS-2LE";
        }
        if (0 == strncmp(c.data(), "\xfe\xff", 2)) {
            c = c.substr(2);
            return "UCS-2BE";
        }

        // Todo: Add logic to guess if the comment is encoded in UTF-8

        return byteOrder_ == littleEndian ? "UCS-2LE" : "UCS-2BE";
    }

Project: exiv2
File: iotest.cpp

int main(int argc, char* const argv[])
{
try {
    if (argc != 4) {
        std::cout << "Usage: " << argv[0] << " filein fileout1 fileout2\n";
        std::cout << "fileouts are overwritten and should match filein exactly\n";
        return 1;
    }

    FileIo fileIn(argv[1]);
    if (fileIn.open() != 0) {
        throw Error(Exiv2::kerDataSourceOpenFailed, fileIn.path(), strError());
    }

    FileIo fileOut1(argv[2]);
    if (fileOut1.open("w+b") != 0) {
        throw Error(Exiv2::kerFileOpenFailed, argv[2], "w+b", strError());
    }

    MemIo memIo1;

    // Copy to output file through memIo
    memIo1.write(fileIn);
    memIo1.seek(0, BasicIo::beg);
    fileOut1.write(memIo1);

    // Make sure they are all the same size
    if(fileIn.size() != memIo1.size() || memIo1.size() != fileOut1.size()) {
        std::cerr << argv[0] <<
            ": Sizes do not match\n";
        return 1;
    }

    // Read writereadseek test on MemIo
    MemIo memIo2;
    int rc = WriteReadSeek(memIo2);
    if (rc != 0) return rc;

    // Read writereadseek test on FileIo
    // Create or overwrite the file, then close it
    FileIo fileTest("iotest.txt");
    if (fileTest.open("w+b") != 0) {
        throw Error(Exiv2::kerFileOpenFailed, "iotest.txt", "w+b", strError());
    }

    fileTest.close();
    rc = WriteReadSeek(fileTest);
    if (rc != 0) return rc;

    // Another test of reading and writing
    fileOut1.seek(0, BasicIo::beg);
    memIo2.seek(0, BasicIo::beg);
    FileIo fileOut2(argv[3]);
    if (fileOut2.open("w+b") != 0) {
        throw Error(Exiv2::kerFileOpenFailed, argv[3], "w+b", strError());
    }

    size_t readCount = 0;
    byte buf[32];
    while ((readCount=fileOut1.read(buf, sizeof(buf)))) {
        if (memIo2.write(buf, readCount) != readCount) {
            std::cerr << argv[0] <<
                ": MemIo bad write 2\n";
            return 13;
        }
        if (fileOut2.write(buf, readCount) != readCount) {
            std::cerr << argv[0] <<
                ": FileIo bad write 2\n";
            return 14;
        }
    }

    return 0;
}
catch (Exiv2::AnyError& e) {
    std::cerr << "Caught Exiv2 exception '" << e << "'\n";
    return 20;
}
}

Project: exiv2
File: tiffcomposite_int.cpp

    TiffComponent::UniquePtr newTiffEntry(uint16_t tag, IfdId group)
    {
        return TiffComponent::UniquePtr(new TiffEntry(tag, group));
    }

Project: exiv2
File: image.cpp

    void Image::writeXmpFromPacket(bool) {}

Project: exiv2
File: tiffimage.cpp

    void TiffHeaderBase::print(std::ostream& os, const std::string& prefix) const
    {
        std::ios::fmtflags f( os.flags() );
        os << prefix
           << _("TIFF header, offset") << " = 0x"
           << std::setw(8) << std::setfill('0') << std::hex << std::right
           << offset_;

        switch (byteOrder_) {
        case littleEndian:     os << ", " << _("little endian encoded"); break;
        case bigEndian:        os << ", " << _("big endian encoded");    break;
        case invalidByteOrder: break;
        }
        os << "\n";
        os.flags(f);
    } // TiffHeaderBase::print

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffComponent::sizeData() const
    {
        return doSizeData();
    } // TiffComponent::sizeData

Project: exiv2
File: makernote_int.cpp

    TiffComponent* newCasioMn(uint16_t    tag,
                             IfdId       group,
                             IfdId    /* mnGroup*/,
                             const byte* pData,
                             uint32_t    size,
                             ByteOrder/* byteOrder */ )
    {
        if (size > 6 && std::string(reinterpret_cast<const char*>(pData), 6)
                        == std::string("QVC\0\0\0", 6)) {
            return newCasio2Mn2(tag, group, casio2Id);
        };
        // Require at least an IFD with 1 entry, but not necessarily a next pointer
        if (size < 14) return 0;
        return newIfdMn2(tag, group, casioId);
    }

Project: exiv2
File: makernote_int.cpp

    size_t OlympusMnHeader::size() const
    {
        return header_.size_;
    }

Project: exiv2
File: convert.cpp

    bool ucs2beToUcs2le(std::string& str)
    {
        return swapBytes(str);
    }

Project: exiv2
File: preview.cpp

    LoaderTiff::LoaderTiff(PreviewId id, const Image &image, int parIdx)
        : Loader(id, image),
          group_(param_[parIdx].group_)
    {
        const ExifData &exifData = image_.exifData();

        int offsetCount = 0;
        ExifData::const_iterator pos;

        // check if the group_ contains a preview image
        if (param_[parIdx].checkTag_) {
            pos = exifData.findKey(ExifKey(param_[parIdx].checkTag_));
            if (pos == exifData.end()) return;
            if (param_[parIdx].checkValue_ && pos->toString() != param_[parIdx].checkValue_) return;
        }

        pos = exifData.findKey(ExifKey(std::string("Exif.") + group_ + ".StripOffsets"));
        if (pos != exifData.end()) {
            offsetTag_ = "StripOffsets";
            sizeTag_ = "StripByteCounts";
            offsetCount = pos->value().count();
        }
        else {
            pos = exifData.findKey(ExifKey(std::string("Exif.") + group_ + ".TileOffsets"));
            if (pos == exifData.end()) return;
            offsetTag_ = "TileOffsets";
            sizeTag_ = "TileByteCounts";
            offsetCount = pos->value().count();
        }

        pos = exifData.findKey(ExifKey(std::string("Exif.") + group_ + '.' + sizeTag_));
        if (pos == exifData.end()) return;
        if (offsetCount != pos->value().count()) return;
        for (int i = 0; i < offsetCount; i++) {
            size_ += pos->toLong(i);
        }

        if (size_ == 0) return;

        pos = exifData.findKey(ExifKey(std::string("Exif.") + group_ + ".ImageWidth"));
        if (pos != exifData.end() && pos->count() > 0) {
            width_ = pos->toLong();
        }

        pos = exifData.findKey(ExifKey(std::string("Exif.") + group_ + ".ImageLength"));
        if (pos != exifData.end() && pos->count() > 0) {
            height_ = pos->toLong();
        }

        if (width_ == 0 || height_ == 0) return;

        valid_ = true;
    }

Project: exiv2
File: convert.cpp

    bool convertStringCharset(std::string &str, const char* from, const char* to)
    {
        if (0 == strcmp(from, to)) return true; // nothing to do
        bool ret = false;
#if defined EXV_HAVE_ICONV
        ret = convertStringCharsetIconv(str, from, to);
#elif defined WIN32 && !defined __CYGWIN__
        ret = convertStringCharsetWindows(str, from, to);
#else
# ifndef SUPPRESS_WARNINGS
        EXV_WARNING << "Charset conversion required but no character mapping functionality available.\n";
# endif
        UNUSED(str);
#endif
        return ret;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    void TiffSizeEntry::doAccept(TiffVisitor& visitor)
    {
        visitor.visitSizeEntry(this);
    } // TiffSizeEntry::doAccept

Project: exiv2
File: makernote_int.cpp

    size_t SigmaMnHeader::size() const
    {
        return sizeOfSignature();
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffBinaryArray::~TiffBinaryArray()
    {
        for (Components::iterator i = elements_.begin(); i != elements_.end(); ++i) {
            delete *i;
        }
    }

Project: exiv2
File: types.cpp

        bool operator==(Exiv2::TypeId typeId) const
        {
            return typeId_ == typeId;
        }

Project: exiv2
File: xmpsidecar.cpp

    static bool matchi(const std::string key,const char* substr)
    {
        return toLowerCase(key).find(substr) != std::string::npos;
    }

Project: exiv2
File: preview.cpp

    PreviewImage::~PreviewImage()
    {
        delete[] pData_;
    }

Project: exiv2
File: makernote_int.cpp

    bool PentaxDngMnHeader::read(const byte* pData,
                              uint32_t size,
                              ByteOrder /*byteOrder*/)
    {
        if (!pData || size < sizeOfSignature()) return false;
        header_.alloc(sizeOfSignature());
        std::memcpy(header_.pData_, pData, header_.size_);
        if (   static_cast<uint32_t>(header_.size_) < sizeOfSignature()
            || 0 != memcmp(header_.pData_, signature_, 7)) {
            return false;
        }
        return true;
    } // PentaxDngMnHeader::read

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffBinaryElement::doWrite(IoWrapper& ioWrapper,
                                        ByteOrder byteOrder,
                                        int32_t   /*offset*/,
                                        uint32_t  /*valueIdx*/,
                                        uint32_t  /*dataIdx*/,
                                        uint32_t& /*imageIdx*/)
    {
        Value const* pv = pValue();
        if (!pv || pv->count() == 0) return 0;
        DataBuf buf(pv->size());
        pv->copy(buf.pData_, byteOrder);
        ioWrapper.write(buf.pData_, buf.size_);
        return (uint32_t)buf.size_;
    } // TiffBinaryElement::doWrite

Project: exiv2
File: jp2image.cpp

    static std::string toAscii(long n)
    {
        const char* p = (const char*) &n;
        std::string result;
        bool bBigEndian = isBigEndian();
        for ( int i = 0 ; i < 4 ; i++) {
            result += p[ bBigEndian ? i : (3-i) ];
        }
        return result;
    }

Project: exiv2
File: types.cpp

    Rational parseRational(const std::string& s, bool& ok)
    {
        Rational ret = stringTo<Rational>(s, ok);
        if (ok) return ret;

        long l = stringTo<long>(s, ok);
        if (ok) return Rational(l, 1);

        float f = stringTo<float>(s, ok);
        if (ok) return floatToRationalCast(f);

        bool b = stringTo<bool>(s, ok);
        if (ok) return b ? Rational(1, 1) : Rational(0, 1);

        // everything failed, return from stringTo<Rational> is probably the best fit
        return ret;
    }

Project: exiv2
File: types.cpp

    long l2Data(byte* buf, int32_t l, ByteOrder byteOrder)
    {
        if (byteOrder == littleEndian) {
            buf[0] =  (byte)(l & 0x000000ff);
            buf[1] = (byte)((l & 0x0000ff00) >> 8);
            buf[2] = (byte)((l & 0x00ff0000) >> 16);
            buf[3] = (byte)((l & 0xff000000) >> 24);
        }
        else {
            buf[0] = (byte)((l & 0xff000000) >> 24);
            buf[1] = (byte)((l & 0x00ff0000) >> 16);
            buf[2] = (byte)((l & 0x0000ff00) >> 8);
            buf[3] =  (byte)(l & 0x000000ff);
        }
        return 4;
    }

Project: exiv2
File: preview.cpp

    DataBuf LoaderExifJpeg::getData() const
    {
        if (!valid()) return DataBuf();
        BasicIo &io = image_.io();

        if (io.open() != 0) {
            throw Error(kerDataSourceOpenFailed, io.path(), strError());
        }
        IoCloser closer(io);

        const Exiv2::byte* base = io.mmap();

        return DataBuf(base + offset_, size_);
    }

Project: exiv2
File: tiffimage.cpp

    void TiffHeaderBase::setByteOrder(ByteOrder byteOrder)
    {
        byteOrder_ = byteOrder;
    }

Project: exiv2
File: pgfimage.cpp

    byte PgfImage::readPgfMagicNumber(BasicIo& iIo)
    {
        byte b = iIo.getb();
        if (iIo.error()) throw Error(kerFailedToReadImageData);

        if (b < 0x36)   // 0x36 = '6'.
        {
            // Not right Magick version.
#ifdef DEBUG
            std::cout << "Exiv2::PgfImage::readMetadata: wrong Magick number\n";
#endif
        }

        return b;
    } // PgfImage::readPgfMagicNumber

Project: exiv2
File: iptc.cpp

    const char* Iptcdatum::familyName() const
    {
        return key_.get() == 0 ? "" : key_->familyName();
    }

Project: exiv2
File: basicio.cpp

    DataBuf MemIo::read(long rcount)
    {
        DataBuf buf(rcount);
        size_t readCount = read(buf.pData_, buf.size_);
        buf.size_ = readCount;
        return buf;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffDecoder::decodeIptc(const TiffEntryBase* object)
    {
        // add Exif tag anyway
        decodeStdTiffEntry(object);

        // All tags are read at this point, so the first time we come here,
        // find the relevant IPTC tag and decode IPTC if found
        if (decodedIptc_) {
            return;
        }
        decodedIptc_ = true;
        // 1st choice: IPTCNAA
        byte const* pData = 0;
        long size = 0;
        getObjData(pData, size, 0x83bb, ifd0Id, object);
        if (pData) {
            if (0 == IptcParser::decode(iptcData_, pData, size)) {
                return;
            }
#ifndef SUPPRESS_WARNINGS
            else {
                EXV_WARNING << "Failed to decode IPTC block found in "
                            << "Directory Image, entry 0x83bb\n";
            }
#endif
        }

        // 2nd choice if no IPTCNAA record found or failed to decode it:
        // ImageResources
        pData = 0;
        size = 0;
        getObjData(pData, size, 0x8649, ifd0Id, object);
        if (pData) {
            byte const* record = 0;
            uint32_t sizeHdr = 0;
            uint32_t sizeData = 0;
            if (0 != Photoshop::locateIptcIrb(pData, size,
                                              &record, &sizeHdr, &sizeData)) {
                return;
            }
            if (0 == IptcParser::decode(iptcData_, record + sizeHdr, sizeData)) {
                return;
            }
#ifndef SUPPRESS_WARNINGS
            else {
                EXV_WARNING << "Failed to decode IPTC block found in "
                            << "Directory Image, entry 0x8649\n";
            }
#endif
        }
    } // TiffMetadataDecoder::decodeIptc

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffFinder::visitBinaryArray(TiffBinaryArray* object)
    {
        findObject(object);
    }

Project: exiv2
File: tiffimage.cpp

    Image::UniquePtr newTiffInstance(BasicIo::UniquePtr io, bool create)
    {
        Image::UniquePtr image(new TiffImage(std::move(io), create));
        if (!image->good()) {
            image.reset();
        }
        return image;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffImageEntry::doSize() const
    {
        return static_cast<uint32_t>(strips_.size()) * 4;
    } // TiffImageEntry::doSize

Project: exiv2
File: iptc.cpp

    std::string Iptcdatum::toString(long n) const
    {
        return value_.get() == 0 ? "" : value_->toString(n);
    }

Project: exiv2
File: makernote_int.cpp

    FujiMnHeader::FujiMnHeader() : start_(0)
    {
        read(signature_, sizeOfSignature(), byteOrder_);
    }

Project: exiv2
File: types.cpp

    URational getURational(const byte* buf, ByteOrder byteOrder)
    {
        uint32_t nominator = getULong(buf, byteOrder);
        uint32_t denominator = getULong(buf + 4, byteOrder);
        return std::make_pair(nominator, denominator);
    }

Project: exiv2
File: exif.cpp

    Thumbnail::UniquePtr Thumbnail::create(const Exiv2::ExifData& exifData)
    {
        Thumbnail::UniquePtr thumbnail;
        const Exiv2::ExifKey k1("Exif.Thumbnail.Compression");
        Exiv2::ExifData::const_iterator pos = exifData.findKey(k1);
        if (pos != exifData.end()) {
            if (pos->count() == 0) return thumbnail;
            long compression = pos->toLong();
            if (compression == 6) {
                thumbnail = Thumbnail::UniquePtr(new JpegThumbnail);
            }
            else {
                thumbnail = Thumbnail::UniquePtr(new TiffThumbnail);
            }
        }
        else {
            const Exiv2::ExifKey k2("Exif.Thumbnail.JPEGInterchangeFormat");
            pos = exifData.findKey(k2);
            if (pos != exifData.end()) {
                thumbnail = Thumbnail::UniquePtr(new JpegThumbnail);
            }
        }
        return thumbnail;
    }

Project: exiv2
File: makernote_int.cpp

    size_t SonyMnHeader::write(IoWrapper& ioWrapper,
                                 ByteOrder /*byteOrder*/) const
    {
        ioWrapper.write(signature_, sizeOfSignature());
        return sizeOfSignature();
    } // SonyMnHeader::write

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffComponent::size() const
    {
        return doSize();
    } // TiffComponent::size

Project: exiv2
File: preview.cpp

    PreviewImage PreviewManager::getPreviewImage(const PreviewProperties &properties) const
    {
        Loader::UniquePtr loader = Loader::create(properties.id_, image_);
        DataBuf buf;
        if (loader.get()) {
            buf = loader->getData();
        }

        return PreviewImage(properties, buf);
    }

Project: exiv2
File: rafimage.cpp

    void RafImage::writeMetadata()
    {
        //! Todo: implement me!
        throw(Error(kerWritingImageFormatUnsupported, "RAF"));
    } // RafImage::writeMetadata

Project: exiv2
File: makernote_int.cpp

    size_t PanasonicMnHeader::write(IoWrapper& ioWrapper,
                                      ByteOrder /*byteOrder*/) const
    {
        ioWrapper.write(signature_, sizeOfSignature());
        return sizeOfSignature();
    } // PanasonicMnHeader::write

Project: exiv2
File: basicio.cpp

    size_t FileIo::read(byte* buf, size_t rcount)
    {
        assert(p_->fp_ != 0);
        if (p_->switchMode(Impl::opRead) != 0) {
            return 0;
        }
        return (long)std::fread(buf, 1, rcount, p_->fp_);
    }

Project: exiv2
File: actions.cpp

    int Erase::eraseXmpData(Exiv2::Image* image) const
    {
        if (Params::instance().verbose_ && image->xmpData().count() > 0) {
            std::cout << _("Erasing XMP data from the file") << std::endl;
        }
        image->clearXmpData();  // Quick fix for bug #612
        image->clearXmpPacket();
        return 0;
    }

Project: exiv2
File: exif.cpp

    ExifThumb::ExifThumb(ExifData& exifData)
        : ExifThumbC(exifData), exifData_(exifData)
    {
    }

Project: exiv2
File: types.cpp

    long f2Data(byte* buf, float f, ByteOrder byteOrder)
    {
        // This algorithm assumes that the internal representation of the float
        // type is the 4-byte IEEE 754 binary32 format, which is common but not
        // required by the C++ standard.
        static_assert(sizeof(float) == 4, "float type requires 4-byte IEEE 754 binary32 format");
        union {
            uint32_t ul_;
            float    f_;
        } u;
        u.f_ = f;
        return ul2Data(buf, u.ul_, byteOrder);
    }

Project: exiv2
File: exif.cpp

    Exifdatum& Exifdatum::operator=(const int32_t& value)
    {
        return Exiv2::setValue(*this, value);
    }

Project: exiv2
File: image.cpp

    void Image::clearIptcData()
    {
        iptcData_.clear();
    }

Project: exiv2
File: value.cpp

    std::string LangAltValue::toString(const std::string& qualifier) const
    {
        ValueType::const_iterator i = value_.find(qualifier);
        if (i != value_.end()) {
            ok_ = true;
            return i->second;
        }
        ok_ = false;
        return "";
    }

Project: exiv2
File: tiffcomposite_int.cpp

    TiffEntry* TiffEntry::doClone() const
    {
        return new TiffEntry(*this);
    }

Project: exiv2
File: makernote_int.cpp

    constexpr uint32_t Nikon2MnHeader::sizeOfSignature()
    {
        return sizeof(signature_);
    }

Project: exiv2
File: value.cpp

    const TimeValue::Time& TimeValue::getTime() const
    {
        return time_;
    }

Project: exiv2
File: tiffcomposite_int.cpp

    uint32_t TiffBinaryArray::doSize() const
    {
        if (cfg() == 0 || !decoded()) return TiffEntryBase::doSize();

        if (elements_.empty()) return 0;

        // Remaining assumptions:
        // - array elements don't "overlap"
        // - no duplicate tags in the array
        uint32_t idx = 0;
        uint32_t sz = cfg()->tagStep();
        for (Components::const_iterator i = elements_.begin(); i != elements_.end(); ++i) {
            if ((*i)->tag() > idx) {
                idx = (*i)->tag();
                sz = (*i)->size();
            }
        }
        idx = idx * cfg()->tagStep() + sz;

        if (cfg()->hasFillers_ && def()) {
            const ArrayDef* lastDef = def() + defSize() - 1;
            uint16_t lastTag = static_cast<uint16_t>(lastDef->idx_ / cfg()->tagStep());
            idx = EXV_MAX(idx, lastDef->idx_ + lastDef->size(lastTag, cfg()->group_));
        }
        return idx;

    } // TiffBinaryArray::doSize

Project: exiv2
File: actions.cpp

    int Erase::eraseIccProfile(Exiv2::Image* image) const
    {
        if (Params::instance().verbose_ && image->iccProfileDefined()) {
            std::cout << _("Erasing ICC Profile data from the file") << std::endl;
        }
        image->clearIccProfile();
        return 0;
    }

Project: exiv2
File: value.cpp

    long CommentValue::copy(byte* buf, ByteOrder byteOrder) const
    {
        std::string c = value_;
        if (charsetId() == unicode) {
            c = value_.substr(8);
            const size_t sz = c.size();
            UNUSED(sz);
            if (byteOrder_ == littleEndian && byteOrder == bigEndian) {
                convertStringCharset(c, "UCS-2LE", "UCS-2BE");
                assert(c.size() == sz);
            }
            else if (byteOrder_ == bigEndian && byteOrder == littleEndian) {
                convertStringCharset(c, "UCS-2BE", "UCS-2LE");
                assert(c.size() == sz);
            }
            c = value_.substr(0, 8) + c;
        }
        if (c.size() == 0)
            return 0;
        assert(buf != 0);
        return static_cast<long>(c.copy(reinterpret_cast<char*>(buf), c.size()));
    }

Project: exiv2
File: image.cpp

    uint16_t Image::byteSwap(uint16_t value,bool bSwap) const
    {
        uint16_t result = 0;
        result |= (value & 0x00FF) << 8;
        result |= (value & 0xFF00) >> 8;
        return bSwap ? result : value;
    }

Project: exiv2
File: xmp.cpp

    void XmpData::eraseFamily(XmpData::iterator& pos)
    {
        // https://github.com/Exiv2/exiv2/issues/521
        // delete 'children' of XMP composites (XmpSeq and XmpBag)

        // I build a StringVector of keys to remove
        // Then I remove them with erase(....)
        // erase() has nasty side effects on its argument
        // The side effects are avoided by the two-step approach
        // https://github.com/Exiv2/exiv2/issues/560
        std::string         key(pos->key());
        Exiv2::StringVector keys;
        while ( pos != xmpMetadata_.end() ) {
            if ( pos->key().find(key)==0 ) {
                keys.push_back(pos->key());
                pos++;
            } else {
                break;
            }
        }
        // now erase the family!
        for ( Exiv2::StringVector_i it = keys.begin() ; it != keys.end() ; it++ ) {
            erase(findKey(Exiv2::XmpKey(*it)));
        }
    }

Project: exiv2
File: actions.cpp

    int FixCom::run(const std::string& path)
    {
        try {
            if (!Exiv2::fileExists(path, true)) {
                std::cerr << path << ": " << _("Failed to open the file\n");
                return -1;
            }
            Timestamp ts;
            if (Params::instance().preserve_)
                ts.read(path);

            Exiv2::Image::UniquePtr image = Exiv2::ImageFactory::open(path);
            image->readMetadata();
            Exiv2::ExifData& exifData = image->exifData();
            if (exifData.empty()) {
                std::cerr << path << ": " << _("No Exif data found in the file\n");
                return -3;
            }
            auto pos = exifData.findKey(Exiv2::ExifKey("Exif.Photo.UserComment"));
            if (pos == exifData.end()) {
                if (Params::instance().verbose_) {
                    std::cout << _("No Exif user comment found") << "\n";
                }
                return 0;
            }
            Exiv2::Value::UniquePtr v = pos->getValue();
            const Exiv2::CommentValue* pcv = dynamic_cast<const Exiv2::CommentValue*>(v.get());
            if (!pcv) {
                if (Params::instance().verbose_) {
                    std::cout << _("Found Exif user comment with unexpected value type") << "\n";
                }
                return 0;
            }
            Exiv2::CommentValue::CharsetId csId = pcv->charsetId();
            if (csId != Exiv2::CommentValue::unicode) {
                if (Params::instance().verbose_) {
                    std::cout << _("No Exif UNICODE user comment found") << "\n";
                }
                return 0;
            }
            std::string comment = pcv->comment(Params::instance().charset_.c_str());
            if (Params::instance().verbose_) {
                std::cout << _("Setting Exif UNICODE user comment to") << " \"" << comment << "\"\n";
            }
            comment = std::string("charset=\"") + Exiv2::CommentValue::CharsetInfo::name(csId) + "\" " + comment;
            // Remove BOM and convert value from source charset to UCS-2, but keep byte order
            pos->setValue(comment);
            image->writeMetadata();
            if (Params::instance().preserve_)
                ts.touch(path);

            return 0;
        } catch (const Exiv2::AnyError& e) {
            std::cerr << "Exiv2 exception in fixcom action for file " << path << ":\n" << e << "\n";
            return 1;
        }
    }

Project: exiv2
File: pngimage.cpp

    inline bool compare(const char* str, const Exiv2::DataBuf& buf, size_t length)
    {
        // str & length should compile time constants => only running this in DEBUG mode is ok
        assert(strlen(str) <= length);
        return memcmp(str, buf.pData_, std::min(length, buf.size_)) == 0;
    }

Project: exiv2
File: value.cpp

    TimeValue::~TimeValue()
    {
    }

Project: exiv2
File: preview.cpp

    PreviewImage& PreviewImage::operator=(const PreviewImage& rhs)
    {
        if (this == &rhs) return *this;
        if (rhs.size_ > size_) {
            delete[] pData_;
            pData_ = new byte[rhs.size_];
        }
        properties_ = rhs.properties_;
        memcpy(pData_, rhs.pData_, rhs.size_);
        size_ = rhs.size_;
        return *this;
    }

Project: exiv2
File: image.cpp

    void Image::setByteOrder(ByteOrder byteOrder)
    {
        byteOrder_ = byteOrder;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffEncoder::encodeBinaryArray(TiffBinaryArray* object, const Exifdatum* datum)
    {
        encodeOffsetEntry(object, datum);
    } // TiffEncoder::encodeBinaryArray

Project: exiv2
File: value.cpp

    std::ostream& TimeValue::write(std::ostream& os) const
    {
        char plusMinus = '+';
        if (time_.tzHour < 0 || time_.tzMinute < 0) plusMinus = '-';

        std::ios::fmtflags f( os.flags() );
        os << std::right
           << std::setw(2) << std::setfill('0') << time_.hour << ':'
           << std::setw(2) << std::setfill('0') << time_.minute << ':'
           << std::setw(2) << std::setfill('0') << time_.second << plusMinus
           << std::setw(2) << std::setfill('0') << abs(time_.tzHour) << ':'
           << std::setw(2) << std::setfill('0') << abs(time_.tzMinute);
        os.flags(f);

        return os;
    }

Project: exiv2
File: tiffvisitor_int.cpp

    void TiffVisitor::setGo(GoEvent event, bool go)
    {
        assert(event >= 0 && static_cast<int>(event) < events_);
        go_[event] = go;
    }