/*
Copyright 1990-2003 Sun Microsystems, Inc. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: The above copyright notice and this
permission notice shall be included in all copies or substantial
portions of the Software.


THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP OR SUN MICROSYSTEMS, INC. BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE EVEN IF
ADVISED IN ADVANCE OF THE POSSIBILITY OF SUCH DAMAGES.


Except as contained in this notice, the names of The Open Group and/or
Sun Microsystems, Inc. shall not be used in advertising or otherwise to
promote the sale, use or other dealings in this Software without prior
written authorization from The Open Group and/or Sun Microsystems,
Inc., as applicable.


X Window System is a trademark of The Open Group

OSF/1, OSF/Motif and Motif are registered trademarks, and OSF, the OSF
logo, LBX, X Window System, and Xinerama are trademarks of the Open
Group. All other trademarks and registered trademarks mentioned herein
are the property of their respective owners. No right, title or
interest in or to any trademark, service mark, logo or trade name of
Sun Microsystems, Inc. or its licensors is granted.

*/

#pragma ident	"$Id$"

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <limits.h>
#include <libgen.h>
#include <sys/param.h>
#include <dlfcn.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>
#if !defined(linux)
#include <libelf.h>
#include <gelf.h>
#endif /* !linux */

#if defined(IM_LOCALE)
#include <locale.h>
#endif /* defined(IM_LOCALE) */

#include <X11/Xlib.h>
#include <X11/Xatom.h>

#include "iiimpAux.h"

#include "xaux_common.h"
#include "xaux_so_common.h"

#if defined(linux) && !defined(MAXNAMELEN)
#define MAXNAMELEN (1024)
#endif /* linux && !MAXNAMELEN */

extern xaux_so_class_t xaux_classes[];

static void		aux_icid_init(void);
static void		aux_icid_finish(void);
static aux_icid_t *	aux_icid_get(int, Bool);
static void		aux_icid_delete(int);

static xaux_so_t	so_;
static xaux_so_t *	so = NULL;

static int		xaux_so_extexec_dirno = -1;

static unsigned int	sx_seqno = 0;

static unsigned int	maxpropsz = XAUX_MAXPROPSZ;

#define HASH_SIZE 137
static aux_icid_t	aux_icid[HASH_SIZE];

#if defined(WORKAROUND_XXXXXXX)
typedef struct window_list {
	Display *		display;
	Window			window;
	struct window_list *	next;
} window_list_t;
static window_list_t *	window_list;
typedef struct event_filter_param {
	Display *	display;
	Window		window;
	Bool		(* filter)(Display *, Window, XEvent *, XPointer);
	XPointer	call_data;
	struct event_filter_param *	next;
} event_filter_param_t;
static event_filter_param_t *	event_filter_param;
static void window_list_remember(Display * display, Window window);
static void window_list_forget(Display * display, Window window);
static void window_list_destroy_all(void);
static void event_filter_remember(
	Display *	display,
	Window		window,
	Bool		(* filter)(Display *, Window, XEvent *, XPointer),
	XPointer	call_data);
static void event_filter_forget(
	Display *	display,
	Window		window,
	Bool		(* filter)(Display *, Window, XEvent *, XPointer),
	XPointer	call_data);
static void event_filter_unregister_all(void);
#endif /* WORKAROUND_XXXXXXX */

/* workaround for "stored reference to aux_t is corrupred" problem */
static void (*aux_setvalue)(aux_t *, const unsigned char *, int);
static size_t (* mb_utf16)(const char **, size_t *, char **, size_t *);
static unsigned char * (* compose)(const aux_data_t *, int *);
static void (* register_X_filter)(Display *, Window, int, int,
		 Bool (* filter)(Display *, Window, XEvent *, XPointer),
		 XPointer);
static void (* unregister_X_filter)(Display *, Window,
		 Bool (* filter)(Display *, Window, XEvent *, XPointer),
		 XPointer);
static aux_t aux_tmp;

static Bool xaux_so_Create(aux_t *);
static Bool xaux_so_Start(aux_t *, const unsigned char *, int size);
static Bool xaux_so_Draw(aux_t *, const unsigned char *, int size);
static Bool xaux_so_Done(aux_t *, const unsigned char *, int size);
static Bool xaux_so_Switched(aux_t *, int im_id, int on_off);
static Bool xaux_so_Destroy(aux_t *);

#if defined(NOTIFY_STATE)
static Bool xaux_so_notify_state(xaux_so_class_t *);
#endif /* defined(NOTIFY_STATE) */

aux_method_t xaux_so_methods = {
	xaux_so_Create,
	xaux_so_Start,
	xaux_so_Draw,
	xaux_so_Done,
	xaux_so_Switched,
	xaux_so_Destroy
};

#if defined(WORKAROUND_XXXXXXX)
static void
window_list_remember(Display * display, Window window) {
	window_list_t *	wl;
	
	for (wl = window_list; NULL != wl; wl = wl->next) {
		if ((display == wl->display) && (window == wl->window)) return;
	}

	wl = (window_list_t *)malloc(sizeof (window_list_t));
	if (NULL == wl) return;

	wl->display = display;
	wl->window = window;
	wl->next = window_list;
	window_list = wl;

	return;
}

static void
window_list_forget(Display * display, Window window) {
	window_list_t *		wl;
	window_list_t **	wl_prev;
	
	wl_prev = &window_list;
	wl = window_list;
	while (NULL != wl) {
		if ((display == wl->display) && (window == wl->window)) {
			*wl_prev = wl->next;
			free(wl);
		} else {
			wl_prev = &(wl->next);
		}
		wl = *wl_prev;
	}

	return;
}

static void
window_list_destroy_all(void)
{
	window_list_t *	wl;
	window_list_t *	wl_next;

	for (wl = window_list; NULL != wl; wl = wl_next) {
		wl_next = wl->next;
		XDestroyWindow(wl->display, wl->window);
		free(wl);
	}
	window_list = NULL;

	return;
}

static void
event_filter_remember(
	Display *	display,
	Window		window,
	Bool		(* filter)(Display *, Window, XEvent *, XPointer),
	XPointer	call_data) {
	event_filter_param_t *	efp;
	
	for (efp = event_filter_param; NULL != efp; efp = efp->next) {
		if ((display == efp->display) &&
		    (window == efp->window) &&
		    (filter == efp->filter) &&
		    (call_data == efp->call_data)) {
			return;
		}
	}

	efp = (event_filter_param_t *)malloc(sizeof (event_filter_param_t));
	if (NULL == efp) return;

	efp->display = display;
	efp->window = window;
	efp->filter = filter;
	efp->call_data = call_data;
	efp->next = event_filter_param;
	event_filter_param = efp;

	return;
}

static void
event_filter_forget(
	Display *	display,
	Window		window,
	Bool		(* filter)(Display *, Window, XEvent *, XPointer),
	XPointer	call_data) {
	event_filter_param_t *	efp;
	event_filter_param_t **	efp_prev;
	
	efp_prev = &event_filter_param;
	efp = event_filter_param;
	while (NULL != efp) {
		if ((display == efp->display) &&
		    (window == efp->window) &&
		    (filter == efp->filter) &&
		    (call_data == efp->call_data)) {
			*efp_prev = efp->next;
			free(efp);
		} else {
			efp_prev = &(efp->next);
		}
		efp = *efp_prev;
	}

	return;
}

static void
event_filter_unregister_all(void)
{
	event_filter_param_t *	efp;
	event_filter_param_t *	efp_next;

	for (efp = event_filter_param; NULL != efp; efp = efp_next) {
		efp_next = efp->next;
		unregister_X_filter(efp->display, efp->window,
				    efp->filter, efp->call_data);
		free(efp);
	}
	event_filter_param = NULL;

	return;
}
#endif /* WORKAROUND_XXXXXXX */

static xaux_so_class_t *
xaux_getclass_bysowin(Window win)
{
	xaux_so_class_t	*p = xaux_classes;

	while (p->classname != NULL) {
		if (p->sowin == win)
			return (p);
		p++;
	}

	return (NULL);
}

static xaux_so_class_t *
xaux_getclass_byextwin(Window win)
{
	xaux_so_class_t	*p = xaux_classes;

	while (p->classname != NULL) {
		if (p->extwin == win)
			return (p);
		p++;
	}

	return (NULL);
}

static xaux_so_class_t *
xaux_getclass_byutfname(
	const CARD16 *	utfname,
	size_t		len)
{
	xaux_so_class_t	*p = xaux_classes;

	while (p->classname != NULL) {
		if (memcmp(p->utfname, utfname, len) == 0) {
			return p;
		}
		p++;
	}

	return NULL;
}

static Bool
xaux_so_extwin_event_filter(Display *, Window, XEvent *, XPointer);

static Bool
xaux_so_get_extwin(
	xaux_so_class_t	*xc,
	Display *	dpy)
{
	size_t		i;

	xc->extwin = XGetSelectionOwner(dpy, xc->atom_extwin);

	if (xc->extwin == None) {
		return (False);
	} else {
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] extwin=0x%x (selection)\n",
		xc->shortname, xc->extwin);
#endif /* defined(DEBUG_XAUX) */
		XSelectInput(dpy, xc->extwin,
			StructureNotifyMask | PropertyChangeMask);

		register_X_filter(dpy, xc->extwin, DestroyNotify, DestroyNotify,
			xaux_so_extwin_event_filter, (XPointer)xc);

		register_X_filter(dpy, xc->extwin,
			PropertyNotify, PropertyNotify,
			xaux_so_extwin_event_filter, (XPointer)xc);

#if defined(WORKAROUND_XXXXXXX)
		event_filter_remember(dpy, xc->extwin,
				      xaux_so_extwin_event_filter,
				      (XPointer)xc);
#endif /* WORKAROUND_XXXXXXX */

		return (True);
	}
}

