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 * Fill the data directory with zeros. 053 * 054 * @since 2.0 055 */ 056 public void erase() { 057 peFile.write(getVirtualAddress(), new byte[getSize()]); 058 } 059 060 /** 061 * Tells if the data directory is at the end of the file. 062 * 063 * @return <code>true</code> if the data directory is at the end of the file, <code>false</code> otherwise 064 * @throws IOException if an I/O error occurs 065 * @since 2.0 066 */ 067 public boolean isTrailing() throws IOException { 068 return getVirtualAddress() + getSize() == peFile.channel.size(); 069 } 070 071 public void write(long virtualAddress, int size) { 072 ByteBuffer buffer = ByteBuffer.allocate(8); 073 buffer.order(ByteOrder.LITTLE_ENDIAN); 074 buffer.putInt((int) virtualAddress); 075 buffer.putInt(size); 076 peFile.write(peFile.getDataDirectoryOffset() + index * 8, buffer.array()); 077 } 078}