/*
Copyright (C) 2006 Evan Teran
                   eteran@alum.rit.edu

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#ifndef MEMORY_REGIONS_20060501_H_
#define MEMORY_REGIONS_20060501_H_

#include <QVector>
#include <QString>
#include "types.h"
#include "DebugEventHandlerInterface.h"

struct BackupInfo;

class MemoryRegions {
public:
	MemoryRegions(BaseTypes::pid_t pid);

	struct Region : public DebugEventHandlerInterface {
	
		static const unsigned int READ;
		static const unsigned int WRITE;
		static const unsigned int EXEC;
		
		Region() : DebugEventHandlerInterface(), start(0), end(0), permissions(0), name(""), base(0), backupInfo(0), lock(0) {
		}
		
		virtual ~Region();
		
		Region(const Region &o) : DebugEventHandlerInterface(), start(o.start), end(o.end), permissions(o.permissions), name(o.name), base(o.base), backupInfo(0), lock(0) {
		}
		
		Region &operator=(const Region &o) {
			start		= o.start;
			end			= o.end;
			permissions	= o.permissions;
			name		= o.name;
			base		= o.base;
			backupInfo	= 0;
			lock		= 0;
			return *this;
		}
		
		bool operator==(const Region &o);
		
		BaseTypes::address_t	start;
		BaseTypes::address_t	end;
		uint8_t					permissions;
		QString					name;
		BaseTypes::address_t	base;
		
		bool readable() const	{ return (permissions & READ) != 0; }
		bool writeable() const	{ return (permissions & WRITE) != 0; }
		bool executable() const { return (permissions & EXEC) != 0; }
		int size() const		{ return end - start; }
		
		void setPermissions(bool read, bool write, bool execute);
		
	public:
		virtual void handleEvent(DebugEvent event);
		
	private:
		void setPermissions(bool read, bool write, bool execute, BaseTypes::address_t tempAddress);
		
	private:
		BackupInfo *backupInfo;
		int lock;
	};
	
	const QVector<Region> &regions() const { return m_Regions; }
	
	void sync();
	
	bool findRegion(BaseTypes::address_t address, Region &region) const;
	bool findRegion(BaseTypes::address_t address) const;
	
	BaseTypes::address_t findBaseAddress(const QString &name, bool *ok = 0) const;

private:
	BaseTypes::pid_t m_PID;
	QVector<Region> m_Regions;
};

#endif