xaux_so_execmng_data_t *
xaux_so_execmng_alloc_data(
	const char		*classname)
{
	xaux_so_execmng_data_t	*data;
	int			i;

	data = (xaux_so_execmng_data_t *)
		malloc(sizeof (xaux_so_execmng_data_t));

	if (data == NULL) {
		return (NULL);
	}

	for (i = 0; i < XAUX_SO_EXECMNG_LOGSIZE; i++) {
		data->log[i].time = (time_t)0;
		data->log[i].state = Initial;
	}

	return (data);
}

static Bool
xaux_so_execmng_triable(
	xaux_so_execmng_data_t	*data)
{
	time_t		cur;

	cur = time(NULL);

	if ((cur - data->log[XAUX_SO_EXECMNG_FAILSINPERIOD_TRIES - 1].time)
		< XAUX_SO_EXECMNG_FAILSINPERIOD_PERIOD) {
		/* too frequent tries */
		return (False);
	} else {
		return (True);
	}
}

static Bool
xaux_so_execmng_logstate(
	xaux_so_execmng_data_t	*data,
	xaux_so_extstate_t	state)
{
	int	i;

	for (i = XAUX_SO_EXECMNG_LOGSIZE - 1; i > 0; i--) {
		data->log[i] = data->log[i - 1];
	}

	data->log[0].time = time(NULL);
	data->log[0].state = state;

	return (True);
}

void
xaux_so_execmng_free_data(
	xaux_so_execmng_data_t	*data
)
{
	if (data == NULL) {
		return;
	}

	free(data);

	return;
}

#if	defined(__sparcv9)
#define	CHECK_SO		"sparcv9/check.so"
#else	/* !__sparcv9 */
#define	CHECK_SO		"check.so"
#endif	/* __sparcv9 */

/*
 * tentative hardcoded logic
 * Check if OK to execute binaries under "xaux1" directory, instead of
 * those under "xaux" directory.
 * The check is done by invoking "check" method in "xaux1/check.so".
 */
static Bool
xaux_so_check_xaux1(void)
{
	void *	handle = NULL;
	int	(*check)() = NULL;
	char	path[MAXPATHLEN];

	if (xaux_so_extexec_dirno >= 0) {
		if (xaux_so_extexec_dirno >= 1) {
			return (True);
		} else {
			return (False);
		}
	}

	snprintf(path, MAXPATHLEN, "%s%d/%s",
		xaux_so_extexec_path, 1, CHECK_SO);

	if ((handle = dlopen(path, RTLD_LAZY)) != NULL) {
		if ((check = ((int (*)())dlsym(handle, "check"))) != NULL) {
			if ((*check)() == 0) {
				dlclose(handle);
				xaux_so_extexec_dirno = 1;
				return (True);
			}
		}
		dlclose(handle);
	}

	xaux_so_extexec_dirno = 0;
	return (False);
}

static Bool
xaux_so_launch_ext(
	xaux_so_class_t	*xc,
	aux_icid_t	*ic)
{
	pid_t		pid;
	char		path[MAXPATHLEN];

#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] xaux_so_launch_ext() called\n", xc->shortname);
#endif /* defined(DEBUG_XAUX) */

	if (xc->extstate == ErrorPerm) {
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] not attempt to launch; permanent error\n",
		xc->shortname);
#endif /* defined(DEBUG_XAUX) */
		return (False);
	}

	if (xaux_so_get_extwin(xc, ic->dpy) == True) {
		/*
		 * succeeded in communicating
		 * with already running external program
		 */
		xc->extstate = Connected;
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] extwin=0x%x (selection:l)\n",
		xc->shortname, xc->extwin);
#endif /* defined(DEBUG_XAUX) */
		return (True);
	}

	if (ic->server == False) {
		/*
		 * do not launch external program
		 * if not loaded by server (htt_xbe) program
		 */
		xc->extstate = ErrorPerm;
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] not attempt to launch; not xbe process\n",
		xc->shortname);
#endif /* defined(DEBUG_XAUX) */
		return (False);
	}

	/*
	 * tentative hardcoded logic
	 * If OK to use xaux1 binaries, use them.
	 */
	if (xaux_so_check_xaux1() == True) {
		snprintf(path, MAXPATHLEN, "%s%d/%s",
			xaux_so_extexec_path, 1, xc->extexec);
	} else {
		snprintf(path, MAXPATHLEN, "%s/%s",
			xaux_so_extexec_path, xc->extexec);
	}

#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] trying executable \"%s\"....\n",
		xc->shortname, path);
#endif /* defined(DEBUG_XAUX) */

	if (access(path, X_OK) != 0) {
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] executable \"%s\" not found\n",
		xc->shortname, path);
#endif /* defined(DEBUG_XAUX) */
		xc->extstate = ErrorPerm;
		return (False);
	}
			
	pid = fork1();

	if (pid == (pid_t)(-1)) { /* fork failed */
		xc->extstate = ErrorTemp;
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] fork failed\n", xc->shortname);
#endif /* defined(DEBUG_XAUX) */
		return (False);
	} else if (0 == pid) { /* child */
#if defined(IM_LOCALE)
		char	*cur;
		size_t	bufsz = sizeof ("LC_ALL=") + MAXNAMELEN;
		char	buf[sizeof ("LC_ALL=") + MAXNAMELEN];

		cur = setlocale(LC_CTYPE, NULL);

		if (cur == NULL) {
			cur = "C";
		}

		if (strncmp(cur, "ja", 2) == 0) { /* locale name is ja* */
			/* Japanese locale; set to current locale */
			snprintf(buf, bufsz, "LC_ALL=%s", cur);
			putenv(buf);
			snprintf(buf, bufsz, "LANG=%s", cur);
			putenv(buf);
		} else {
			/* not Japanese locale; set to IM_LOCALE */
			putenv("LC_ALL=" IM_LOCALE);
			putenv("LANG=" IM_LOCALE);
		}
#endif /* defined(IM_LOCALE) */
#if defined(DEBUG_XAUX)
		chdir("/tmp");
#endif /* defined(DEBUG_XAUX) */
		execl(path, xc->classname, NULL);
		_exit(1);
	}

	/* parent */
	xc->extstate = Launched;
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] fork done\n", xc->shortname);
#endif /* defined(DEBUG_XAUX) */
	return (True);
}

static Bool
xaux_so_notify_flowstate(
	xaux_so_class_t *	xc,
	int			flowstate)
{
	int		size;
	aux_data_t	aux_data_;
	aux_data_t *	aux_data = &(aux_data_);
	int		state;
	int		int_array[2];
	unsigned char	*p;

	if (xc->ic == NULL) {
		/* no current IC */
		return (False);
	}

	/* header */

	aux_data->type = AUX_DATA_SETVALUE;
	aux_data->im = xc->ic->imid;
	aux_data->ic = xc->ic->icid;
	aux_data->aux_index = xc->index;
	aux_data->aux_name = (unsigned char *)xc->utfname;
	aux_data->aux_name_length = strlen(xc->classname)*sizeof(CARD16);

	/* int values */

	aux_data->integer_count = 2;

	aux_data->integer_list = &int_array[0];
	aux_data->integer_list[0] = XAUX_SO_NOTIFY_FLOWSTATE_ID;
	aux_data->integer_list[1] = flowstate;

	/* no string values */

	aux_data->string_count = 0;
	aux_data->string_list = NULL;
	aux_data->string_ptr = NULL;

	/* compose and send message to engine */

/* workaround for "stored reference to aux_t is corrupred" problem */
	if ((p = /*ic->aux->service->*/compose(aux_data, &size)) == NULL) {
		return (False);
	}

#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] SETVALUE(flow): im=0x%x ic=0x%x i[0]=0x%x "
			"i[1]=0x%x in=%d sn=%d\n",
		xc->shortname, aux_data->im, aux_data->ic,
		aux_data->integer_list[0], aux_data->integer_list[1],
		aux_data->integer_count, aux_data->string_count);
#endif /* defined(DEBUG_XAUX) */

/* workaround for "stored reference to aux_t is corrupred" problem */
	/*ic->aux->service->*/aux_setvalue(/*ic->aux*/&aux_tmp, p, size);

	return (True);
}

static Bool
xaux_sx_flushq(
	Display		*dpy,
	Window		win,
	xaux_so_class_t	*xc,
	Bool		detour)
{
	Bool		rv = True;
	unsigned char	*p;
	int		len;
	Atom		atom;
	int		qcount;

	if ((win = xc->extwin) == (Window)None) {
		if (xaux_so_get_extwin(xc, dpy) == True) {
			win = xc->extwin;
		} else if (detour) {
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] property detoured to sowin\n", xc->shortname);
#endif /* defined(DEBUG_XAUX) */
			win = xc->sowin;
		} else {
			/* discard remaining data */
			xaux_propq_clean(xc->propq);
			return (False);
		}
	}

	while (xaux_propq_check(xc->propq) > 0) {
		atom = xaux_atommng_get_atom(xc->atommng_data, win);
		if (atom == (Atom)None) {
			break;
		}
		if ((qcount = xaux_propq_get(xc->propq, &p, &len)) >= 0) {
			XChangeProperty(dpy, win, atom, XA_STRING, 8,
				PropModeReplace, (unsigned char *)p, len);
			XFlush(dpy);
#if defined(DEBUG_XAUX)
fprintf(stderr, "[%s] send property atom=%d\n", xc->shortname, atom);
#endif /* defined(DEBUG_XAUX) */
			free(p);
		} else {
			break;
		}
	}

	return (rv);
}

static Bool
xaux_sx_check_propdel(
	Display		*dpy,
	XEvent		*ev,
	XPointer	arg)
{
	xaux_so_class_t	*xc = (xaux_so_class_t *)arg;

	if (ev->type == PropertyNotify) {
		XPropertyEvent	*pev = &(ev->xproperty);

		if ((pev->state == PropertyDelete)
				&& (pev->atom == xc->atom_sx)) {
			return (True);
		}
	} else if (ev->type == DestroyNotify) {
		XDestroyWindowEvent	*dev = &(ev->xdestroywindow);

		if (dev->window == xc->extwin) {
			return (True);
		}
	}

	return (False);
}

