Failure in TIFFSetSubDirectory() will break subsequent TIFFSetDirectory() calls

If int TIFFSetSubDirectory(TIFF *tif, uint64_t diroff) fails due to TIFFReadDirectory() error, subsequent calls to TIFFSetDirectory() can not recover a consistent state.

This is reproducible in master, 4.6, 4.5.1. My guess is that this issue surfaced around the time when relative seeking support / IFD hash map optimiazions were introduced.

This can be reproduced by opening an invalid SubIFD directory (e.g. w/o required ImageLength tag).

` int main() { TIFF* tif = TIFFOpen("example_with_invalid_subifd.tiff", "r"); if (!tif) { std::cerr << "Failed to open TIFF file.\n"; return 1; }

// Read SubIFD tag
uint64* subifds;
uint16 count;
if (!TIFFGetField(tif, TIFFTAG_SUBIFD, &count, &subifds))
{
    std::cerr << "Failed to read SubIFD tag.\n";
    TIFFClose(tif);
    return 1;
}

// Attempt to set the subdirectory
if (TIFFSetSubDirectory(tif, subifds[0]) != 1) 
{
    std::cerr << "Failed to set SubDirectory.\n";
    // Attempt to set back to the main directory
    TIFFSetDirectory(tif, 0);
    // "tif" internal state is inconsistent, e.g. tif->tif_diroff
}

TIFFClose(tif);
return 0;

}

`

Edited by Manuel Massing