/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//@category Exporter

import java.io.*;
import java.util.List;

import ghidra.app.script.GhidraScript;
import ghidra.app.util.DomainObjectService;
import ghidra.app.util.Option;
import ghidra.app.util.exporter.Exporter;
import ghidra.app.util.exporter.ExporterException;
import ghidra.framework.model.DomainObject;
import ghidra.program.database.mem.AddressSourceInfo;
import ghidra.program.database.mem.FileBytes;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.Program;
import ghidra.program.model.mem.*;
import ghidra.program.model.reloc.Relocation;
import ghidra.util.HelpLocation;
import ghidra.util.task.TaskMonitor;

public class FixedBinaryExporter extends GhidraScript {

	private static final BinaryExporter EXPORTER = new BinaryExporter();

	@Override
	protected void run() throws Exception {
		File file = askFile("Output File", "OK");
		EXPORTER.export(file, currentProgram, null, monitor);
	}

	private static class BinaryExporter extends Exporter {

		public BinaryExporter() {
			super("TestBinary", "bin", new HelpLocation("ExporterPlugin", "binary"));
		}
	
	@Override
	public boolean export(File file, DomainObject domainObj, AddressSetView addrSet,
			TaskMonitor monitor) throws IOException, ExporterException {

		if (!(domainObj instanceof Program)) {
			log.appendMsg("Unsupported type: " + domainObj.getClass().getName());
			return false;
		}
		final Program program = (Program) domainObj;
		final Memory memory = program.getMemory();

		try (final RandomAccessFile fout = new RandomAccessFile(file, "rw")) {
			final List<FileBytes> fileBytes = memory.getAllFileBytes();
			if (!fileBytes.isEmpty()) {
				final FileBytes fByte = fileBytes.get(0);
				long offset = 0;
				long size = fByte.getSize();
				while (size > Integer.MAX_VALUE) {
					final byte[] bytes = new byte[Integer.MAX_VALUE];
					fByte.getModifiedBytes(offset, bytes);
					fout.write(bytes);
					size -= Integer.MAX_VALUE;
					offset += Integer.MAX_VALUE;
				}
				final byte[] bytes = new byte[(int) size];
				fByte.getModifiedBytes(offset, bytes);
				fout.write(bytes);
				final Iterable<Relocation> relocs =
					() -> program.getRelocationTable().getRelocations();
				for (Relocation reloc : relocs) {
					final AddressSourceInfo info = memory.getAddressSourceInfo(reloc.getAddress());
					// some relocations report negative offsets
					if (info.getFileOffset() >= 0) {
						// seek incase we are larger than an int
						fout.seek(info.getFileOffset());
						fout.write(reloc.getBytes());
					}
				}
			}
		}

		return true;
	}
	
		@Override
		public List<Option> getOptions(DomainObjectService domainObjectService) {
			return EMPTY_OPTIONS;
		}
	
		@Override
		public void setOptions(List<Option> options) {
		}
	}

}