static Bool
xaux_so_process_destroy_extwin(
	Display *	dpy,
	Window		win,
	XDestroyWindowEvent	*ev)
{
	xaux_so_class_t *	xc;

	if ((xc = xaux_getclass_byextwin(ev->window)) == NULL) {
		return (False);
	}

#if defined(DEBUG_XAUX)
fprintf(stderr, "[%s] extwin 0x%x destroyed\n", xc->shortname, win);
#endif /* defined(DEBUG_XAUX) */

	xc->extwin = (Window)None;
	xc->extstate = Disconnected;

	xaux_atommng_release_atom(xc->atommng_data);
	xaux_propq_clean(xc->propq);

#if defined(NOTIFY_STATE)
	(void)xaux_so_notify_state(xc);
#endif /* defined(NOTIFY_STATE) */

        unregister_X_filter(dpy, xc->extwin,
			xaux_so_extwin_event_filter, NULL);
#if defined(WORKAROUND_XXXXXXX)
	event_filter_forget(dpy, xc->extwin, xaux_so_extwin_event_filter, NULL);
#endif /* WORKAROUND_XXXXXXX */

#if defined(SO_RESTART_EXT_AUTO)
	if (xc->ic != NULL) { /* have current IC */
		/* then restart external process */
		if (xaux_so_execmng_triable(xc->execmng_data)) {
			xaux_so_launch_ext(xc, xc->ic);
#if defined(NOTIFY_STATE)
	(void)xaux_so_notify_state(xc);
#endif /* defined(NOTIFY_STATE) */
		}
	}
#endif /* defined(SO_RESTART_EXT_AUTO) */

	return (True);
}


static Bool
xaux_so_send_property(
	aux_t *			aux,
	xaux_so_class_t *	xc,
	unsigned char *		p,	/* data to send */
	int			len,	/* length of data (bytes) */
	Bool			detour)	/* use sowin when extwin is absent */
{
	Display *	dpy;
	Bool		rv;
	Atom		atom;
	Window		win;
	int		i;
	int		qcount;
	struct pollfd	fds[1];
	XEvent		ev;
	int		retry_count;

	dpy = aux->service->display(aux);

	fds[0].fd = ConnectionNumber(dpy);
	fds[0].events = POLLIN;
	fds[0].revents = 0;

	/* first try to flush existing data (if any) */
	xaux_sx_flushq(dpy, win, xc, detour);

	retry_count = 0;
	while (xaux_propq_check(xc->propq) > 0) {
		int	r;

		if (XCheckIfEvent(dpy, &ev, xaux_sx_check_propdel, (XPointer)xc)
				== True) {
			retry_count = 0;
			if (ev.type == PropertyNotify) {
				/* atom released - flush existing data */
				xaux_atommng_process_delete(xc->atommng_data,
					(XPropertyEvent *)(&(ev.xproperty)));
				xaux_sx_flushq(dpy, win, xc, detour);
			} else if (ev.type == DestroyNotify) {
				/* extwin deleted - discard unset data */
				xaux_so_process_destroy_extwin(dpy,
					ev.xdestroywindow.window,
					(XDestroyWindowEvent *)
					(&(ev.xdestroywindow)));
				free(p);
				return (False);
			}
		} else {
			/* wait data from X server */
			retry_count += 1;
			if (retry_count <= 20) {
 				r = poll(&(fds[0]), 1, (100 * retry_count));
/*  			if (retry_count <= 3) { */
/*  				r = poll(&(fds[0]), 1, (1000 * retry_count)); */
/*  				r = poll(&(fds[0]), 1, */
/*  					 (1 == retry_count) ? */
/*  					 500 : (1000 * retry_count)); */
			} else {
				r = 0;
			}
			if (r <= 0) {
				xaux_atommng_release_atom(xc->atommng_data);
				xaux_sx_flushq(dpy, win, xc, detour);
			}
		}
	}

	if ((qcount = xaux_propq_add(xc->propq, p, len)) == -1) {
		/* malloc error */
		free(p);
		return (False);
	} else if (qcount == -2) {
		/* queue full */
		free(p);
		return (False);
	}

	/* try to flush data just added */
	xaux_sx_flushq(dpy, win, xc, detour);

	return (True);
}

static Bool
xaux_so_dispatch_propnot_extwin(
	Display		*dpy,
	Window		win,
	XPropertyEvent	*pev,
	xaux_so_class_t	*xc)
{
	Bool		rv = False;

	if (xaux_atommng_check_atom(xc->atommng_data, False, pev->atom)
			== True) {
		/* sx */
		if (pev->state == PropertyDelete) {
			if (xaux_atommng_process_delete(xc->atommng_data, pev)
					== True) {
				xaux_sx_flushq(dpy, pev->window, xc, True);
			}
		}
		rv = True;
	}

	return (rv);
}

static Bool
xaux_so_extwin_event_filter(
	Display *	display,
	Window		window,
	XEvent *	event,
	XPointer	pointer)
{
	switch (event->type) {
	case DestroyNotify:
		return (xaux_so_process_destroy_extwin(display, window,
			(XDestroyWindowEvent *)event));
	case PropertyNotify:
		return (xaux_so_dispatch_propnot_extwin(display, window,
			(XPropertyEvent *)(&event->xproperty),
			(xaux_so_class_t *)pointer));
	}
	return (False);
}

static Bool
xaux_so_clean_setv_state(xaux_so_setv_state_t *state, Bool initial)
{
	int		maxnprops_sv;
	unsigned char	**props_sv;
	aux_data_t *	aux_data;
	int		i;

	if (!initial) {
		if (state->aux_data != NULL) {
			free(state->aux_data->integer_list);
			aux_data = state->aux_data;
			if (NULL != aux_data->string_list) {
				for (i = 0; i < aux_data->string_count; i++) {
					free((aux_data->string_list + i)->ptr);
				}
			}
			free(state->aux_data->string_list);
		}
		free(state->outbuf);

		for (i = 0; i < state->nprops; i++) {
			if (state->props[i] != NULL) {
				XFree(state->props[i]);
			}
		}

		maxnprops_sv = state->maxnprops;
		props_sv = state->props;
	}

	memset(state, 0, sizeof (xaux_so_setv_state_t));

	if (initial) {
		state->maxnprops = XAUX_MAXNPROPS_INIT;
		if ((state->props = (unsigned char **)malloc(
				sizeof (unsigned char *)
				* state->maxnprops)) == NULL) {
			return (False);
		}
	} else {
		state->maxnprops = maxnprops_sv;
		state->props = props_sv;
	}

	state->nprops = 0;
	state->stored = False;
	state->aux_data = &(state->aux_data_);

	return (True);
}

static Bool
xaux_so_add_prop_to_setv_state(
	xaux_so_setv_state_t	*state,
	unsigned char		*prop)
{
	int		maxnprops = state->maxnprops;
	int		nprops = state->nprops;
	unsigned char	**props = state->props;

	if ((state->nprops) >= state->maxnprops) {
		maxnprops += XAUX_MAXNPROPS_INIT;
		props = (unsigned char **)realloc(props,
			sizeof (unsigned char *) * maxnprops);
		if (props == NULL) {
			return (False);
		}
		state->maxnprops = maxnprops;
		state->props = props;
	}

	state->props[state->nprops] = prop;
	state->nprops++;
	return (True);
}

static Bool
xaux_so_init_setv_state(
	xaux_so_setv_state_t	*state,
	xaux_so_class_t		*xc,
	unsigned char		*prop)
{
	aux_data_t	*aux_data;
	char		*setv;

	if (xaux_so_clean_setv_state(state, False) == False) {
		return (False);
	}

	setv = (char *)XS_DATA_TOP(prop);

	state->seqno = BO_SEQNO(prop);

	aux_data = state->aux_data;
	aux_data->type = AUX_DATA_DRAW;
	aux_data->im = BO_IMID(prop);
	aux_data->ic = BO_ICID(prop);
	aux_data->aux_index = xc->index;
	aux_data->aux_name = (unsigned char *)xc->utfname;
	aux_data->aux_name_length =
		(strlen((const char *)xc->classname) * (sizeof (CARD16)));
	aux_data->integer_count = BO_SETV_INT_COUNT(prop);
	aux_data->string_count = BO_SETV_STR_COUNT(prop);

	state->segno = BO_SEGNO(prop);

	state->str_yet = 0;

	if (aux_data->integer_count > 0) {
		if ((aux_data->integer_list = (int *)malloc(sizeof (int)
				* aux_data->integer_count)) == NULL) {
			(void)xaux_so_clean_setv_state(state, False);
			return (False);
		}
	} else {
		aux_data->integer_list = NULL;
	}

	if (aux_data->string_count > 0) {
		if ((aux_data->string_list = (aux_string_t *)malloc(
				sizeof (aux_string_t) *
				aux_data->string_count)) == NULL) {
			(void)xaux_so_clean_setv_state(state, False);
			return (False);
		}
	}

	return (True);
}

