*
*    WatchOpenDevice - a tool for AmigaOS to monitor OpenDevice() calls
*    Copyright (C) 1997 Matthias Andree
*
*    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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*

	XDEF _InitPatch
	XDEF _RemovePatch ; returns error core
	XDEF _RemovePatchForce ; no return

	XREF _LVOEnable
	XREF _LVODisable
	XREF _LVOOpenDevice
	XREF _LVOSetFunction
	XREF _OpenDevDebug ; has OpenDev args in d0/d1/a0/a1
			   ; OpenDevDebug MUST! take register arguments

	SECTION WOD_s,CODE

	IFD  __USE_SYSBASE
_SysBase EQU 4
	ELSE
	XREF _SysBase
	ENDC

* this is our OpenDevice replacement
* make sure this is properly aligned
_MyOpenDevice:
	movem.l d0-d7/a0-a6,-(sp)
	* Send message
	jsr     _OpenDevDebug
	movem.l (sp)+,d0-d7/a0-a6
	* Proceed to original function
	move.l  OldFunc(pc),-(sp)
	rts

_InitPatch:
	* Patch installieren
	move.l  _SysBase,a6
	jsr     _LVODisable(a6)
	move.l  #_MyOpenDevice,d0
	move.l  a6,a1
	move.l  #_LVOOpenDevice,a0
	jsr     _LVOSetFunction(a6)
	move.l  d0,OldFunc
	jsr     _LVOEnable(a6)
	moveq   #0,d0
	rts

_RemovePatch
	move.l  _SysBase,a6
	* Check if patched again, if not, remove patch
	cmp.l   #_MyOpenDevice,_LVOOpenDevice+2(a6)
	beq.s   _RemovePatchForce
	* if patched again, return error
	moveq   #-1,d0
	rts

_RemovePatchForce
	move.l  _SysBase,a6
	* remove patch
	jsr     _LVODisable(a6)
	move.l  OldFunc,d0
	move.l  a6,a1
	move.l  #_LVOOpenDevice,a0
	jsr     _LVOSetFunction(a6)
	jsr     _LVOEnable(a6)
	* return okay
	moveq   #0,d0
	rts

	cnop    0,4
OldFunc ds.l    1

	END
