001/**
002 * Copyright 2012 Emmanuel Bourg
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package net.jsign.pe;
018
019import java.io.IOException;
020import java.nio.ByteBuffer;
021import java.nio.ByteOrder;
022
023/**
024 * Entry of the data directory.
025 * 
026 * @author Emmanuel Bourg
027 * @since 1.0
028 */
029public class DataDirectory {
030
031    private final PEFile peFile;
032    private final int index;
033
034    DataDirectory(PEFile peFile, int index) {
035        this.peFile = peFile;
036        this.index = index;
037    }
038
039    public long getVirtualAddress() {
040        return peFile.readDWord(peFile.getDataDirectoryOffset(), index * 8);
041    }
042    
043    public int getSize() {
044        return (int) peFile.readDWord(peFile.getDataDirectoryOffset(), index * 8 + 4);
045    }
046
047    public boolean exists() {
048        return getVirtualAddress() != 0 && getSize() != 0;
049    }
050
051    /**
052     * Checks if the entry is valid.
053     *
054     * @throws IOException if the entry is invalid
055     * @since 4.2
056     */
057    void check() throws IOException {
058        long address = getVirtualAddress();
059        int size = getSize();
060
061        if (address < 0 || size < 0 || address + size > peFile.channel.size()) {
062            throw new IOException("Invalid data directory (index=" + index + ", address=" + address + ", size=" + size + ")");
063        }
064    }
065
066    /**
067     * Fill the data directory with zeros.
068     * 
069     * @since 2.0
070     */
071    public void erase() {
072        peFile.write(getVirtualAddress(), new byte[getSize()]);
073    }
074
075    /**
076     * Tells if the data directory is at the end of the file.
077     * 
078     * @return <code>true</code> if the data directory is at the end of the file, <code>false</code> otherwise
079     * @throws IOException if an I/O error occurs
080     * @since 2.0
081     */
082    public boolean isTrailing() throws IOException {
083        return getVirtualAddress() + getSize() == peFile.channel.size();
084    }
085
086    public void write(long virtualAddress, int size) {
087        ByteBuffer buffer = ByteBuffer.allocate(8);
088        buffer.order(ByteOrder.LITTLE_ENDIAN);
089        buffer.putInt((int) virtualAddress);
090        buffer.putInt(size);
091        peFile.write(peFile.getDataDirectoryOffset() + index * 8, buffer.array());
092    }
093}