static Bool
xaux_so_process_property_xs(
	Display	*		dpy,
	Window			window,
	Atom			atom,
	xaux_so_class_t *	xc)
{
	Atom		actual_type_return = (Atom)None;
	int		actual_format_return = 0;
	unsigned long	nitem_return = 0;
	unsigned long	bytes_after_return = 0;
	unsigned char *	prop = NULL;
	unsigned char *	setv;
	unsigned char	*p;
	int		r;
	unsigned char	*proptail;
/*
	aux_icid_t * 	ic;
*/
	int		size;
	aux_data_t	aux_data_;
	aux_data_t *	aux_data = &(aux_data_);
	int		i;
	int		n=0;
	Bool		rv = True;

	xaux_so_setv_state_t	*state;
	int		*ip;
	char		*sp;

	r = XGetWindowProperty(dpy, window,
			       atom, 0, INT_MAX, True,
			       XA_STRING, &actual_type_return,
			       &actual_format_return, &nitem_return,
			       &bytes_after_return, &prop);

	if ((r != Success) || (actual_type_return != XA_STRING)) {
		return False;
	}

/*
	if ((ic = aux_icid_get(BO_ICID(prop_return), False)) == NULL) {
		XFree(prop_return);
		return (False);
	}
*/
	XSetSelectionOwner(dpy, atom, (Window)None, CurrentTime);

	proptail = prop + XS_SIZE_HEADER + BO_SEGSIZE(prop);

	setv = XS_DATA_TOP(prop);

	if (xc->pending_setv == NULL) {
		if ((xc->pending_setv = (xaux_so_setv_state_t *)malloc(
				sizeof (xaux_so_setv_state_t))) == NULL) {
			rv = False;
			goto cleanup_return;
		}
		xaux_so_clean_setv_state(xc->pending_setv, True);
	}

	if (BO_SEGNO(prop) > 0) {
		if (xc->pending_setv->stored == True) {
			if (BO_SEGNO(prop) == (xc->pending_setv->segno + 1)) {
#if defined(DEBUG_XAUX)
fprintf(stderr, "[%s] SETV: segno=%d, continue with stored segno=%d\n",
		xc->shortname, BO_SEGNO(prop), xc->pending_setv->segno);
#endif /* defined(DEBUG_XAUX) */
				state = xc->pending_setv;
				ip = (int *)setv;
			} else {
#if defined(DEBUG_XAUX)
fprintf(stderr, "[%s] SETV: stored segno mismatch (%d expected %d actual)\n",
		xc->shortname, xc->pending_setv->segno + 1, BO_SEGNO(prop));
#endif /* defined(DEBUG_XAUX) */
				xaux_so_clean_setv_state(xc->pending_setv,
					False);
				rv = False;
				goto cleanup_return;
			}
		} else {
#if defined(DEBUG_XAUX)
fprintf(stderr, "[%s] SETV: received segno=%d but no stored segs\n",
		xc->shortname, BO_SEGNO(prop));
#endif /* defined(DEBUG_XAUX) */
			rv = False;
			goto cleanup_return;
		}
	} else {
		if (xc->pending_setv->stored == True) {
#if defined(DEBUG_XAUX)
fprintf(stderr, "[%s] SETV: stored but received segno=0 (%d expected)\n",
				xc->shortname, xc->pending_setv->segno + 1);
#endif /* defined(DEBUG_XAUX) */
			xaux_so_init_setv_state(xc->pending_setv, xc, prop);
		} else {
			xaux_so_init_setv_state(xc->pending_setv, xc, prop);
		}
		state = xc->pending_setv;
		ip = (int *)BO_SETV_INT_LIST(setv);
	}

	aux_data = state->aux_data;

	for (i = state->int_next; i < aux_data->integer_count; i++) {
		if ((unsigned char *)ip >= proptail) {
			state->int_next = i;
			state->segno = BO_SEGNO(prop);
			xaux_so_add_prop_to_setv_state(state, prop);
			state->stored = True;
#if defined(DEBUG_XAUX)
fprintf(stderr, "[%s] DRAW: received up to int[%d]\n", xc->shortname, i - 1);
#endif /* defined(DEBUG_XAUX) */
			return (True);
		}
		aux_data->integer_list[i] = BO_CARD32(prop, ip);
		ip++;
	}

	state->int_next = i;

	sp = (char *)ip;

	for(i = state->str_next; i < aux_data->string_count; i++) {
		int	len;

		if (sp >= (char *)proptail) {
			state->str_next = i;
			state->segno = BO_SEGNO(prop);
			xaux_so_add_prop_to_setv_state(state, prop);
			state->stored = True;
#if defined(DEBUG_XAUX)
fprintf(stderr, "(%s) DRAW: received up to string[%d]\n", xc->shortname, i - 1);
#endif /* defined(DEBUG_XAUX) */
			return (True);
		}

		len = BO_CARD16(prop, sp);
		aux_data->string_list[i].length = len;
		sp += sizeof(CARD16);
		aux_data->string_list[i].ptr =
			(unsigned char *)malloc((sizeof (CARD16)) * len);
		if (1 == (*((CARD16 *)(prop)))) {
			memcpy((char *)(aux_data->string_list[i].ptr), sp,
			       (sizeof (CARD16)) * len);
		} else {
			swab(sp, (char *)(aux_data->string_list[i].ptr),
			     (sizeof (CARD16)) * len);
		}
		sp += (len + padding[(sizeof(CARD16) + len) % 4]);
	}

#if defined(DEBUG_XAUX)
	if (aux_data->integer_count > 0) {
		fprintf(stderr, "[%s] SETV: im=0x%x ic=0x%x "
				"i[0]=0x%x in=%d sn=%d\n",
			xc->shortname,
			aux_data->im, aux_data->ic,
			aux_data->integer_list[0],
			aux_data->integer_count,
			aux_data->string_count);
	} else {
		fprintf(stderr, "[%s] SETV: im=0x%x ic=0x%x in=%d sn=%d\n",
			xc->shortname,
			aux_data->im, aux_data->ic,
			aux_data->integer_count,
			aux_data->string_count);
	}
#endif /* defined(DEBUG_XAUX) */

/* workaround for "stored reference to aux_t is corrupred" problem */
	if ((p = /*ic->aux->service->*/compose(aux_data, &size)) == NULL) {
		xaux_so_clean_setv_state(state, False);
		rv = False;
		goto cleanup_return;
	}

/* workaround for "stored reference to aux_t is corrupred" problem */
	/*ic->aux->service->*/aux_setvalue(/*ic->aux*/&aux_tmp, p, size);

	xaux_so_clean_setv_state(state, False);

cleanup_return:
	if (prop != NULL) {
		XFree(prop);
	}

	return (rv);
}

static Bool
xaux_so_notify_state(
	xaux_so_class_t *	xc)
{
	int		size;
	aux_data_t	aux_data_;
	aux_data_t *	aux_data = &(aux_data_);
	int		state;
	int		int_array[2];
	unsigned char	*p;

	if (xc->ic == NULL) {
		/* no current IC */
		return (False);
	}

	switch (xc->extstate) {
	case Initial:
		state = XAUX_SO_NOTIFY_STATE_NOTAVAILABLE;
		break;
	case ErrorPerm:
		state = XAUX_SO_NOTIFY_STATE_NOTAVAILABLE;
		break;
	case ErrorTemp:
		state = XAUX_SO_NOTIFY_STATE_NOTAVAILABLE;
		break;
	case Launched:
		state = XAUX_SO_NOTIFY_STATE_STANDBY;
		break;
	case Connected:
		state = XAUX_SO_NOTIFY_STATE_OK;
		break;
	case Disconnected:
		state = XAUX_SO_NOTIFY_STATE_NOTAVAILABLE;
		break;
	}

	/* header */

	aux_data->type = AUX_DATA_SETVALUE;
	aux_data->im = xc->ic->imid;
	aux_data->ic = xc->ic->icid;
	aux_data->aux_index = xc->index;
	aux_data->aux_name = (unsigned char *)xc->utfname;
	aux_data->aux_name_length = strlen(xc->classname)*sizeof(CARD16);

	/* int values */

	aux_data->integer_count = 2;

	aux_data->integer_list = &int_array[0];
	aux_data->integer_list[0] = XAUX_SO_NOTIFY_STATE_ID;
	aux_data->integer_list[1] = state;

	/* no string values */

	aux_data->string_count = 0;
	aux_data->string_list = NULL;
	aux_data->string_ptr = NULL;

	/* compose and send message to engine */

/* workaround for "stored reference to aux_t is corrupred" problem */
	if ((p = /*ic->aux->service->*/compose(aux_data, &size)) == NULL) {
		return (False);
	}

#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] SETVALUE(state): im=0x%x ic=0x%x i[0]=0x%x "
			"i[1]=0x%x in=%d sn=%d\n",
		xc->shortname, aux_data->im, aux_data->ic,
		aux_data->integer_list[0], aux_data->integer_list[1],
		aux_data->integer_count, aux_data->string_count);
#endif /* defined(DEBUG_XAUX) */

/* workaround for "stored reference to aux_t is corrupred" problem */
	/*ic->aux->service->*/aux_setvalue(/*ic->aux*/&aux_tmp, p, size);

	return (True);
}

static Bool
xaux_so_process_property_xs_list(
	Display	*		dpy,
	Window			win,
	xaux_so_class_t		*xc,
	Atom			atom)
{
	int		r;		/* return of Xlib functions */
	Bool		rv;		/* return of xaux functions */
	unsigned long	bytes_after_return = 0U;

	rv = xaux_so_process_property_xs(dpy, xc->sowin, atom, xc);

	return (True);
}

static Bool
xaux_so_process_property_extwin(
	Display	*		dpy,
	Window			win,
	xaux_so_class_t		*xc)
{
	int		r;		/* return of Xlib functions */
	Atom		actual_type_return;
	int		actual_format_return;
	unsigned long	nitems_return = 0;
	unsigned char	*prop_return = NULL;
	unsigned long	bytes_after_return = 0U;

	r = XGetWindowProperty(dpy, xc->sowin, xc->atom_extwin,
		(long)0, 1, False, XA_WINDOW,
		&actual_type_return,
		&actual_format_return,
		&nitems_return,
		&bytes_after_return,
		&prop_return);
	
	if ((r != Success) || (actual_type_return != XA_WINDOW)) {
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] property %s read failed\n",
		xc->shortname, XGetAtomName(dpy, xc->atom_extwin));
#endif /* defined(DEBUG_XAUX) */
		return (False);
	}

	xc->extwin = *(Window *)(prop_return);
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] extwin=0x%x (property)\n",
		xc->shortname, xc->extwin);
#endif /* defined(DEBUG_XAUX) */

	if (xc->extstate != Connected) {
		xc->extstate = Connected;
#if defined(NOTIFY_STATE)
		xaux_so_notify_state(xc);
#endif /* defined(NOTIFY_STATE) */
	}

	if (prop_return != NULL) {
		XFree(prop_return);
	}

	XSelectInput(dpy, xc->extwin,
		StructureNotifyMask | PropertyChangeMask);

	register_X_filter(dpy, xc->extwin, DestroyNotify, DestroyNotify,
		xaux_so_extwin_event_filter, (XPointer)NULL);

#if defined(WORKAROUND_XXXXXXX)
	event_filter_remember(dpy, xc->extwin,
			      xaux_so_extwin_event_filter, (XPointer)NULL);
#endif /* WORKAROUND_XXXXXXX */

	register_X_filter(dpy, xc->extwin, PropertyNotify, PropertyNotify,
		xaux_so_extwin_event_filter, (XPointer)xc);

#if defined(WORKAROUND_XXXXXXX)
	event_filter_remember(dpy, xc->extwin, 
			      xaux_so_extwin_event_filter, (XPointer)xc);
#endif /* WORKAROUND_XXXXXXX */

	return (True);
}

static Bool
xaux_so_process_property_notify(
	Display	*		dpy,
	Window			win,
	XPropertyEvent		*pev)
{
	Bool		rv = False;
	xaux_so_class_t	*xc;

	if ((xc = xaux_getclass_bysowin(pev->window)) == NULL) {
		return False;
	}
	
	if (pev->atom == xc->atom_extwin) { /* notify extwin */
		if (pev->state == PropertyNewValue) {
			rv = xaux_so_process_property_extwin(dpy, win, xc);
		} else {
			rv = True;
		}
	} else if (xaux_atommng_check_atom(xc->atommng_data, True, pev->atom)
			== True) {
		/* xs */
		if (pev->state == PropertyNewValue) {
			rv = xaux_so_process_property_xs_list(dpy, win, xc,
				pev->atom);
		}
		rv = True;
	} else if (xaux_atommng_check_atom(xc->atommng_data, False, pev->atom)
			== True) {
		/* sx(detoured) */
		if (pev->state == PropertyDelete) {
			if (xaux_atommng_process_delete(xc->atommng_data, pev)
					== True) {
				xaux_sx_flushq(dpy, xc->extwin, xc, True);
			}
		}
		rv = True;
	}


	return (rv);
}

static Bool
xaux_so_sowin_event_filter(
	Display *	display,
	Window		window,
	XEvent *	event,
	XPointer	pointer)
{
	xaux_so_class_t	*xc = (xaux_so_class_t *)pointer;
	Bool		rv;

	switch (event->type) {
	case PropertyNotify:
		rv = xaux_so_process_property_notify(display, window,
			(XPropertyEvent *)event);
		break;
	case SelectionClear:
		if ((rv = xaux_atommng_process_selclr(xc->atommng_data,
				(XSelectionClearEvent *)event)) == True) {
			xaux_sx_flushq(display, xc->extwin, xc, True);
		}
		break;
	}
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[--] ignore event type=%d\n", event->type);
#endif /* defined(DEBUG_XAUX) */
	return False;
}

static void
aux_icid_init(void)
{
	int	i;

	for (i = 0; i < HASH_SIZE; i++) {
		aux_icid[i].icid = (-1);
	}
}

static void
aux_icid_finish(void)
{
	int		i;
	aux_icid_t *	p0;
	aux_icid_t *	p1;

	for (i = 0; i < HASH_SIZE; i++) {
		p0 = aux_icid[i].next;

		for (; p0 != NULL; p0 = p1) {
			p1 = p0->next;
			free(p0);
		}
	}
}

static aux_icid_t *
aux_icid_get(
	int	icID,
	Bool	createit)
{
	int		hash_value;
	aux_icid_t *	p;

	p = &(aux_icid[icID % HASH_SIZE]);

	if (p->icid == -1) {
		if (!createit)
			return NULL;
		p->icid = icID;
		return (p);
	}

	for (; ; p = p->next) {
		if (icID == p->icid) {
			return p;
		}
		if (p->next == NULL) {
			if (!createit)
				return NULL;
			p->next = malloc(sizeof (aux_icid_t));
			if (p->next == NULL) {
				return NULL;
			}
			memset(p->next, 0, (sizeof (aux_icid_t)));
			p->next->prev = p;
			p->next->next = NULL;
			p->next->icid = icID;
			return (p->next);
		}
	}
}

static void
aux_icid_delete(int icID)
{
	aux_icid_t *	p;

	p = aux_icid_get(icID, False);

	if (NULL == p) {
		return;
	}

	p->icid = -1;

	if (p->next != NULL) {
		p->next->prev = p->prev;
	}
	if (p->prev != NULL) {
		p->prev->next = p->next;
		free(p);
	}
}

static Bool
xaux_so_init_classes_phase1(
	xaux_so_t *	so,
	aux_t *		aux)
{
	Display		*dpy;

	xaux_so_class_t *p = xaux_classes;

	dpy = aux->service->display(aux);

	while (p->classname != NULL) {
		if (p->extexec == NULL) {
			/* this class does not use external process */
			p++;
			continue;
		}

		p->extstate = Initial;

		p->shortname = strrchr(p->classname, '.');
		if (p->shortname == NULL) {
			p->shortname = (char *)p->classname;
		} else {
			p->shortname++;
		}
		p->shortname = strdup(p->shortname);
		if (p->shortname == NULL) {
			p->shortname = "";
		} else {
			if (strlen(p->shortname) > 4) {
				p->shortname[4] = '\0';
			}
		}

		p->atom_classname = (Atom)None;
		p->atom_sowin = (Atom)None;
		p->atom_extwin = (Atom)None;
		p->atommng_data = NULL;
		p->execmng_data = NULL;
		p->sowin = (Window)None;
		p->extwin = (Window)None;
		p->propq = NULL;

		p++;
	}

	so->classes = xaux_classes;

	return (True);
}

static Bool
xaux_so_init_class_phase2(
	xaux_so_class_t	*xc,
	aux_t		*aux)
{
	Display		*dpy;
	char		buf[XAUX_MAXCLASSNAMELEN + XAUX_MAXSUFFIXLEN + 1];

	if (xc->extexec == NULL) {
		/* this class does not use external process */
		return (True);
	}

	dpy = aux->service->display(aux);

	xc->atom_classname = XInternAtom(dpy, xc->classname, False);

	sprintf(buf, "%s%s", xc->classname, XAUX_SOWIN_SUFFIX);
	xc->atom_sowin = XInternAtom(dpy, buf, False);

	sprintf(buf, "%s%s", xc->classname, XAUX_EXTWIN_SUFFIX);
	xc->atom_extwin = XInternAtom(dpy, buf, False);

	sprintf(buf, "%s_sx", xc->classname);
	xc->atom_sx = XInternAtom(dpy, buf, False);

	sprintf(buf, "%s_xs", xc->classname);
	xc->atom_xs = XInternAtom(dpy, buf, False);

	xc->atommng_data = xaux_atommng_alloc_data(
		xc->classname, False /* means "sx" */, dpy);

	xc->execmng_data = xaux_so_execmng_alloc_data(xc->classname);

	xc->propq = xaux_propq_alloc(XAUX_MAXPROPSZ);

	if (XGetSelectionOwner(dpy, xc->atom_sowin) != None) {
#if defined(DEBUG_XAUX)
		fprintf(stderr, "%s: %s already exists. [%s](1)\n",
			ME_SO, ME_SO, xc->classname);
#endif /* defined(DEBUG_XAUX) */
		goto done_sowin;
	}

	xc->sowin = XCreateSimpleWindow(dpy, RootWindow(dpy, 0),
		     0, 0, 1, 1, 0, 0, 0);

	if (xc->sowin == None) {
		fprintf(stderr, "%s: creating window for \"%s\" failed.\n",
			ME_SO, xc->classname);
		goto done_sowin;
	}

#if defined(WORKAROUND_XXXXXXX)
	window_list_remember(dpy, xc->sowin);
#endif /* WORKAROUND_XXXXXXX */

	XSelectInput(dpy, xc->sowin, PropertyChangeMask);

	aux->service->register_X_filter(dpy, xc->sowin,
			PropertyNotify, PropertyNotify,
			xaux_so_sowin_event_filter, (XPointer)NULL);

#if defined(WORKAROUND_XXXXXXX)
	event_filter_remember(dpy, xc->sowin,
			      xaux_so_sowin_event_filter, (XPointer)NULL);
#endif /* WORKAROUND_XXXXXXX */

	aux->service->register_X_filter(dpy, xc->sowin,
			SelectionClear, SelectionClear,
			xaux_so_sowin_event_filter, (XPointer)xc);

#if defined(WORKAROUND_XXXXXXX)
	event_filter_remember(dpy, xc->sowin,
			      xaux_so_sowin_event_filter, (XPointer)xc);
#endif /* WORKAROUND_XXXXXXX */

	XSetSelectionOwner(dpy, xc->atom_sowin, xc->sowin, CurrentTime);

	if (XGetSelectionOwner(dpy, xc->atom_sowin) != xc->sowin) {
		fprintf(stderr, "%s: %s already exists.[%s](2)\n",
			ME_SO, ME_SO, xc->classname);
		XDestroyWindow(dpy, xc->sowin);
#if defined(WORKAROUND_XXXXXXX)
		window_list_remember(dpy, xc->sowin);
#endif /* WORKAROUND_XXXXXXX */
		xc->sowin = (Window)0;
		goto done_sowin;
	}

#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] sowin created 0x%x\n", xc->shortname, xc->sowin);
#endif /* defined(DEBUG_XAUX) */

done_sowin:
	xc->extwin = (Window)0;

	return (True);
}

static Bool
xaux_so_Create(aux_t * aux)
{
	int		i;
	pid_t		pid;
	aux_icid_t *	aux_icid;

	if (so == NULL) {
		so = &so_;
		bzero((void *)so, sizeof (xaux_so_t));
		aux_icid_init();
	}

	if (NULL == (aux_icid = aux_icid_get(aux->service->ic_id(aux), True))) {
		return False;
	}

	aux_icid->aux = aux;
	aux_icid->imid = aux->service->im_id(aux);
	aux_icid->dpy = aux->service->display(aux);
	aux_icid->server = aux->service->server(aux);

#if defined(DEBUG_XAUX)
	fprintf(stderr, "[--] CREATE: im=0x%x ic=0x%x\n",
		aux->service->im_id(aux),
		aux->service->ic_id(aux));
#endif /* defined(DEBUG_XAUX) */

/* workaround for "stored reference to aux_t is corrupred" problem */
aux_tmp.ic = aux->ic;
aux_setvalue = aux_icid->aux->service->aux_setvalue;
mb_utf16 = aux_icid->aux->service->mb_utf16;
compose = aux_icid->aux->service->compose;
register_X_filter = aux_icid->aux->service->register_X_filter;
unregister_X_filter = aux_icid->aux->service->unregister_X_filter;

	if (so->classes == NULL) {
		xaux_so_init_classes_phase1(so, aux);
	}

	return (True);
}

static Bool
xaux_so_Start(aux_t * aux, const unsigned char * p, int size)
{
	aux_data_t *	aux_data;
	char		*propbuf;
	xaux_so_class_t *	xc;
	Bool		rv;
	aux_icid_t *	ic;

#if defined(WORKAROUND_XXXXXXX)
	if ((ic = aux_icid_get(aux->service->ic_id(aux), False)) == NULL) {
		xaux_so_Create(aux);
	}
#endif /* WORKAROUND_XXXXXXX */

	aux_data = aux->service->decompose(AUX_DATA_START, p);

	if ((ic = aux_icid_get(aux->service->ic_id(aux), False)) == NULL) {
		aux->service->decompose_free(aux_data);
#if defined(DEBUG_XAUX)
	fprintf(stderr, "[noinfo] START: unknown ic: 0x%x\n", ic);
#endif /* defined(DEBUG_XAUX) */
		return (False);
	}

	/* workaround for "stored reference to aux_t is corrupred" problem */
	aux_tmp.ic = aux->ic;

	if ((xc = xaux_getclass_byutfname(
		(const CARD16 *)aux_data->aux_name,
		aux_data->aux_name_length)) == NULL) {
		aux->service->decompose_free(aux_data);
		return (False);
	}

	if ((xc->atom_classname == (Atom)None) &&
			xaux_so_init_class_phase2(xc, aux) == False) {
		aux->service->decompose_free(aux_data);
		return (False);
	}

	if ((propbuf = (char *)malloc(SX_SIZE_HEADER)) == NULL) {
		aux->service->decompose_free(aux_data);
		return (False);
	}

#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] START: ic=0x%x\n", xc->shortname, ic);
	fprintf(stderr, "[%s] START: before launch extstate=%d\n",
		xc->shortname, xc->extstate);
#endif /* defined(DEBUG_XAUX) */

	xc->ic = ic;

	if ((xc->extstate == Initial) ||
		(xc->extstate == ErrorTemp) ||
		(xc->extstate == Disconnected)) {
		rv = xaux_so_launch_ext(xc, ic);
	}

#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] START: after launch extstate=%d\n",
		xc->shortname, xc->extstate);
#endif /* defined(DEBUG_XAUX) */

#if defined(NOTIFY_STATE)
	(void)xaux_so_notify_state(xc);
#endif /* defined(NOTIFY_STATE) */

	if ((xc->extstate != Connected) && (xc->extstate != Launched)) {
		aux->service->decompose_free(aux_data);
		return (False);
	}

	SX_PROTOVERS_MAJOR(propbuf) = XAUX_PROTOVERS_MAJOR;
	SX_PROTOVERS_MINOR(propbuf) = XAUX_PROTOVERS_MINOR;
	SX_SEQNO(propbuf) = sx_seqno++;
	SX_ATOM_AUX_NAME(propbuf) = xc->atom_classname;
	SX_INDEX(propbuf) = xc->index;
	SX_PRIVTYPE(propbuf) = (CARD8)XAUX_PRIVTYPE_PUBLIC;
	SX_AUXTYPE(propbuf) = (CARD8)AUX_DATA_START;
	SX_IMID(propbuf) = aux_data->im;
	SX_ICID(propbuf) = aux_data->ic;
	SX_MORESEGS(propbuf) = 1;
	SX_SEGNO(propbuf) = 0;
	SX_SEGSIZE(propbuf) = 0;

#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] START: im=0x%x ic=0x%x\n",
		xc->shortname, aux_data->im, aux_data->ic);
#endif /* defined(DEBUG_XAUX) */

	rv = xaux_so_send_property(aux, xc,
		(unsigned char *)propbuf, SX_SIZE_HEADER, True);

	aux->service->decompose_free(aux_data);

	return (rv);
}

static Bool
xaux_so_send_property_draw(
	aux_t		*aux,
	xaux_so_class_t	*xc,
	char		*prop)
{
	char		*draw = SX_DATA_TOP(prop);
	Bool		rv;
	Bool		detour;

#if defined(DEBUG_XAUX)
	if (BO_SEGNO(prop) == 0) {
		if (BO_DRAW_INT_COUNT(draw) > 0) {
			fprintf(stderr, "[%s] DRAW: im=0x%x ic=0x%x "
				"i[0]=0x%x in=%d sn=%d "
				"segno=%d segsize=0x%x\n",
				xc->shortname,
				BO_IMID(prop), BO_ICID(prop),
				*(BO_DRAW_INT_LIST(draw)),
				BO_DRAW_INT_COUNT(draw),
				BO_DRAW_STR_COUNT(draw),
				BO_SEGNO(prop), BO_SEGSIZE(prop));
		} else {
			fprintf(stderr, "[%s] DRAW: im=0x%x ic=0x%x "
				"in=%d sn=%d "
				"segno=%d segsize=0x%x\n",
				xc->shortname,
				BO_IMID(prop), BO_ICID(prop),
				BO_DRAW_INT_COUNT(draw),
				BO_DRAW_STR_COUNT(draw),
				BO_SEGNO(prop), BO_SEGSIZE(prop));
		}
	} else {
		fprintf(stderr, "[%s] DRAW: im=0x%x ic=0x%x "
				"segno=%d segsize=0x%x\n",
			xc->shortname,
			BO_IMID(prop), BO_ICID(prop),
			BO_SEGNO(prop), BO_SEGSIZE(prop));
	}
#endif /* defined(DEBUG_XAUX) */

	detour = aux->service->server(aux);

	rv = xaux_so_send_property(aux, xc, (unsigned char *)prop,
		SX_SIZE_HEADER + SX_SEGSIZE(prop),
		detour/* tentative */);

	return (True);
}

static Bool
xaux_so_Draw(aux_t * aux, const unsigned char * p, int size)
{
	aux_data_t *	aux_data;
	XPoint		point;
	char *		draw;
	xaux_so_class_t *	xc;
	size_t		i;
	int		*ip;
	char		*sp;
	Bool		rv = True;
	int		int_next;
	int		str_next;
	int		total_str_len;
	int		segno;
	char		*propbuf = NULL;
	char		*propbuftail = NULL;
	int		allocsz;

	aux_data = aux->service->decompose(AUX_DATA_DRAW, p);

	if ((xc = xaux_getclass_byutfname(
		(const CARD16 *)aux_data->aux_name,
		aux_data->aux_name_length)) == NULL) {
#if defined(DEBUG_XAUX)
	fprintf(stderr, "im: 0x%x ic:0x%x get faild in so_Draw[%s]\n",
			aux_data->im, aux_data->ic, xc->classname);
#endif /* defined(DEBUG_XAUX) */
		goto discard;
	}

	/* workaround for "stored reference to aux_t is corrupred" problem */
	aux_tmp.ic = aux->ic;

	if ((xc->atom_classname == (Atom)None) &&
			xaux_so_init_class_phase2(xc, aux) == False) {
		aux->service->decompose_free(aux_data);
		return (False);
	}

	if ((xc->extwin == (Window)None) && (aux->service->server(aux) == True)
			&& (xc->extstate != Launched)) {
		aux->service->decompose_free(aux_data);
		return (False);
	}

	for (i = 0, total_str_len = 0; i < aux_data->string_count; i++) {
		total_str_len += aux_data->string_list[i].length;
	}

	allocsz = SX_SIZE_HEADER + SX_SIZE_DRAW_HEADER		/* header */
		+ (sizeof (CARD32) * aux_data->integer_count)	/* int */
		+ total_str_len					/* str */
		+ (sizeof (CARD16) * aux_data->string_count)	/* strlen */
		+ (5 * aux_data->string_count);			/* pad + null */
	
	if (allocsz > maxpropsz) {
		allocsz = maxpropsz;
	}

	for (segno = 0; ; segno++) {
		if (segno > 0) {
			allocsz = maxpropsz;
		}
		if ((propbuf = (char *)malloc(allocsz)) == NULL) {
			goto discard;
		}
		propbuftail = propbuf + allocsz;
	
		SX_PROTOVERS_MAJOR(propbuf) = XAUX_PROTOVERS_MAJOR;
		SX_PROTOVERS_MINOR(propbuf) = XAUX_PROTOVERS_MINOR;
		SX_SEQNO(propbuf) = sx_seqno;
		SX_ATOM_AUX_NAME(propbuf) = xc->atom_classname;
		SX_INDEX(propbuf) = xc->index;
		SX_PRIVTYPE(propbuf) = (CARD8)XAUX_PRIVTYPE_PUBLIC;
		SX_AUXTYPE(propbuf) = (CARD8)AUX_DATA_DRAW;
		SX_IMID(propbuf) = aux_data->im;
		SX_ICID(propbuf) = aux_data->ic;
		SX_MORESEGS(propbuf) = 0;
		SX_SEGNO(propbuf) = segno;

		draw = SX_DATA_TOP(propbuf);

		if (segno == 0) {
			SX_DRAW_SOWIN(draw) = xc->sowin;
			SX_DRAW_CLIENTWIN(draw) =
				aux->service->client_window(aux);
			SX_DRAW_FOCUSWIN(draw) = aux->service->window(aux);
			aux->service->point(aux, &point);
			SX_DRAW_POSX(draw) = point.x;
			SX_DRAW_POSY(draw) = point.y;
			SX_DRAW_INT_COUNT(draw) = aux_data->integer_count;
			SX_DRAW_STR_COUNT(draw) = aux_data->string_count;
			SX_DRAW_TOTAL_STR_LEN(draw) = total_str_len;
			int_next = 0;
			str_next = 0;
			ip = (int *)SX_DRAW_INT_LIST(draw);
		} else {
			ip = (int *)draw;
		}

		for (i = int_next; i < aux_data->integer_count; i++) {
			if ((char *)(ip + 1) > propbuftail) {
				/* avoid to exceed tail of buffer */
				SX_MORESEGS(propbuf) = 1;
				SX_SEGSIZE(propbuf) = (char *)ip - draw;
				xaux_so_send_property_draw(aux, xc, propbuf);
#if defined(DEBUG_XAUX)
fprintf(stderr, "[%s] DRAW: sent up to integer[%d]\n", xc->shortname, i - 1);
#endif /* defined(DEBUG_XAUX) */
				int_next = i;
				break;
			}
			*ip++ = aux_data->integer_list[i];
		}

		if (i < aux_data->integer_count) {
			continue;
		}

		int_next = i;		/* no more int */
		sp = (char *)ip;	/* int array tail is str array head */

		for (i = str_next; i < aux_data->string_count; i++) {
			size_t		len;
			int		pn;
			unsigned char	*p;
			size_t		j;

			len = aux_data->string_list[i].length;
			p = aux_data->string_list[i].ptr;
			pn = padding[(sizeof (CARD16)
				+ len + sizeof (unsigned char) * 2) % 4];

			if ((sp + sizeof (CARD16) + len
					+ sizeof (unsigned char) * 2 + pn)
					> propbuftail) {
				/* avoid to exceed tail of buffer */
				if (i == str_next) {
					/* single string too long */
					goto discard;
				}
				SX_MORESEGS(propbuf) = 1;
				SX_SEGSIZE(propbuf) = sp - draw;
				xaux_so_send_property_draw(aux, xc, propbuf);
#if defined(DEBUG_XAUX)
fprintf(stderr, "[%s] DRAW: sent up to string[%d]\n", xc->shortname, i - 1);
#endif /* defined(DEBUG_XAUX) */
				str_next = i;
				break;
			} else {
				/* put length */
				*(CARD16 *)sp = len;
				sp += sizeof (CARD16);
				/* put string */
				for (j = 0; j < len; j++) {
					*sp++ = *p++;
				}
				/* put UTF-16 null for termination */
				*sp++ = 0U;
				*sp++ = 0U;
				/* put padding */
				for (j = 0; j < pn; j++) {
					*sp++ = 0U;
				}
			}
		}

		if (i < aux_data->string_count) {
			continue;
		}

		SX_MORESEGS(propbuf) = 0;
		SX_SEGSIZE(propbuf) = (int)(sp - draw);
		rv = xaux_so_send_property_draw(aux, xc, propbuf);
		break;
		/* NOTREACHED */
	}

discard:
	sx_seqno++;
	aux->service->decompose_free(aux_data);

	return (rv);
}

static Bool
xaux_so_Done(aux_t * aux, const unsigned char * p, int size)
{
	aux_data_t *	aux_data;
	char		*propbuf;
	xaux_so_class_t *	xc;
	Bool		rv;

	aux_data = aux->service->decompose(AUX_DATA_DONE, p);

	if ((xc = xaux_getclass_byutfname(
		(const CARD16 *)aux_data->aux_name,
		aux_data->aux_name_length)) == NULL) {
		aux->service->decompose_free(aux_data);
		return (False);
	}

	/* workaround for "stored reference to aux_t is corrupred" problem */
	aux_tmp.ic = aux->ic;

	if ((xc->atom_classname == (Atom)None) &&
			xaux_so_init_class_phase2(xc, aux) == False) {
		aux->service->decompose_free(aux_data);
		return (False);
	}

	if ((propbuf = (char *)malloc(SX_SIZE_HEADER)) == NULL) {
		aux->service->decompose_free(aux_data);
		return (False);
	}

	SX_PROTOVERS_MAJOR(propbuf) = XAUX_PROTOVERS_MAJOR;
	SX_PROTOVERS_MINOR(propbuf) = XAUX_PROTOVERS_MINOR;
	SX_SEQNO(propbuf) = sx_seqno++;
	SX_ATOM_AUX_NAME(propbuf) = xc->atom_classname;
	SX_INDEX(propbuf) = xc->index;
	SX_PRIVTYPE(propbuf) = (CARD8)XAUX_PRIVTYPE_PUBLIC;
	SX_AUXTYPE(propbuf) = (CARD8)AUX_DATA_DONE;
	SX_IMID(propbuf) = aux_data->im;
	SX_ICID(propbuf) = aux_data->ic;
	SX_MORESEGS(propbuf) = 0;
	SX_SEGNO(propbuf) = 0;
	SX_SEGSIZE(propbuf) = 0;

#if defined(DEBUG_XAUX)
	fprintf(stderr, "[%s] DONE: im=0x%x ic=0x%x\n",
		xc->shortname, aux_data->im, aux_data->ic);
#endif /* defined(DEBUG_XAUX) */

	rv = xaux_so_send_property(aux, xc,
		(unsigned char *)propbuf, SX_SIZE_HEADER,
		True /* tentative */);

	aux->service->decompose_free(aux_data);

	xc->ic = NULL;

	return (rv);
}

static Bool
xaux_so_Switched(aux_t * aux, int im_id, int on_off)
{
	return True;
}

static Bool
xaux_so_Destroy(aux_t * aux)
{
	Display *		dpy;
	xaux_so_class_t *	p;

#if defined(WORKAROUND_XXXXXXX)
	if (NULL == aux) {
		event_filter_unregister_all();
		window_list_destroy_all();
		return True;
	}
#endif /* WORKAROUND_XXXXXXX */

	dpy = aux->service->display(aux);

	for (p = xaux_classes; NULL != p->classname; p++) {
		if (None != p->sowin) {
			unregister_X_filter(dpy, p->sowin,
					    xaux_so_sowin_event_filter, NULL);
			XDestroyWindow(dpy, p->sowin);
		}
		if (None != p->extwin) {
			unregister_X_filter(dpy, p->extwin,
					    xaux_so_extwin_event_filter, NULL);
		}
	}

	return True;
}

static Bool VersionQueryAux_Start(aux_t *, const unsigned char *, int size);
static Bool VersionQueryAux_Draw(aux_t *, const unsigned char *, int size);
static Bool VersionQueryAux_Done(aux_t *, const unsigned char *, int size);

aux_method_t VersionQueryAux_methods = {
	xaux_so_Create,
	VersionQueryAux_Start,
	VersionQueryAux_Draw,
	VersionQueryAux_Done,
	xaux_so_Switched,
	xaux_so_Destroy
};

#define	VERSION_TAG	"(#)IM for Solaris"

static Bool
VersionQueryAux_elf_tryaline(
	char *	line,
	int *	pmajor,
	int *	pminor)
{
	char	*p;
	long	longval;
	char	*endptr;

	*pmajor = -1;
	*pminor = -1;

	if ((p = strstr(line, VERSION_TAG)) != NULL) {
		p += strlen(VERSION_TAG);

		/* search "/" */
		if ((p = strchr(p, '/')) == NULL) {
			goto failed;
		} else {
			p++;
		}

		/* get version major */
#if defined(DEBUG_XAUX_DETAIL)
		fprintf(stderr, "trying to get version major at:\"%s\"\n", p);
#endif /* defined(DEBUG_XAUX_DETAIL) */
		errno = 0;
		longval = strtol(p, &endptr, 10);
		if (errno != 0) {
			goto failed;
		} else {
			*pmajor = longval;
		}
		if ((endptr == NULL) || ((p = endptr + 1) == '\0')) {
			goto failed;
		}

		/* get version minor */
#if defined(DEBUG_XAUX_DETAIL)
		fprintf(stderr, "trying to get version minor at:\"%s\"\n", p);
#endif /* defined(DEBUG_XAUX_DETAIL) */
		errno = 0;
		longval = strtol(p, &endptr, 10);
		if ((errno != 0) || p == endptr) {
			goto failed;
		} else {
			*pminor = longval;
		}
#if defined(DEBUG_XAUX)
		fprintf(stderr, "major=%d minor=%d\n", *pmajor, *pminor);
#endif /* defined(DEBUG_XAUX) */
failed:
		return (False); /* not read lines further */
	} else {
		return (True); /* read lines further */
	}
}

static Bool
VersionQueryAux_elf(
	const char *	filename,
	int		*pmajor,
	int		*pminor)
{
#if !defined(linux)
	Elf *		elf;
	Elf_Scn	*	scn = NULL;
	GElf_Shdr	shdr;
	GElf_Ehdr	ehdr;
	Elf_Data *	data;
	int		fd;
	int		c;
	int		cc;
	char *		p;
	Elf_Data *	cdata;
	Bool		terminated = False;

	elf_version(EV_CURRENT);

	if ((fd = open(filename, O_RDONLY)) == -1) {
#if defined(DEBUG_XAUX_DETAIL)
		fprintf(stderr, "cannot open: %s\n", filename);
#endif /* defined(DEBUG_XAUX_DETAIL) */
		return (False);
	}

	elf = elf_begin(fd, ELF_C_READ, NULL);

	/* get ELF header */
	if (gelf_getehdr(elf, &ehdr) == NULL) {
		perror("gelf_getehdr");
		goto failed;
	}

	/* get data of section which holds section name strings */
	if (((scn = elf_getscn(elf, ehdr.e_shstrndx)) == NULL) ||
			((data = elf_getdata(scn, NULL)) == NULL)) {
		goto failed;
	}

	for (scn = NULL; (scn = elf_nextscn(elf, scn)) != NULL; ) {
		if (gelf_getshdr(scn, &shdr) == NULL) {
			perror("gelf_getshdr");
			goto failed;
		}
#if defined(DEBUG_XAUX_DETAIL)
		fprintf(stderr, "skipping section: %s\n",
			(char *)data->d_buf + shdr.sh_name);
#endif /* defined(DEBUG_XAUX_DETAIL) */
		if (strcmp(".comment", (char *)data->d_buf + shdr.sh_name)
				== 0) {
			cdata = elf_getdata(scn, NULL);
			p = (char *)(cdata->d_buf);
			c = 1;
			while (c < shdr.sh_size) {
				terminated = False;
				for (cc = c; cc < shdr.sh_size; cc++) {
					if (*(p + cc) == '\0') {
						terminated = True;
					}
				}
				if (terminated == True) {
					if (VersionQueryAux_elf_tryaline(
							p + c, pmajor, pminor)
							== False) {
						break;
					}
				} else {
		fprintf(stderr, "binary file may be corrupted: %s\n",
			filename);
					goto failed;
				}
				c += (strlen(p + c) + 1);
			}
			if ((*pmajor != -1) && (*pminor != -1)) {
				goto succeeded;
			}
		}
	}

failed:
	elf_end(elf);
	close(fd);
	fprintf(stderr, "cannot get version information from \"%s\"\n",
		filename);
	return (False);

succeeded:
	elf_end(elf);
	close(fd);
#endif /* !linux */
	return (True);
}

static Bool
VersionQueryAux_get_extversion(
	xaux_so_class_t *	xc,
	int *		major,
	int *		minor)
{
	char		path[MAXPATHLEN];

	/*
	 * tentaive hardcoded logic
	 * return major=1 minor=1 in case of either:
	 *	- VersionQueryAux
	 * 	- other classes and xaux1() check returned true
	 * otherwise, return default version.
	 */
	if (strcmp(xc->classname,
		"com.sun.sampleja4.VersionQueryAux") == 0) {
			*major = 1;
			*minor = 2;
	} else {
		if (xaux_so_check_xaux1() == True) {
			snprintf(path, MAXPATHLEN, "%s%d/%s",
				xaux_so_extexec_path, 1, xc->extexec);
		} else {
			snprintf(path, MAXPATHLEN, "%s/%s",
				xaux_so_extexec_path, xc->extexec);
		}

		if (VersionQueryAux_elf(path, major, minor) == True) {
#if defined(DEBUG_XAUX)
		fprintf(stderr, "[Vers] \"%s\" major=%d minor=%d (from ELF)\n",
			xc->shortname, *major, *minor);
#endif /* defined(DEBUG_XAUX) */
		} else if (access(path, X_OK) == 0) {
			*major = xaux_so_default_extversion[0];
			*minor = xaux_so_default_extversion[1];
#if defined(DEBUG_XAUX)
		fprintf(stderr, "[Vers] \"%s\" major=%d minor=%d (default)\n",
			xc->shortname, *major, *minor);
#endif /* defined(DEBUG_XAUX) */
		} else {
			*major = XAUX_EXTVERS_MAJOR_NOTAVAIL;
			*minor = XAUX_EXTVERS_MINOR_NOTAVAIL;
#if defined(DEBUG_XAUX)
		fprintf(stderr, "[Vers] \"%s\" major=%d minor=%d (notavail)\n",
			xc->shortname, *major, *minor);
#endif /* defined(DEBUG_XAUX) */
		}
	}

	return (True);
}

static Bool
VersionQueryAux_send_extversion(
	xaux_so_class_t *	xc_vq,
	aux_data_t *	aux_data_vq,
	int		server)
{
	int		major = 0;
	int		minor = 0;
	int		size;
	aux_data_t	aux_data_;
	aux_data_t *	aux_data = &(aux_data_);
	xaux_so_class_t	*xc = xaux_classes;
	int		nclasses = 0;
	int		ni;
	int		ns;
	unsigned char *	p;

	for (xc = xaux_classes, nclasses = 0; xc->classname != NULL; xc++) {
			nclasses++;
	}

	aux_data->type = AUX_DATA_SETVALUE;
	aux_data->im = aux_data_vq->im;
	aux_data->ic = aux_data_vq->ic;
	aux_data->aux_index = xc_vq->index;
	aux_data->aux_name = (unsigned char *)xc_vq->utfname;
	aux_data->aux_name_length = strlen(xc_vq->classname) * sizeof(CARD16);

	aux_data->integer_count = (2 + (nclasses * 2) + 1);
	aux_data->integer_list =
		(int *)malloc(sizeof (int) * aux_data->integer_count);
	
	if (aux_data->integer_list == NULL) {
		return False;
	}

	aux_data->string_count = nclasses;
	aux_data->string_list = (aux_string_t *)
		malloc(sizeof (aux_string_t) * aux_data->string_count);

	if (aux_data->string_list == NULL) {
		free(aux_data->integer_list);
		return False;
	}

	ni = 0;

	aux_data->integer_list[ni] = 1;
#if defined(DEBUG_XAUX)
	fprintf(stderr, "int[%d]=%d\n", ni, aux_data->integer_list[ni]);
#endif /* defined(DEBUG_XAUX) */
	ni++;

	aux_data->integer_list[ni] = nclasses;
#if defined(DEBUG_XAUX)
	fprintf(stderr, "int[%d]=%d\n", ni, aux_data->integer_list[ni]);
#endif /* defined(DEBUG_XAUX) */
	ni++;

	ns = 0;

	for (xc = xaux_classes, nclasses = 0; xc->classname != NULL; xc++) {
		int	major = 0;
		int	minor = 0;

		VersionQueryAux_get_extversion(xc, &major, &minor);

		aux_data->integer_list[ni] = major;
#if defined(DEBUG_XAUX)
		fprintf(stderr, "int[%d]=%d\n", ni, aux_data->integer_list[ni]);
#endif /* defined(DEBUG_XAUX) */
		ni++;

		aux_data->integer_list[ni] = minor;
#if defined(DEBUG_XAUX)
		fprintf(stderr, "int[%d]=%d\n", ni, aux_data->integer_list[ni]);
#endif /* defined(DEBUG_XAUX) */
		ni++;

		aux_data->string_list[ns].length =
			strlen(xc->classname) * sizeof (CARD16);
		aux_data->string_list[ns].ptr = (unsigned char *)(xc->utfname);
#if defined(DEBUG_XAUX)
{
	int	i;

	fprintf(stderr, "str[%d]=\"", ns);
	for (i = 0; i < aux_data->string_list[ns].length; i++) {
		if (aux_data->string_list[ns].ptr[i] == '\0') {
			fprintf(stderr, "\\0");
		} else {
			fprintf(stderr, "%c", aux_data->string_list[ns].ptr[i]);
		}
	}
	fprintf(stderr, "\"\n");
}
#endif /* defined(DEBUG_XAUX) */
		ns++;
	}

	aux_data->integer_list[ni] = server;
	ni++;

	aux_data->string_ptr = NULL;

	/* compose and send message to engine */

/* workaround for "stored reference to aux_t is corrupred" problem */
#if	!defined(DONT_SEND_VERSION)
	if ((p = /*ic->aux->service->*/compose(aux_data, &size)) == NULL) {
		return False;
	}
#endif	/* !DONT_SEND_VERSION */

#if defined(DEBUG_XAUX)
	fprintf(stderr, "so_SetValue[VersionQueryAux]"
		" im:0x%x ic:0x%x ic=%d sc=%d id=%d nclasses=%d\n",
		aux_data->im, aux_data->ic,
		aux_data->integer_count,
		aux_data->string_count,
		aux_data->integer_list[0],
		aux_data->integer_list[1]);
#endif /* defined(DEBUG_XAUX) */

/* workaround for "stored reference to aux_t is corrupred" problem */
#if	!defined(DONT_SEND_VERSION)
	/*ic->aux->service->*/aux_setvalue(/*ic->aux*/&aux_tmp, p, size);
#endif	/* !DONT_SEND_VERSION */

	free(aux_data->integer_list);
	free(aux_data->string_list);

	return True;
}

static Bool
VersionQueryAux_Start(aux_t * aux, const unsigned char * p, int size)
{
	aux_data_t *	aux_data;
	xaux_so_class_t *	xc;
	Bool		rv = True;

	aux_data = aux->service->decompose(AUX_DATA_START, p);

	if ((xc = xaux_getclass_byutfname(
		(const CARD16 *)aux_data->aux_name,
		aux_data->aux_name_length)) == NULL) {
		aux->service->decompose_free(aux_data);
		return False;
	}

	VersionQueryAux_send_extversion(
		xc, aux_data, (False == aux->service->server(aux)) ? 0 : 1);

#if defined(DEBUG_XAUX)
	fprintf(stderr, "so_Start[VersionQueryAux] im:0x%x ic:0x%x\n",
		aux_data->im, aux_data->ic);
#endif /* defined(DEBUG_XAUX) */

	aux->service->decompose_free(aux_data);

	return (rv);
}

static Bool
VersionQueryAux_Draw(aux_t * aux, const unsigned char * p, int size)
{
#if defined(DEBUG_XAUX)
	fprintf(stderr, "so_Draw[VersionQueryAux]\n");
#endif /* defined(DEBUG_XAUX) */

	return True;
}

static Bool
VersionQueryAux_Done(aux_t * aux, const unsigned char * p, int size)
{
#if defined(DEBUG_XAUX)
	fprintf(stderr, "so_Done[VersionQueryAux]\n");
#endif /* defined(DEBUG_XAUX) */

	return True;
}
