示例#1
0
/*************
 * FUNCTION:		SendRexxMsg
 * VERSION:			0.1 08.03.1995
 * DESCRIPTION:	Sends a single (or a list of) command(s) to Rexx host
 *						and returns the secondary result
 * INPUT:			HostName			name of host
 *						MsgList			messagelist (SingleMsg must be NULL)
 *						SingleMsg		single message (MsgList must be NULL)
 *						GetResult		TRUE: get results
 * OUTPUT:			secondary result
 * HISTORY:       DATE		NAME		COMMENT
 *						08.03.95	ah			first release
 *************/
ULONG SendRexxMsg(STRPTR HostName,STRPTR *MsgList,STRPTR SingleMsg,LONG GetResult)
{
	struct RexxMsg *RexxMessage;
	struct MsgPort *HostPort,*ReplyPort;
	ULONG Result = 0;
	SHORT i;

	/* Valid pointers given? */
	if(HostName && (MsgList || SingleMsg))
	{
		/* Can we find the host? */
		HostPort = (struct MsgPort *)FindPort((char *)HostName);
		if(HostPort)
		{
			/* Allocate a reply port. */
			ReplyPort = (struct MsgPort *)AllocMem(sizeof(struct MsgPort),MEMF_PUBLIC | MEMF_CLEAR);
			if(ReplyPort)
			{
				ReplyPort->mp_SigBit = AllocSignal(-1);
				if(ReplyPort->mp_SigBit != -1)
				{
					ReplyPort->mp_Node.ln_Type	= NT_MSGPORT;
					ReplyPort->mp_Flags			= PA_SIGNAL;
					ReplyPort->mp_SigTask		= FindTask(NULL);

					ReplyPort->mp_MsgList.lh_Head = (struct Node *)&ReplyPort->mp_MsgList.lh_Tail;
					ReplyPort->mp_MsgList.lh_Tail = 0;
					ReplyPort->mp_MsgList.lh_TailPred = (struct Node *)&ReplyPort->mp_MsgList.lh_Head;

					/* Create a Rexx message. */
					RexxMessage = (struct RexxMsg *)CreateRexxMsg(ReplyPort,"",(char *)HostName);
					if(RexxMessage)
					{
						/* A list of arguments or only a single arg? */
						if(MsgList)
						{
							for(i=0 ; i<16 ; i++)
								RexxMessage->rm_Args[i] = MsgList[i];
						}
						else
							RexxMessage->rm_Args[0] = SingleMsg;

						/* Do we want result codes? */
						if(GetResult)
							RexxMessage->rm_Action = RXFF_RESULT;

						/* Send packet and wait for the reply. */
						PutMsg(HostPort,(struct Message *)RexxMessage);
						WaitPort(ReplyPort);

						/* Remember result. */
						if(GetResult && !RexxMessage->rm_Result1)
							Result = RexxMessage->rm_Result2;

						/* Remove Rexx message. */
						DeleteRexxMsg(RexxMessage);
					}
					/* Free reply port signal bit. */
					FreeSignal(ReplyPort->mp_SigBit);
				}
				/* Free the replyport itself. */
				FreeMem(ReplyPort,sizeof(struct MsgPort));
			}
		}
	}
	/* Return the result. */
	return(Result);
}
示例#2
0
/*
 * Load a DLL.  Returns NULL on failure.
 */
void *InitDllTool( int whichtool, const DllToolCallbacks *callbacks )
/*******************************************************************/
{
    DllTool *           tool = AllocMem( sizeof( DllTool ) );
    unsigned            dllversion;
    IDECallBacks *      dllcallbacks;

    /*** Load the DLL ***/
    switch( whichtool ) {
      case DLLTOOL_WLIB:
        tool->dllhandle = LoadLibrary( WLIB_DLL_FILENAME );
        break;
      default:
        Zoinks();
    };
    if( tool->dllhandle == NULL ) {
        return( NULL );
    }

    /*** Grab the entry points ***/
    tool->getversion = (GetVerFn)GetProcAddress( tool->dllhandle, DLL_GETVER );
    tool->initdll = (InitDllFn)GetProcAddress( tool->dllhandle, DLL_INITDLL );
    tool->initinfo = (InitInfoFn)GetProcAddress( tool->dllhandle, DLL_INITINFO );
    tool->runyourself = (RunSelfFn)GetProcAddress( tool->dllhandle, DLL_RUNSELF );
    tool->finidll = (FiniDllFn)GetProcAddress( tool->dllhandle, DLL_FINIDLL );
    tool->stoprunning = (StopRunFn)GetProcAddress( tool->dllhandle, DLL_STOPRUN );
    if( tool->getversion == NULL  ||  tool->initdll == NULL  ||
        tool->runyourself == NULL  || tool->finidll == NULL  ||
        tool->stoprunning == NULL ) {
        FreeLibrary( tool->dllhandle );
        return( NULL );
    }

    /*** Set up the callbacks ***/
    dllversion = tool->getversion();
    if( dllversion == 1 ) {
        memset( &tool->callbacks_ver1, 0, sizeof( IDECallBacks1 ) );
        if( callbacks->printmessage != NULL ) {
            tool->callbacks_ver1.PrintMessage = callbacks->printmessage;
        } else {
            tool->callbacks_ver1.PrintMessage = print_message;
        }
        if( callbacks->printmessageCRLF != NULL ) {
            tool->callbacks_ver1.PrintWithCRLF = callbacks->printmessageCRLF;
        } else {
            tool->callbacks_ver1.PrintWithCRLF = print_message_crlf;
        }
        tool->callbacks_ver1.GetInfo = NULL;
        tool->callbacks_ver1.RunBatch = NULL;
        dllcallbacks = (IDECallBacks*) &tool->callbacks_ver1;
    } else if( dllversion > 1 ) {
        memset( &tool->callbacks, 0, sizeof( IDECallBacks ) );
        if( callbacks->printmessage != NULL ) {
            tool->callbacks.PrintMessage = callbacks->printmessage;
        } else {
            tool->callbacks.PrintMessage = print_message;
        }
        if( callbacks->printmessageCRLF != NULL ) {
            tool->callbacks.PrintWithCRLF = callbacks->printmessageCRLF;
        } else {
            tool->callbacks.PrintWithCRLF = print_message_crlf;
        }
        if( dllversion == 2 ) {
            if( callbacks->printwithinfo != NULL ) {
                tool->callbacks.PrintWithInfo = (IDEMsgInfoFn)callbacks->printwithinfo2;
            } else {
                tool->callbacks.PrintWithInfo = (IDEMsgInfoFn)print_with_info2;
            }
        } else {                        /* dllversion >= 3 */
            if( callbacks->printwithinfo != NULL ) {
                tool->callbacks.PrintWithInfo = callbacks->printwithinfo;
            } else {
                tool->callbacks.PrintWithInfo = print_with_info;
            }
        }
        tool->callbacks.GetInfo = NULL;
        tool->callbacks.RunBatch = NULL;
        tool->callbacks.ProgressMessage = NULL;
        dllcallbacks = &tool->callbacks;
    } else {
        FreeLibrary( tool->dllhandle );
        return( NULL );
    }

    /*** Tell the DLL to initialize itself ***/
    if( tool->initdll( (IDECBHdl)callbacks->cookie, dllcallbacks, &tool->dllHdl ) ) {
        FreeLibrary( tool->dllhandle );
        return( NULL );
    }
    if( tool->initinfo != NULL ) {
        memset( &tool->initdata, 0, sizeof( tool->initdata ) );
        tool->initdata.ver = IDE_CUR_INFO_VER;
        tool->initdata.ignore_env = 1;
        tool->initdata.cmd_line_has_files = 1;
        tool->initinfo( tool->dllHdl, &tool->initdata );
    }

    return( (void*)tool );
}
示例#3
0
文件: common.c 项目: cosmos72/twin
static byte X11_InitHW(void) {
    char *arg = HW->Name;
    int xscreen;
    unsigned int xdepth;
    XSetWindowAttributes xattr;
    XColor xcolor;
    XSizeHints *xhints;
    XEvent event;
    Visual *xvisual;
    Colormap colormap;
    byte *s, *xdisplay_ = NULL, *xdisplay0 = NULL,
        *fontname = NULL, *fontname0 = NULL,
        *charset = NULL, *charset0 = NULL,
        title[X11_TITLE_MAXLEN];
    int i, nskip;
    udat fontwidth = 8, fontheight = 16;
    byte drag = tfalse, noinput = tfalse;
    unsigned long xcreategc_mask = GCForeground|GCBackground|GCGraphicsExposures;
    
    if (!(HW->Private = (struct x11_data *)AllocMem(sizeof(struct x11_data)))) {
	printk("      X11_InitHW(): Out of memory!\n");
	return tfalse;
    }
    WriteMem(HW->Private, 0, sizeof(struct x11_data));

    /* default: show the whole screen */
    xhw_view = xhw_startx = xhw_starty = xhw_endx = xhw_endy = 0;

    /* not yet opened */
    xdisplay = NULL;
    
    if (arg && *arg && ((nskip = check_hw_name(arg)) > 0)) {
        arg += nskip;

	if (*arg == '@') {
	    if ((s = strchr(xdisplay_ = ++arg, ','))) {
		*(xdisplay0 = s) = '\0';
		arg = s + 1;
	    } else
		arg = NULL;
	}

	while (arg && *arg) {
	    /* parse options */
	    if (*arg == ',') {
		arg++;
		continue;
	    }
	    if (!strncmp(arg, "font=", 5)) {
		fontname = arg += 5;
		s = strchr(arg, ',');
		if (s) *(fontname0 = s++) = '\0';
		arg = s;
            } else if (!strncmp(arg, "fontsize=", 9)) {
                int n1 = atoi(arg += 9), n2 = 0;
                byte ch;
                if (n1 > 0) {
                    while ((ch = (byte)*++arg) && ch != ',') {
                        if (ch == 'x') {
                            n2 = atoi(arg+1);
                            break;
                        }
                    }
                    fontwidth  = Min2(TW_MAXUDAT, n2 > 0 ? n1 : n1 / 2);
                    fontheight = Min2(TW_MAXUDAT, n2 > 0 ? n2 : n1);
                }
	    } else if (!strncmp(arg, "charset=", 8)) {
		charset = arg += 8;
		s = strchr(arg, ',');
		if (s) *(charset0 = s++) = '\0';
		arg = s;
	    } else if (!strncmp(arg, "view=", 5)) {
		xhw_view = 1;
		xhw_endx = strtol(arg+5, &arg, 0);
		xhw_endy = strtol(arg+1, &arg, 0);
		xhw_startx = strtol(arg+1, &arg, 0);
		xhw_starty = strtol(arg+1, &arg, 0);
		xhw_endx += xhw_startx;
		xhw_endy += xhw_starty;
	    } else if (!strncmp(arg, "drag", 4)) {
		arg += 4;
		drag = ttrue;
	    } else if (!strncmp(arg, "noinput", 7)) {
		arg += 7;
		noinput = ttrue;
	    } else
		arg = strchr(arg, ',');
	}
    }

    xsfont = NULL; xhints = NULL;
    xwindow = None; xgc = None;
    xReqCount = XReqCount = 0;
    HW->keyboard_slot = NOSLOT;
    
    if ((xdisplay = XOpenDisplay(xdisplay_))) do {
	
	(void)XSetIOErrorHandler(X11_Die);

	if (!X11_CheckRemapKeys())
	    break;

	xscreen = DefaultScreen(xdisplay);
	xdepth  = DefaultDepth(xdisplay, xscreen);
        xvisual = DefaultVisual(xdisplay, xscreen);
        colormap = DefaultColormap(xdisplay, xscreen);
	
	for (i = 0; i <= MAXCOL; i++) {
	    xcolor.red   = 257 * (udat)Palette[i].Red;
	    xcolor.green = 257 * (udat)Palette[i].Green;
	    xcolor.blue  = 257 * (udat)Palette[i].Blue;
            if (!X11_AllocColor(xdisplay, xvisual, colormap, &xcolor, &xcol[i], i)) {
                printk("      X11_InitHW() failed to allocate colors\n");
                break;
            }
	}
	if (i <= MAXCOL)
	    break;
	
	xattr.background_pixel = xcol[0];
	xattr.event_mask = ExposureMask | VisibilityChangeMask |
	    StructureNotifyMask | SubstructureNotifyMask |
	    KeyPressMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask;

	if (!X11_LoadFont(fontname, fontwidth, fontheight))
	    break;
	
	if (xhw_view && xhw_startx >= 0 && xhw_starty >= 0 && xhw_endx > xhw_startx && xhw_endy > xhw_starty) {
	    /* a valid view was specified */
	    
	    xwidth  = xwfont * (ldat)(xhw_endx - xhw_startx);
	    xheight = xhfont * (ldat)(xhw_endy - xhw_starty);
	} else {
	    xhw_view = xhw_startx = xhw_starty = 0;
	    xhw_endx = HW->X;
	    xhw_endy = HW->Y;
	}
	
	if ((xwindow = XCreateWindow(xdisplay, DefaultRootWindow(xdisplay), 0, 0,
				     xwidth, xheight, 0, xdepth, InputOutput,
				     xvisual, CWBackPixel | CWEventMask, &xattr)) &&

	    (xsgc.foreground = xsgc.background = xcol[0],
	     xsgc.graphics_exposures = False,
#if HW_X_DRIVER == HW_X11
	     xsgc.font = xsfont->fid,
             xcreategc_mask = xcreategc_mask|GCFont,
#elif HW_X_DRIVER == HW_XFT
             xforeground = xbackground = xftcolors[0],
#endif
	     xgc = XCreateGC(xdisplay, xwindow, xcreategc_mask, &xsgc)) &&

	    (xhints = XAllocSizeHints()))
        {
	    
            static XComposeStatus static_xcompose;
            xcompose = static_xcompose;

#if HW_X_DRIVER == HW_XFT
            xftdraw = XftDrawCreate(xdisplay,xwindow,xvisual,colormap);
#endif

#ifdef TW_FEATURE_X11_XIM_XIC
            xim = XOpenIM(xdisplay, NULL, NULL, NULL);
            if (xim != NULL) {
                xic = XCreateIC(xim, XNInputStyle, XIMStatusNothing|XIMPreeditNothing,
                                XNClientWindow, xwindow, XNFocusWindow, xwindow, NULL);
                if (xic == NULL) {
                    XCloseIM(xim);
                    xim = NULL;
                }
            } else
                xic = NULL;
#endif
            X11_FillWindowTitle(title, sizeof(title));
	    XStoreName(xdisplay, xwindow, title);


	    if (!(xUTF_32_to_charset = X11_UTF_32_to_charset_function(charset)))
		xUTF_32_to_charset = X11_UTF_32_to_UCS_2;
	    /*
	     * ask ICCCM-compliant window manager to tell us when close window
	     * has been chosen, rather than just killing us
	     */
	    xWM_PROTOCOLS = XInternAtom(xdisplay, "WM_PROTOCOLS", False);
	    xWM_DELETE_WINDOW = XInternAtom(xdisplay, "WM_DELETE_WINDOW", False);
	    xTARGETS = XInternAtom(xdisplay, "TARGETS", False);

	    XChangeProperty(xdisplay, xwindow, xWM_PROTOCOLS, XA_ATOM, 32, PropModeReplace,
			    (unsigned char *) &xWM_DELETE_WINDOW, 1);

	    if (xhw_view) {
		xhints->flags = PMinSize|PMaxSize;
		xhints->min_width = xhints->max_width = xwidth;
		xhints->min_height = xhints->max_height = xheight;
	    } else {
		xhints->flags = PResizeInc;
		xhints->width_inc  = xwfont;
		xhints->height_inc = xhfont;
	    }
	    XSetWMNormalHints(xdisplay, xwindow, xhints);
	    
	    XMapWindow(xdisplay, xwindow);
	    
	    do {
		XNextEvent(xdisplay, &event);
	    } while (event.type != MapNotify);
	    
	    XFree(xhints); xhints = NULL;
	    
	    HW->mouse_slot = NOSLOT;
	    HW->keyboard_slot = RegisterRemote(i = XConnectionNumber(xdisplay), (obj)HW,
					       X11_KeyboardEvent);
	    if (HW->keyboard_slot == NOSLOT)
		break;
	    fcntl(i, F_SETFD, FD_CLOEXEC);
	    
	    HW->FlushVideo = X11_FlushVideo;
	    HW->FlushHW = X11_FlushHW;
	    
	    HW->KeyboardEvent = X11_KeyboardEvent;
	    HW->MouseEvent = (void *)NoOp; /* mouse events handled by X11_KeyboardEvent */
	    
	    HW->XY[0] = HW->XY[1] = 0;
	    HW->TT = NOCURSOR;
	    
	    HW->ShowMouse = NoOp;
	    HW->HideMouse = NoOp;
	    HW->UpdateMouseAndCursor = NoOp;
	    HW->MouseState.x = HW->MouseState.y = HW->MouseState.keys = 0;
	    
	    HW->DetectSize  = X11_DetectSize;
	    HW->CheckResize = X11_CheckResize;
	    HW->Resize      = X11_Resize;
	    
	    HW->HWSelectionImport  = X11_SelectionImport_X11;
	    HW->HWSelectionExport  = X11_SelectionExport_X11;
	    HW->HWSelectionRequest = X11_SelectionRequest_X11;
	    HW->HWSelectionNotify  = X11_SelectionNotify_X11;
	    HW->HWSelectionPrivate = 0;
	    
	    if (drag) {
		HW->CanDragArea = X11_CanDragArea;
		HW->DragArea    = X11_DragArea;
	    } else
		HW->CanDragArea = NULL;
	    
	    HW->Beep = X11_Beep;
	    HW->Configure = X11_Configure;
	    HW->SetPalette = (void *)NoOp;
	    HW->ResetPalette = NoOp;
	    
	    HW->QuitHW = X11_QuitHW;
	    HW->QuitKeyboard  = NoOp;
	    HW->QuitMouse = NoOp;
	    HW->QuitVideo = NoOp;
	    
	    HW->DisplayIsCTTY = tfalse;
	    HW->FlagsHW &= ~FlHWSoftMouse; /* mouse pointer handled by X11 server */
	    
	    HW->FlagsHW |= FlHWNeedOldVideo;
	    HW->FlagsHW |= FlHWExpensiveFlushVideo;
	    if (noinput)
		HW->FlagsHW |= FlHWNoInput;
	    
	    HW->NeedHW = 0;
	    HW->CanResize = ttrue;
	    HW->merge_Threshold = 0;
	    
	    /*
	     * we must draw everything on our new shiny window
	     * without forcing all other displays
	     * to redraw everything too.
	     */
	    HW->RedrawVideo = tfalse;
	    NeedRedrawVideo(0, 0, HW->X - 1, HW->Y - 1);
	    
	    if (xdisplay0) *xdisplay0 = ',';
	    if (fontname0) *fontname0 = ',';
	    if (charset0) *charset0 = ',';
	    
	    return ttrue;
	}
    } while (0); else {
	if (xdisplay_ || (xdisplay_ = getenv("DISPLAY")))
	    printk("      X11_InitHW() failed to open display %."STR(TW_SMALLBUFF)"s\n", HW->Name);
	else
	    printk("      X11_InitHW() failed: DISPLAY is not set\n");
    }

fail:
    if (xdisplay0) *xdisplay0 = ',';
    if (fontname0) *fontname0 = ',';
    if (charset0) *charset0 = ',';
	
    if (xdisplay)
	X11_QuitHW();

    FreeMem(HW->Private);
    HW->Private = NULL;
    
    return tfalse;
}
示例#4
0
/*
================
CutNodePortals_r
================
*/
static void
CutNodePortals_r(node_t *node)
{
    plane_t *plane, clipplane;
    node_t *f, *b, *other_node;
    portal_t *p, *new_portal, *next_portal;
    winding_t *w, *frontwinding, *backwinding;
    int side;

#ifdef PARANOID
    CheckLeafPortalConsistancy (node);
#endif

    // separate the portals on node into it's children
    if (node->contents)
	return;			// at a leaf, no more dividing

    plane = &pPlanes[node->planenum];

    f = node->children[0];
    b = node->children[1];

    // create the new portal by taking the full plane winding for the cutting plane
    // and clipping it by all of the planes from the other portals
    new_portal = AllocMem(PORTAL, 1, true);
    new_portal->planenum = node->planenum;

    w = BaseWindingForPlane(&pPlanes[node->planenum]);
    side = 0;			// shut up compiler warning
    for (p = node->portals; p; p = p->next[side]) {
	clipplane = pPlanes[p->planenum];
	if (p->nodes[0] == node)
	    side = 0;
	else if (p->nodes[1] == node) {
	    clipplane.dist = -clipplane.dist;
	    VectorSubtract(vec3_origin, clipplane.normal, clipplane.normal);
	    side = 1;
	} else
	    Message(msgError, errMislinkedPortal);

	w = ClipWinding(w, &clipplane, true);
	if (!w) {
	    Message(msgWarning, warnPortalClippedAway);
	    break;
	}
    }

    if (w) {
	// if the plane was not clipped on all sides, there was an error
	new_portal->winding = w;
	AddPortalToNodes(new_portal, f, b);
    }
    // partition the portals
    for (p = node->portals; p; p = next_portal) {
	if (p->nodes[0] == node)
	    side = 0;
	else if (p->nodes[1] == node)
	    side = 1;
	else
	    Message(msgError, errMislinkedPortal);
	next_portal = p->next[side];

	other_node = p->nodes[!side];
	RemovePortalFromNode(p, p->nodes[0]);
	RemovePortalFromNode(p, p->nodes[1]);

	// cut the portal into two portals, one on each side of the cut plane
	DivideWinding(p->winding, plane, &frontwinding, &backwinding);

	if (!frontwinding) {
	    if (side == 0)
		AddPortalToNodes(p, b, other_node);
	    else
		AddPortalToNodes(p, other_node, b);
	    continue;
	}
	if (!backwinding) {
	    if (side == 0)
		AddPortalToNodes(p, f, other_node);
	    else
		AddPortalToNodes(p, other_node, f);
	    continue;
	}
	// the winding is split
	new_portal = AllocMem(PORTAL, 1, true);
	*new_portal = *p;
	new_portal->winding = backwinding;
	FreeMem(p->winding, WINDING, 1);
	p->winding = frontwinding;

	if (side == 0) {
	    AddPortalToNodes(p, f, other_node);
	    AddPortalToNodes(new_portal, b, other_node);
	} else {
	    AddPortalToNodes(p, other_node, f);
	    AddPortalToNodes(new_portal, other_node, b);
	}
    }

    // Display progress
    iNodesDone++;
    Message(msgPercent, iNodesDone, splitnodes);

    CutNodePortals_r(f);
    CutNodePortals_r(b);
}
示例#5
0
SWBOOL CacheSound(int num, int type)
{
    VOC_INFOp vp = &voc[num];

    PRODUCTION_ASSERT(num >= 0 && num < DIGI_MAX);

    // if no data we need to cache it in
    if (!vp->data)
    {
        int handle;
        int length;

        if (!OpenSound(vp, &handle, &length))
        {
            sprintf(ds,"Could not open sound %s, num %d, priority %d\n",vp->name,num,vp->priority);
            CON_ConMessage(ds);
            return FALSE;
        }

        if (vp != NULL)
        {
            //FILE *fp;

            /*
            if (type == CACHE_SOUND_PLAY)
                // start it out locked at the min
                vp->lock = CACHE_LOCK_START;
            else
            if (type == CACHE_SOUND_PRECACHE)
                // start it out unlocked at the max
            */
            vp->lock = CACHE_UNLOCK_MAX;

            allocache((intptr_t*)&vp->data, length, &vp->lock);

#if 0
            // DEBUG
            globsndata[num] = AllocMem(length);
            glength[num] = length;

            fp = fopen(vp->name, "rb");
            if (fp != NULL)
            {
                fread(globsndata[num], length, 1, fp);
                ASSERT(globsndata[num] != NULL);
                fclose(fp);
            }
#endif
            ///////

            ASSERT(vp->data);
            ReadSound(handle, vp, length);

#if 0
            //DEBUG
            globvpdata[num] = vp->data;
            CheckSndData(__FILE__, __LINE__);
#endif
        }
    }

    return TRUE;
}
示例#6
0
文件: memory.c 项目: akadata/IanOS
//===============================================================================
// Allocate some user memory from the heap. sizeRequested = amount to allocate
// Returns in RAX address of allocated memory.
//===============================================================================
void *AllocUMem(size_t sizeRequested)
{
	return (AllocMem(sizeRequested, (void *) currentTask->firstfreemem));
}
示例#7
0
文件: csg4.c 项目: AidHamza/eviltoys
/*
==================
CSGFaces

Returns a list of surfaces containing all of the faces
==================
*/
surface_t *
CSGFaces(void)
{
    brush_t *b1, *b2;
    int i;
    bool overwrite;
    face_t *f;
    surface_t *surfhead;
    int iBrushes = 0;

    Message(msgProgress, "CSGFaces");

    if (validfaces == NULL)
	validfaces = AllocMem(OTHER, sizeof(face_t *) * cPlanes, true);
    else
	memset(validfaces, 0, sizeof(face_t *) * cPlanes);
    csgfaces = brushfaces = csgmergefaces = 0;

    // do the solid faces
    for (b1 = pCurEnt->pBrushes; b1; b1 = b1->next) {
	// set outside to a copy of the brush's faces
	CopyFacesToOutside(b1);

	// Why is this necessary?
	overwrite = false;

	for (b2 = pCurEnt->pBrushes; b2; b2 = b2->next) {
	    // check bounding box first
	    for (i = 0; i < 3; i++)
		if (b1->mins[i] > b2->maxs[i] || b1->maxs[i] < b2->mins[i])
		    break;
	    if (i < 3)
		continue;

	    // see if b2 needs to clip a chunk out of b1
	    if (b1 == b2) {
		overwrite = true;
		continue;
	    }
	    // divide faces by the planes of the new brush
	    inside = outside;
	    outside = NULL;

	    CheckInside(b2);
	    for (f = b2->faces; f; f = f->next)
		ClipInside(f->planenum, f->planeside, overwrite);

	    // these faces are continued in another brush, so get rid of them
	    if (b1->contents == CONTENTS_SOLID
		&& b2->contents <= CONTENTS_WATER)
		FreeInside(b2->contents);
	    else
		FreeInside(CONTENTS_SOLID);
	}

	// all of the faces left in outside are real surface faces
	if (b1->contents != CONTENTS_SOLID)
	    SaveOutside(true);	// mirror faces for inside view
	else
	    SaveOutside(false);

	iBrushes++;
	Message(msgPercent, iBrushes, pCurEnt->cBrushes);
    }

    surfhead = BuildSurfaces();

    Message(msgStat, "%5i brushfaces", brushfaces);
    Message(msgStat, "%5i csgfaces", csgfaces);
    Message(msgStat, "%5i mergedfaces", csgmergefaces);

    return surfhead;
}
示例#8
0
/*
=============
LoadBSPFile
=============
*/
void
LoadBSPFile(void)
{
    int i;
    int cFileSize, cLumpSize, iLumpOff;
    mapentity_t *entity;

    // Load the file header
    StripExtension(options.szBSPName);
    strcat(options.szBSPName, ".bsp");
    cFileSize = LoadFile(options.szBSPName, &header, true);

    switch (header->version) {
    case BSPVERSION:
        MemSize = MemSize_BSP29;
        break;
    case BSP2RMQVERSION:
        MemSize = MemSize_BSP2rmq;
        break;
    case BSP2VERSION:
        MemSize = MemSize_BSP2;
        break;
    default:
        Error("%s has unknown BSP version %d",
              options.szBSPName, header->version);
    }
    options.BSPVersion = header->version;

    /* Throw all of the data into the first entity to be written out later */
    entity = map.entities;
    for (i = 0; i < BSP_LUMPS; i++) {
        map.cTotal[i] = cLumpSize = header->lumps[i].filelen;
        iLumpOff = header->lumps[i].fileofs;
        
        if (i == LUMP_MODELS && !options.hexen2) {
            int j;

            if (cLumpSize % sizeof(dmodelq1_t))
                Error("Deformed lump in BSP file (size %d is not divisible by %d)",
                      cLumpSize, (int)sizeof(dmodelq1_t));
            
            entity->lumps[i].count = cLumpSize / sizeof(dmodelq1_t);
            entity->lumps[i].data = AllocMem(i, entity->lumps[i].count, false);
            
            map.cTotal[i] = entity->lumps[i].count * sizeof(dmodel_t);
            
            for (j=0; j<entity->lumps[i].count; j++)
            {
                int k;
                const dmodelq1_t *in = (dmodelq1_t *)((byte *)header + iLumpOff) + j;
                dmodelh2_t *out = (dmodelh2_t *)entity->lumps[i].data + j;
                
                for (k = 0; k < 3; k++) {
                    out->mins[k] = in->mins[k];
                    out->maxs[k] = in->maxs[k];
                    out->origin[k] = in->origin[k];
                }
                for (k = 0; k < MAX_MAP_HULLS_Q1; k++)
                    out->headnode[k] = in->headnode[k];
                out->visleafs = in->visleafs;
                out->firstface = in->firstface;
                out->numfaces = in->numfaces;
            }
        } else {
            if (cLumpSize % MemSize[i])
                Error("Deformed lump in BSP file (size %d is not divisible by %d)",
                      cLumpSize, MemSize[i]);
            
            entity->lumps[i].count = cLumpSize / MemSize[i];
            entity->lumps[i].data = AllocMem(i, entity->lumps[i].count, false);
            
            memcpy(entity->lumps[i].data, (byte *)header + iLumpOff, cLumpSize);
        }
    }

    FreeMem(header, OTHER, cFileSize + 1);
}
示例#9
0
void packet_handle_request(struct IOFileSys *iofs, struct PacketBase *PacketBase) {
    struct ph_handle *handle;
    struct ph_packet *pkt;
    struct DosPacket *dp;

    D(bug("[packet] got io request %d (%s)\n", iofs->IOFS.io_Command, fsa_str(iofs->IOFS.io_Command)));

    /* get our data back */
    handle = (struct ph_handle *) iofs->IOFS.io_Unit;

    /* make a fresh new packet */
    pkt = packet_alloc();
    dp = &(pkt->dp);

    /* hook the iofs up to the packet so we can find it on return
     * dp_Arg7 should be unused; DoPkt() doesn't touch it */
    dp->dp_Arg7 = (IPTR) iofs;

    /* our reply port will cause packet_reply() to be called when they reply */
    dp->dp_Port = &(handle->mount->reply_port);

    /* convert the command */
    switch (iofs->IOFS.io_Command) {

        case FSA_OPEN:
            D(bug("[packet] OPEN: lock 0x%08x (%s) name '%s' type %s\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_OPEN.io_Filename,
                (iofs->io_Union.io_OPEN.io_FileMode & FMF_LOCK) ? "EXCLUSIVE" : "SHARED"));

            if (!handle->is_lock) {
                /* If passed a filehandle, we can only deal with locking the
                 * filehandle itself or its parent (unless we were to resort
                 * to sending multiple packets)
                 */
                if (iofs->io_Union.io_OPEN.io_Filename[0] == '\0') {
                    dp->dp_Type = ACTION_COPY_DIR_FH;
                    dp->dp_Arg1 = (IPTR) handle->actual;
                }
                else if (iofs->io_Union.io_OPEN.io_Filename[0] == '/' &&
                    iofs->io_Union.io_OPEN.io_Filename[1] == '\0') {
                    dp->dp_Type = ACTION_PARENT_FH;
                    dp->dp_Arg1 = (IPTR) handle->actual;
                }
                else {
                    iofs->io_DosError = ERROR_NOT_IMPLEMENTED;
                    goto reply;
                }
            }
            else {
                dp->dp_Type = ACTION_LOCATE_OBJECT;
                dp->dp_Arg1 = (IPTR) handle->actual;
                dp->dp_Arg2 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_OPEN.io_Filename);
                dp->dp_Arg3 = (iofs->io_Union.io_OPEN.io_FileMode & FMF_LOCK) ? EXCLUSIVE_LOCK : SHARED_LOCK;
            }

            break;

        case FSA_OPEN_FILE: {
            ULONG mode = iofs->io_Union.io_OPEN_FILE.io_FileMode;
            struct ph_handle *new_handle;

            D(bug("[packet] OPEN_FILE: lock 0x%08x (%s) name '%s' mode 0x%x prot 0x%x\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_OPEN_FILE.io_Filename,
                mode,
                iofs->io_Union.io_OPEN_FILE.io_Protection));

            /* convert modes to the proper packet type (as best we can) */
            if ((mode & FMF_CLEAR) != 0)
                dp->dp_Type = ACTION_FINDOUTPUT;
            else if ((mode & FMF_CREATE) != 0)
                dp->dp_Type = ACTION_FINDUPDATE;
            else
                dp->dp_Type = ACTION_FINDINPUT;
            if ((mode & FMF_APPEND) != 0) {
                iofs->io_DosError = ERROR_BAD_NUMBER;
                goto reply;
            }

            /* make a new handle */
            new_handle =
                (struct ph_handle *) AllocMem(sizeof(struct ph_handle),
                MEMF_PUBLIC | MEMF_CLEAR);
            if (new_handle == NULL) {
                iofs->io_DosError = ERROR_NO_FREE_STORE;
                goto reply;
            }

            /* dos.lib buffer stuff, must be initialised this way */
            new_handle->fh.fh_Pos = new_handle->fh.fh_End = (UBYTE *) -1;

            dp->dp_Arg1 = (IPTR) MKBADDR(&new_handle->fh);
            dp->dp_Arg2 = (IPTR) (handle->is_lock ? handle->actual : NULL);
            dp->dp_Arg3 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_OPEN.io_Filename);

            break;
        }

        case FSA_CLOSE:
            D(bug("[packet] CLOSE: lock 0x%08x (%s)\n",
                handle->actual, handle_desc(handle)));

            /* if this is the root handle, then we previously intercepted a
             * call and returned it (e.g. FSA_OPEN/ACTION_PARENT), so we don't
             * want the handler to do anything */
            if (handle == &(handle->mount->root_handle)) {
                iofs->IOFS.io_Unit = NULL;
                goto reply;
            }

            dp->dp_Type = (handle->is_lock) ? ACTION_FREE_LOCK : ACTION_END;
            dp->dp_Arg1 = (IPTR) handle->actual;
            break;

        case FSA_READ:
            D(bug("[packet] READ: handle 0x%08x buf 0x%08x len %ld\n",
                handle->actual,
                iofs->io_Union.io_READ.io_Buffer,
                iofs->io_Union.io_READ.io_Length));

            dp->dp_Type = ACTION_READ;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) iofs->io_Union.io_READ.io_Buffer;
            dp->dp_Arg3 = (IPTR) iofs->io_Union.io_READ.io_Length;

            /* DOSFALSE == 0, so we can't distinguish between a zero-length
             * read and an actual error. So, we reset the length here. If the
             * returned packet is DOSFALSE, but no error, this will make sure
             * DOS gets the right length back */
            iofs->io_Union.io_READ.io_Length = 0;
            break;

        case FSA_WRITE:
            D(bug("[packet] WRITE: handle 0x%08x buf 0x%08x len %ld\n",
                handle->actual,
                iofs->io_Union.io_WRITE.io_Buffer,
                iofs->io_Union.io_WRITE.io_Length));

            dp->dp_Type = ACTION_WRITE;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) iofs->io_Union.io_WRITE.io_Buffer;
            dp->dp_Arg3 = (IPTR) iofs->io_Union.io_WRITE.io_Length;

            iofs->io_Union.io_WRITE.io_Length = 0;
            break;

        case FSA_SEEK:
#if defined(DEBUG) && DEBUG != 0
        {
            ULONG mode = iofs->io_Union.io_SEEK.io_SeekMode;

            bug("[packet] SEEK: handle 0x%08x offset %ld mode %ld (%s)\n",
                handle->actual,
                (LONG) iofs->io_Union.io_SEEK.io_Offset,
                mode,
                mode == OFFSET_BEGINNING ? "OFFSET_BEGINNING" :
                mode == OFFSET_CURRENT   ? "OFFSET_CURRENT"   :
                mode == OFFSET_END       ? "OFFSET_END"       :
                                           "[unknown]");
        }
#endif

            dp->dp_Type = ACTION_SEEK;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) iofs->io_Union.io_SEEK.io_Offset;
            dp->dp_Arg3 = (IPTR) iofs->io_Union.io_SEEK.io_SeekMode;
            break;

        case FSA_SET_FILE_SIZE:
#if defined(DEBUG) && DEBUG != 0
        {
            ULONG mode = iofs->io_Union.io_SET_FILE_SIZE.io_SeekMode;

            bug("[packet] SET_FILE_SIZE: handle 0x%08x offset %ld mode %ld (%s)\n",
                handle->actual,
                (LONG) iofs->io_Union.io_SET_FILE_SIZE.io_Offset,
                mode,
                mode == OFFSET_BEGINNING ? "OFFSET_BEGINNING" :
                mode == OFFSET_CURRENT   ? "OFFSET_CURRENT"   :
                mode == OFFSET_END       ? "OFFSET_END"       :
                                           "[unknown]");
        }
#endif

            dp->dp_Type = ACTION_SET_FILE_SIZE;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) iofs->io_Union.io_SET_FILE_SIZE.io_Offset;
            dp->dp_Arg3 = (IPTR) iofs->io_Union.io_SET_FILE_SIZE.io_SeekMode;
            break;

        case FSA_FILE_MODE: {

            D(bug("[packet] FILE_MODE: object 0x%08x (%s) mode 0x%x\b\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_FILE_MODE.io_FileMode));

            dp->dp_Type = ACTION_CHANGE_MODE;

            /* We can only change access mode */
            if ((iofs->io_Union.io_FILE_MODE.io_Mask & FMF_LOCK) == 0) {
                iofs->io_DosError = 0;
                goto reply;
            }
            if (handle->is_lock) {
                dp->dp_Arg1 = CHANGE_LOCK;
                dp->dp_Arg2 = (IPTR) handle->actual;
            }
            else {
                dp->dp_Arg1 = CHANGE_FH;
                handle->fh.fh_Arg1 = (IPTR) handle->actual;
                dp->dp_Arg2 = (IPTR) MKBADDR(&handle->fh);
            }
            dp->dp_Arg3 = (iofs->io_Union.io_FILE_MODE.io_FileMode & FMF_LOCK) ?
                EXCLUSIVE_LOCK : SHARED_LOCK;

            break;
        }

        case FSA_IS_INTERACTIVE:
            /* XXX is there some other way to query this? how does (eg) aos
             * console handler do it? */
            iofs->io_Union.io_IS_INTERACTIVE.io_IsInteractive = FALSE;
            iofs->io_DosError = 0;
            goto reply;

        case FSA_SAME_LOCK: {
            struct ph_handle *h1, *h2;
            h1 = (struct ph_handle *) iofs->io_Union.io_SAME_LOCK.io_Lock[0];
            h2 = (struct ph_handle *) iofs->io_Union.io_SAME_LOCK.io_Lock[1];

            D(bug("[packet] SAME_LOCK: lock1 0x%08x (%s) lock2 0x%08x (%s)\n",
                h1->actual, handle_desc(h1), h2->actual, handle_desc(h2)));

            dp->dp_Type = ACTION_SAME_LOCK;
            dp->dp_Arg1 = (IPTR) h1->actual;
            dp->dp_Arg2 = (IPTR) h2->actual;
            break;
        }

        case FSA_EXAMINE: {
            struct FileInfoBlock *fib;

            D(bug("[packet] EXAMINE: lock 0x%08x (%s)\n",
                handle->actual, handle_desc(handle)));

            fib = (struct FileInfoBlock *) AllocMem(sizeof(struct FileInfoBlock), MEMF_PUBLIC | MEMF_CLEAR);

            dp->dp_Type = (handle->is_lock) ? ACTION_EXAMINE_OBJECT : ACTION_EXAMINE_FH;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) MKBADDR(fib);
            break;
        }

        case FSA_EXAMINE_NEXT:
            D(bug("[packet] EXAMINE_NEXT: lock 0x%08x (%s) fib 0x%08x\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_EXAMINE_NEXT.io_fib));

            dp->dp_Type = ACTION_EXAMINE_NEXT;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) MKBADDR(iofs->io_Union.io_EXAMINE_NEXT.io_fib);
            break;

        case FSA_CREATE_DIR:
            D(bug("[packet] CREATE_DIR: lock 0x%08x (%s) name '%s'\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_CREATE_DIR.io_Filename));

            dp->dp_Type = ACTION_CREATE_DIR;
            dp->dp_Arg1 = (IPTR) (handle->is_lock ? handle->actual : NULL);
            dp->dp_Arg2 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_CREATE_DIR.io_Filename);
            break;

        case FSA_IS_FILESYSTEM:
            dp->dp_Type = ACTION_IS_FILESYSTEM;
            break;

        case FSA_DISK_INFO:
            dp->dp_Type = ACTION_DISK_INFO;
            dp->dp_Arg1 = (IPTR) MKBADDR(iofs->io_Union.io_INFO.io_Info);
            break;

        case FSA_CREATE_HARDLINK:
            {
                struct ph_handle *target = (struct ph_handle *)
                    iofs->io_Union.io_CREATE_HARDLINK.io_OldFile;

                D(bug("[packet] CREATE_HARDLINK: lock 0x%08x (%s) name '%s' "
                    "target 0x%08x (%s)\n",
                    handle->actual, handle_desc(handle),
                    iofs->io_Union.io_CREATE_HARDLINK.io_Filename,
                    target->actual, handle_desc(target)));

                dp->dp_Type = ACTION_MAKE_LINK;
                dp->dp_Arg1 = (IPTR) handle->actual;
                dp->dp_Arg2 = (IPTR) mkbstr(pkt->pool,
                    iofs->io_Union.io_CREATE_HARDLINK.io_Filename);
                dp->dp_Arg3 = (IPTR) target->actual;
                dp->dp_Arg4 = LINK_HARD;
                break;
            }

        case FSA_CREATE_SOFTLINK:
            D(bug("[packet] CREATE_SOFTLINK: lock 0x%08x (%s) name '%s' target '%s'\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_CREATE_SOFTLINK.io_Filename,
                iofs->io_Union.io_CREATE_SOFTLINK.io_Reference));

            dp->dp_Type = ACTION_MAKE_LINK;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_CREATE_SOFTLINK.io_Filename);
            dp->dp_Arg3 = (IPTR) iofs->io_Union.io_CREATE_SOFTLINK.io_Reference;
            dp->dp_Arg4 = LINK_SOFT;
            break;

        case FSA_RENAME:
            D(bug("[packet] RENAME: lock 0x%08x (%s) name '%s' target '%s'\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_RENAME.io_Filename,
                iofs->io_Union.io_RENAME.io_NewName));

            /* XXX the two paths from FSA_RENAME are copied directly from the
             * arguments to rename with no changes, so they may contain volume
             * specifiers, path seperators, etc. both can be calculated
             * relative to the handle. here we just pass them through to the
             * handler as-is, but I'm not sure if that's right. fat.handler at
             * least will do the right thing. this probably needs to be
             * revisited if another packet-based handler is ported */

            dp->dp_Type = ACTION_RENAME_OBJECT;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_RENAME.io_Filename);
            dp->dp_Arg3 = (IPTR) handle->actual;
            dp->dp_Arg4 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_RENAME.io_NewName);
            break;

        case FSA_READ_SOFTLINK:
            D(bug("[packet] READ_SOFTLINK: lock 0x%08x (%s) name '%s'\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_READ_SOFTLINK.io_Filename));

            dp->dp_Type = ACTION_READ_LINK;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) iofs->io_Union.io_READ_SOFTLINK.io_Filename;
            dp->dp_Arg3 = (IPTR) iofs->io_Union.io_READ_SOFTLINK.io_Buffer;
            dp->dp_Arg4 = (IPTR) iofs->io_Union.io_READ_SOFTLINK.io_Size;
            break;

        case FSA_DELETE_OBJECT:
            D(bug("[packet] DELETE: lock 0x%08x (%s) name '%s'\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_DELETE_OBJECT.io_Filename));

            dp->dp_Type = ACTION_DELETE_OBJECT;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_DELETE_OBJECT.io_Filename);
            break;

        case FSA_SET_COMMENT:
            D(bug("[packet] SET_COMMENT: lock 0x%08x (%s) name '%s' comment '%s'\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_SET_COMMENT.io_Filename,
                iofs->io_Union.io_SET_COMMENT.io_Comment));

            dp->dp_Type = ACTION_SET_COMMENT;
            dp->dp_Arg1 = 0;
            dp->dp_Arg2 = (IPTR) handle->actual;
            dp->dp_Arg3 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_SET_COMMENT.io_Filename);
            dp->dp_Arg4 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_SET_COMMENT.io_Comment);
            break;
            
        case FSA_SET_PROTECT:
            D(bug("[packet] SET_PROTECT: lock 0x%08x (%s) name '%s' attrs 0x%x\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_SET_PROTECT.io_Filename,
                iofs->io_Union.io_SET_PROTECT.io_Protection));

            dp->dp_Type = ACTION_SET_PROTECT;
            dp->dp_Arg1 = 0;
            dp->dp_Arg2 = (IPTR) handle->actual;
            dp->dp_Arg3 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_SET_PROTECT.io_Filename);
            dp->dp_Arg4 = (IPTR) iofs->io_Union.io_SET_PROTECT.io_Protection;
            break;

        case FSA_SET_OWNER: /* XXX untested */
            D(bug("[packet] SET_OWNER: lock 0x%08x (%s) name '%s' uid 0x%x gid 0x%x\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_SET_OWNER.io_Filename,
                iofs->io_Union.io_SET_OWNER.io_UID,
                iofs->io_Union.io_SET_OWNER.io_GID));

            dp->dp_Type = ACTION_SET_OWNER;
            dp->dp_Arg1 = 0;
            dp->dp_Arg2 = (IPTR) handle->actual;
            dp->dp_Arg3 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_SET_OWNER.io_Filename);
            dp->dp_Arg4 = (IPTR) iofs->io_Union.io_SET_OWNER.io_GID << 16 |
                                 iofs->io_Union.io_SET_OWNER.io_UID;
            break;

        case FSA_SET_DATE: /* XXX untested */
#if defined(DEBUG) && DEBUG != 0
        {
            struct DateTime dt;
            char datestr[LEN_DATSTRING];

            dt.dat_Stamp = iofs->io_Union.io_SET_DATE.io_Date;
            dt.dat_Format = FORMAT_DOS;
            dt.dat_Flags = 0;
            dt.dat_StrDay = NULL;
            dt.dat_StrDate = datestr;
            dt.dat_StrTime = NULL;
            DateToStr(&dt);

            bug("[packet] SET_DATE: lock 0x%08x (%s) name '%s' date '%s'\n",
                handle->actual, handle_desc(handle),
                iofs->io_Union.io_SET_DATE.io_Filename,
                datestr);
        }
#endif

            dp->dp_Type = ACTION_SET_DATE;
            dp->dp_Arg1 = 0;
            dp->dp_Arg2 = (IPTR) handle->actual;
            dp->dp_Arg3 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_SET_DATE.io_Filename);
            dp->dp_Arg4 = (IPTR) &iofs->io_Union.io_SET_DATE.io_Date;
            break;

        case FSA_MORE_CACHE: /* XXX untested */
            D(bug("[packet] MORE_CACHE: buffers '0x%x'\n", iofs->io_Union.io_MORE_CACHE.io_NumBuffers));

            dp->dp_Type = ACTION_MORE_CACHE;
            dp->dp_Arg1 = (IPTR) iofs->io_Union.io_MORE_CACHE.io_NumBuffers;
            break;

        case FSA_FORMAT: /* XXX untested */
            D(bug("[packet] FSA_FORMAT: name '%s' type 0x%x\n",
                  iofs->io_Union.io_FORMAT.io_VolumeName,
                  iofs->io_Union.io_FORMAT.io_DosType));

            dp->dp_Type = ACTION_FORMAT;
            dp->dp_Arg1 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_FORMAT.io_VolumeName);
            dp->dp_Arg2 = (IPTR) iofs->io_Union.io_FORMAT.io_DosType;
            break;

        case FSA_INHIBIT:
            D(bug("[packet] FSA_INHIBIT: %sinhibit\n", iofs->io_Union.io_INHIBIT.io_Inhibit == 0 ? "un" : ""));

            dp->dp_Type = ACTION_INHIBIT;
            dp->dp_Arg1 = iofs->io_Union.io_INHIBIT.io_Inhibit ? DOSTRUE : DOSFALSE;
            break;

        case FSA_RELABEL:
            D(bug("[packet] FSA_RELABEL: name '%s'\n", iofs->io_Union.io_RELABEL.io_NewName));

            dp->dp_Type = ACTION_RENAME_DISK;
            dp->dp_Arg1 = (IPTR) mkbstr(pkt->pool, iofs->io_Union.io_RELABEL.io_NewName);
            break;

        case FSA_LOCK_RECORD: /* XXX untested */
#if defined(DEBUG) && DEBUG != 0
        {
            ULONG mode = iofs->io_Union.io_RECORD.io_RecordMode;

            bug("[packet] FSA_LOCK_RECORD: handle 0x%08x offset %ld size %ld mode %d (%s) timeout %d\n",
                handle->actual,
                (LONG) iofs->io_Union.io_RECORD.io_Offset,
                iofs->io_Union.io_RECORD.io_Size,
                mode,
                mode == REC_EXCLUSIVE       ? "REC_EXCLUSIVE"       :
                mode == REC_EXCLUSIVE_IMMED ? "REC_EXCLUSIVE_IMMED" :
                mode == REC_SHARED          ? "REC_SHARED"          :
                mode == REC_SHARED_IMMED    ? "REC_SHARED_IMMED"    :
                                              "[unknown]",
                iofs->io_Union.io_RECORD.io_Timeout);
        }
#endif

            dp->dp_Type = ACTION_LOCK_RECORD;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) iofs->io_Union.io_RECORD.io_Offset;
            dp->dp_Arg3 = (IPTR) iofs->io_Union.io_RECORD.io_Size;
            dp->dp_Arg4 = (IPTR) iofs->io_Union.io_RECORD.io_RecordMode;
            dp->dp_Arg5 = (IPTR) iofs->io_Union.io_RECORD.io_Timeout;
            break;

        case FSA_UNLOCK_RECORD: /* XXX untested */
            D(bug("[packet] FSA_UNLOCK_RECORD: handle 0x%08x offset %ld size %ld\n",
                  handle->actual,
                  (LONG) iofs->io_Union.io_RECORD.io_Offset,
                  iofs->io_Union.io_RECORD.io_Size));

            dp->dp_Type = ACTION_FREE_RECORD;
            dp->dp_Arg1 = (IPTR) handle->actual;
            dp->dp_Arg2 = (IPTR) iofs->io_Union.io_RECORD.io_Offset;
            dp->dp_Arg3 = (IPTR) iofs->io_Union.io_RECORD.io_Size;
            break;

        case FSA_ADD_NOTIFY:
            D(bug("[packet] FSA_ADD_NOTIFY: nr 0x%08x name '%s'\n", 
                  iofs->io_Union.io_NOTIFY.io_NotificationRequest,
                  iofs->io_Union.io_NOTIFY.io_NotificationRequest->nr_FullName));

            dp->dp_Type = ACTION_ADD_NOTIFY;
            dp->dp_Arg1 =
                (SIPTR) iofs->io_Union.io_NOTIFY.io_NotificationRequest;
            break;

        case FSA_REMOVE_NOTIFY:
            D(bug("[packet] FSA_REMOVE_NOTIFY: nr 0x%08x name '%s'\n", 
                  iofs->io_Union.io_NOTIFY.io_NotificationRequest,
                  iofs->io_Union.io_NOTIFY.io_NotificationRequest->nr_FullName));

            dp->dp_Type = ACTION_REMOVE_NOTIFY;
            dp->dp_Arg1 =
                (SIPTR) iofs->io_Union.io_NOTIFY.io_NotificationRequest;
            break;

        /* XXX implement */
        case FSA_EXAMINE_ALL:
        case FSA_EXAMINE_ALL_END:
        case FSA_MOUNT_MODE:
        case FSA_CHANGE_SIGNAL:
        case FSA_PARENT_DIR:
        case FSA_PARENT_DIR_POST:
        case FSA_CONSOLE_MODE:
            D(bug("[packet] command not implemented\n"));
            iofs->io_DosError = ERROR_NOT_IMPLEMENTED;
            goto reply;

        default:
            D(bug("[packet] unknown command\n"));
            iofs->io_DosError = ERROR_ACTION_NOT_KNOWN;
            goto reply;
    }

    D(bug("[packet] converted to %s packet\n", act_str(dp->dp_Type)));

    /* WaitIO() will look into this */
    iofs->IOFS.io_Message.mn_Node.ln_Type = NT_MESSAGE;

    /* since these all go to the packet handler process, they can't be done now */
    iofs->IOFS.io_Flags &= ~IOF_QUICK;

    /* send the packet */
    PutMsg(&(handle->mount->process->pr_MsgPort), dp->dp_Link);

    return;

    /* jump here to reply to the packet now, handling IOF_QUICK appropriately */
reply:
    D(bug("[packet] replying directly with error %d\n", iofs->io_DosError));
    
    /* kill the packet */
    DeletePool(pkt->pool);

    /* if they can handle quick replies, just bail out */
    if (iofs->IOFS.io_Flags & IOF_QUICK)
        return;

    /* otherwise tell them properly */
    ReplyMsg((APTR) iofs);
}
示例#10
0
文件: startup.c 项目: diegocr/YGRip
int __startup_function_which_calls_main_without_arguments ( void )
{
	unsigned int stack_size, __stack_size = STACK_SIZE ;
	struct WBStartup * startup_message;
	struct Process * this_process;
	struct StackSwapStruct *stk;
	APTR old_window_pointer;
	struct Task *this_task;
	APTR new_stack;
	int ret = 1;
	
	SysBase = *(struct ExecBase **) 4L;
	
	this_process = (struct Process *)(this_task = FindTask(NULL));
	
	if(!this_process->pr_CLI)
	{
		struct MsgPort * mp = &this_process->pr_MsgPort;
		
		WaitPort(mp);
		
		startup_message = (struct WBStartup *)GetMsg(mp);
	}
	else	startup_message = NULL;
	
	old_window_pointer = this_process->pr_WindowPtr;
	
//	_WBenchMsg = startup_message;
	
	__stack_size += ((ULONG)this_task->tc_SPUpper-(ULONG)this_task->tc_SPLower);
	
	/* Make the stack size a multiple of 32 bytes. */
	stack_size = 32 + ((__stack_size + 31UL) & ~31UL);
	
	/* Allocate the stack swapping data structure
	   and the stack space separately. */
	stk = AllocVec( sizeof(*stk), MEMF_PUBLIC|MEMF_ANY );
	if(stk != NULL)
	{
		new_stack = AllocMem(stack_size,MEMF_PUBLIC|MEMF_ANY);
		if(new_stack != NULL)
		{
			/* Fill in the lower and upper bounds, then
			   take care of the stack pointer itself. */
			
			stk->stk_Lower	= new_stack;
			stk->stk_Upper	= (ULONG)(new_stack)+stack_size;
			stk->stk_Pointer= (APTR)(stk->stk_Upper - 32);
			
			ret = __swap_stack_and_call(stk,(APTR)__main);
			
			FreeMem(new_stack, stack_size);
		}
		
		FreeVec(stk);
	}
	
	this_process->pr_WindowPtr = old_window_pointer;
	
	if(startup_message != NULL)
	{
		Forbid();
		
		ReplyMsg((struct Message *)startup_message);
	}
	
	return ret;
}
示例#11
0
文件: simplerexx.c 项目: vidarh/FPL
/*
 * This routine initializes an ARexx port for your process
 * This should only be done once per process.  You must call it
 * with a valid application name and you must use the handle it
 * returns in all other calls...
 *
 * NOTE:  The AppName should not have spaces in it...
 *        Example AppNames:  "MyWord" or "FastCalc" etc...
 *        The name *MUST* be less that 16 characters...
 *        If it is not, it will be trimmed...
 *        The name will also be UPPER-CASED...
 *
 * NOTE:  The Default file name extension, if NULL will be
 *        "rexx"  (the "." is automatic)
 */
AREXXCONTEXT InitARexx(char *AppName,char *Extension)
{
    register	AREXXCONTEXT	RexxContext=NULL;
    register	short		loop;
    register	short		count;
    register	char		*tmp;

    if (RexxContext=AllocMem(sizeof(struct ARexxContext),
                             MEMF_PUBLIC|MEMF_CLEAR))
    {
        if (RexxContext->RexxSysBase=OpenLibrary("rexxsyslib.library",
                                     NULL))
        {
            /*
             * Set up the extension...
             */
            if (!Extension) Extension="rexx";
            tmp=RexxContext->Extension;
            for (loop=0; (loop<7)&&(Extension[loop]); loop++)
            {
                *tmp++=Extension[loop];
            }
            *tmp='\0';

            /*
             * Set up a port name...
             */
            tmp=RexxContext->PortName;
            for (loop=0; (loop<16)&&(AppName[loop]); loop++)
            {
                *tmp++=toupper(AppName[loop]);
            }
            *tmp='\0';

            /*
             * Set up the last error RVI name...
             *
             * This is <appname>.LASTERROR
             */
            strcpy(RexxContext->ErrorName,RexxContext->PortName);
            strcat(RexxContext->ErrorName,".LASTERROR");

            /* We need to make a unique port name... */
            Forbid();
#if 0
            for (count=1,RexxContext->ARexxPort=(VOID *)1;
                    RexxContext->ARexxPort; count++)
            {
                stci_d(tmp,count);
#endif
                RexxContext->ARexxPort=
                    FindPort(RexxContext->PortName);
#if 0
            }
#endif
            RexxContext->ARexxPort=CreatePort(
                                       RexxContext->PortName,NULL);
            Permit();
        }

        if (	(!(RexxContext->RexxSysBase))
                ||	(!(RexxContext->ARexxPort))	)
        {
            FreeARexx(RexxContext);
            RexxContext=NULL;
        }
    }
    return(RexxContext);
}
示例#12
0
static BOOL CmdTrackType(struct IOSana2Req *request,
   struct DevBase *base)
{
   struct DevUnit *unit;
   struct Opener *opener;
   ULONG packet_type, wire_error;
   struct TypeTracker *tracker;
   struct TypeStats *initial_stats;
   BYTE error = 0;

   unit = (APTR)request->ios2_Req.io_Unit;
   packet_type = request->ios2_PacketType;
   if(packet_type <= ETH_MTU)
      packet_type = ETH_MTU;

   /* Get global tracker */

   tracker = (struct TypeTracker *)
      FindTypeStats(unit, &unit->type_trackers, packet_type, base);

   if(tracker != NULL)
      tracker->user_count++;
   else
   {
      tracker =
         AllocMem(sizeof(struct TypeTracker), MEMF_PUBLIC | MEMF_CLEAR);
      if(tracker != NULL)
      {
         tracker->packet_type = packet_type;
         tracker->user_count = 1;

         Disable();
         AddTail((APTR)&unit->type_trackers, (APTR)tracker);
         Enable();
      }
   }

   /* Store initial figures for this opener */

   opener = request->ios2_BufferManagement;
   initial_stats = FindTypeStats(unit, &opener->initial_stats, packet_type,
      base);

   if(initial_stats != NULL)
   {
      error = S2ERR_BAD_STATE;
      wire_error = S2WERR_ALREADY_TRACKED;
   }

   if(error == 0)
   {
      initial_stats = AllocMem(sizeof(struct TypeStats), MEMF_PUBLIC);
      if(initial_stats == NULL)
      {
         error = S2ERR_NO_RESOURCES;
         wire_error = S2WERR_GENERIC_ERROR;
      }
   }

   if(error == 0)
   {
      CopyMem(tracker, initial_stats, sizeof(struct TypeStats));
      AddTail((APTR)&opener->initial_stats, (APTR)initial_stats);
   }

   /* Return */

   request->ios2_Req.io_Error = error;
   request->ios2_WireError = wire_error;
   return TRUE;
}
示例#13
0
	/* xoper hunks Shell Process */

	num=0;
        for (data = (ULONG *)BADDR(myseglist); data != NULL;
             data = (ULONG *)BADDR(data[0])) {
	  if (((ULONG) GC_register_data_segments < (ULONG) &data[1]) ||
	      ((ULONG) GC_register_data_segments > (ULONG) &data[1] + data[-1])) {
#             ifdef __GNUC__
		if (dataSegSize == data[-1]) {
		  found_segment = TRUE;
		}
# 	      endif
	      GC_add_roots_inner((char *)&data[1],
				 ((char *)&data[1]) + data[-1], FALSE);
          }
          ++num;
        } /* for */
# 	ifdef __GNUC__
	   if (!found_segment) {
	     ABORT("Can`t find correct Segments.\nSolution: Use an newer version of ixemul.library");
	   }
# 	endif
  }

#if 0 /* old version */
  void GC_register_data_segments()
  {
    extern struct WBStartup *_WBenchMsg;
    struct Process	*proc;
    struct CommandLineInterface *cli;
    BPTR myseglist;
    ULONG *data;

    if ( _WBenchMsg != 0 ) {
	if ((myseglist = _WBenchMsg->sm_Segment) == 0) {
	    GC_err_puts("No seglist from workbench\n");
	    return;
	}
    } else {
	if ((proc = (struct Process *)FindTask(0)) == 0) {
	    GC_err_puts("Cannot find process structure\n");
	    return;
	}
	if ((cli = BADDR(proc->pr_CLI)) == 0) {
	    GC_err_puts("No CLI\n");
	    return;
	}
	if ((myseglist = cli->cli_Module) == 0) {
	    GC_err_puts("No seglist from CLI\n");
	    return;
	}
    }

    for (data = (ULONG *)BADDR(myseglist); data != 0;
         data = (ULONG *)BADDR(data[0])) {
#        ifdef AMIGA_SKIP_SEG
           if (((ULONG) GC_register_data_segments < (ULONG) &data[1]) ||
           ((ULONG) GC_register_data_segments > (ULONG) &data[1] + data[-1])) {
#	 else
	   {
#	 endif /* AMIGA_SKIP_SEG */
          GC_add_roots_inner((char *)&data[1],
			     ((char *)&data[1]) + data[-1], FALSE);
         }
    }
  }
#endif /* old version */


#endif



#ifdef GC_AMIGA_AM

#ifndef GC_AMIGA_FASTALLOC

void *GC_amiga_allocwrapper(size_t size,void *(*AllocFunction)(size_t size2)){
	return (*AllocFunction)(size);
}

void *(*GC_amiga_allocwrapper_do)(size_t size,void *(*AllocFunction)(size_t size2))
	=GC_amiga_allocwrapper;

#else




void *GC_amiga_allocwrapper_firsttime(size_t size,void *(*AllocFunction)(size_t size2));

void *(*GC_amiga_allocwrapper_do)(size_t size,void *(*AllocFunction)(size_t size2))
	=GC_amiga_allocwrapper_firsttime;


/******************************************************************
   Amiga-spesific routines to obtain memory, and force GC to give
   back fast-mem whenever possible.
	These hacks makes gc-programs go many times faster when
   the amiga is low on memory, and are therefore strictly necesarry.

   -Kjetil S. Matheussen, 2000.
******************************************************************/



/* List-header for all allocated memory. */

struct GC_Amiga_AllocedMemoryHeader{
	ULONG size;
	struct GC_Amiga_AllocedMemoryHeader *next;
};
struct GC_Amiga_AllocedMemoryHeader *GC_AMIGAMEM=(struct GC_Amiga_AllocedMemoryHeader *)(int)~(NULL);



/* Type of memory. Once in the execution of a program, this might change to MEMF_ANY|MEMF_CLEAR */

ULONG GC_AMIGA_MEMF = MEMF_FAST | MEMF_CLEAR;


/* Prevents GC_amiga_get_mem from allocating memory if this one is TRUE. */
#ifndef GC_AMIGA_ONLYFAST
BOOL GC_amiga_dontalloc=FALSE;
#endif

#ifdef GC_AMIGA_PRINTSTATS
int succ=0,succ2=0;
int nsucc=0,nsucc2=0;
int nullretries=0;
int numcollects=0;
int chipa=0;
int allochip=0;
int allocfast=0;
int cur0=0;
int cur1=0;
int cur10=0;
int cur50=0;
int cur150=0;
int cur151=0;
int ncur0=0;
int ncur1=0;
int ncur10=0;
int ncur50=0;
int ncur150=0;
int ncur151=0;
#endif

/* Free everything at program-end. */

void GC_amiga_free_all_mem(void){
	struct GC_Amiga_AllocedMemoryHeader *gc_am=(struct GC_Amiga_AllocedMemoryHeader *)(~(int)(GC_AMIGAMEM));
	struct GC_Amiga_AllocedMemoryHeader *temp;

#ifdef GC_AMIGA_PRINTSTATS
	printf("\n\n"
		"%d bytes of chip-mem, and %d bytes of fast-mem where allocated from the OS.\n",
		allochip,allocfast
	);
	printf(
		"%d bytes of chip-mem were returned from the GC_AMIGA_FASTALLOC supported allocating functions.\n",
		chipa
	);
	printf("\n");
	printf("GC_gcollect was called %d times to avoid returning NULL or start allocating with the MEMF_ANY flag.\n",numcollects);
	printf("%d of them was a success. (the others had to use allocation from the OS.)\n",nullretries);
	printf("\n");
	printf("Succeded forcing %d gc-allocations (%d bytes) of chip-mem to be fast-mem.\n",succ,succ2);
	printf("Failed forcing %d gc-allocations (%d bytes) of chip-mem to be fast-mem.\n",nsucc,nsucc2);
	printf("\n");
	printf(
		"Number of retries before succeding a chip->fast force:\n"
		"0: %d, 1: %d, 2-9: %d, 10-49: %d, 50-149: %d, >150: %d\n",
		cur0,cur1,cur10,cur50,cur150,cur151
	);
	printf(
		"Number of retries before giving up a chip->fast force:\n"
		"0: %d, 1: %d, 2-9: %d, 10-49: %d, 50-149: %d, >150: %d\n",
		ncur0,ncur1,ncur10,ncur50,ncur150,ncur151
	);
#endif

	while(gc_am!=NULL){
		temp=gc_am->next;
		FreeMem(gc_am,gc_am->size);
		gc_am=(struct GC_Amiga_AllocedMemoryHeader *)(~(int)(temp));
	}
}

#ifndef GC_AMIGA_ONLYFAST

/* All memory with address lower than this one is chip-mem. */

char *chipmax;


/*
 * Allways set to the last size of memory tried to be allocated.
 * Needed to ensure allocation when the size is bigger than 100000.
 *
 */
size_t latestsize;

#endif


/*
 * The actual function that is called with the GET_MEM macro.
 *
 */

void *GC_amiga_get_mem(size_t size){
	struct GC_Amiga_AllocedMemoryHeader *gc_am;

#ifndef GC_AMIGA_ONLYFAST
	if(GC_amiga_dontalloc==TRUE){
//		printf("rejected, size: %d, latestsize: %d\n",size,latestsize);
		return NULL;
	}

	// We really don't want to use chip-mem, but if we must, then as little as possible.
	if(GC_AMIGA_MEMF==(MEMF_ANY|MEMF_CLEAR) && size>100000 && latestsize<50000) return NULL;
#endif

	gc_am=AllocMem((ULONG)(size + sizeof(struct GC_Amiga_AllocedMemoryHeader)),GC_AMIGA_MEMF);
	if(gc_am==NULL) return NULL;

	gc_am->next=GC_AMIGAMEM;
	gc_am->size=size + sizeof(struct GC_Amiga_AllocedMemoryHeader);
	GC_AMIGAMEM=(struct GC_Amiga_AllocedMemoryHeader *)(~(int)(gc_am));

//	printf("Allocated %d (%d) bytes at address: %x. Latest: %d\n",size,tot,gc_am,latestsize);

#ifdef GC_AMIGA_PRINTSTATS
	if((char *)gc_am<chipmax){
		allochip+=size;
	}else{
		allocfast+=size;
	}
#endif

	return gc_am+1;

}




#ifndef GC_AMIGA_ONLYFAST

/* Tries very hard to force GC to find fast-mem to return. Done recursively
 * to hold the rejected memory-pointers reachable from the collector in an
 * easy way.
 *
 */
#ifdef GC_AMIGA_RETRY
void *GC_amiga_rec_alloc(size_t size,void *(*AllocFunction)(size_t size2),const int rec){
	void *ret;

	ret=(*AllocFunction)(size);

#ifdef GC_AMIGA_PRINTSTATS
	if((char *)ret>chipmax || ret==NULL){
		if(ret==NULL){
			nsucc++;
			nsucc2+=size;
			if(rec==0) ncur0++;
			if(rec==1) ncur1++;
			if(rec>1 && rec<10) ncur10++;
			if(rec>=10 && rec<50) ncur50++;
			if(rec>=50 && rec<150) ncur150++;
			if(rec>=150) ncur151++;
		}else{
			succ++;
			succ2+=size;
			if(rec==0) cur0++;
			if(rec==1) cur1++;
			if(rec>1 && rec<10) cur10++;
			if(rec>=10 && rec<50) cur50++;
			if(rec>=50 && rec<150) cur150++;
			if(rec>=150) cur151++;
		}
	}
#endif

	if (((char *)ret)<=chipmax && ret!=NULL && (rec<(size>500000?9:size/5000))){
		ret=GC_amiga_rec_alloc(size,AllocFunction,rec+1);
//		GC_free(ret2);
	}

	return ret;
}
示例#14
0
文件: allocator.c 项目: michalsc/AROS
int main(void)
{
#if defined(KrnStatMemory)

#if defined(__AROSPLATFORM_SMP__)
    void *ExecLockBase = OpenResource("execlock.resource");
#endif
    APTR KernelBase;
    struct Task *me;
    ULONG page;
    struct MemHeader *TestArea;
    ULONG TestLength;
    struct MemChunk *mc;
    APTR region1, region2, region3, region4;

    KernelBase = OpenResource("kernel.resource");
    if (!KernelBase)
    {
	printf("Failed to open kernel.resource!\n");
	return 1;
    }

    if (!KrnStatMemory(0, KMS_PageSize, &page, TAG_DONE))
    {
	printf("MMU support is not implemented for this system!\n"
	       "kernel.resource memory allocator will not work!\n");
	return 1;
    }
    printf("System page size: %u (0x%08X)\n", (unsigned)page, (unsigned)page);

    TestLength = PAGES_NUM * page;
    TestArea = AllocMem(TestLength, MEMF_ANY);
    printf("Allocated test region (%u bytes) at 0x%p\n", (unsigned)TestLength, TestArea);
    if (!TestArea)
    {
	printf("Failed to allocate test region!\n");
	return 1;
    }

    /* Install trap handler */
    me = FindTask(NULL);
    me->tc_TrapCode = TrapHandler;

    /* Compose a MemHeader */
    TestArea->mh_Node.ln_Succ = NULL;
    TestArea->mh_Node.ln_Type = NT_MEMORY;
    TestArea->mh_Node.ln_Name = "Kernel allocator test area";
    TestArea->mh_Node.ln_Pri  = 127;			/* This MemHeader must be the first in the list, otherwise KrnFreePages() will find a wrong one */
    TestArea->mh_Attributes   = MEMF_FAST;
    TestArea->mh_Lower        = TestArea;
    TestArea->mh_Upper        = TestArea->mh_Lower + TestLength - 1;
    TestArea->mh_First        = TestArea->mh_Lower + MEMHEADER_TOTAL;
    TestArea->mh_Free         = TestLength - MEMHEADER_TOTAL;

    mc = TestArea->mh_First;
    mc->mc_Next  = NULL;
    mc->mc_Bytes = TestArea->mh_Free;

    /* Give up the area to kernel allocator */
    KrnInitMemory(TestArea);
    if (mc->mc_Next || mc->mc_Bytes)
    {
	printf("KrnInitMemory() failed:\n"
	       "  mc_Next  is 0x%p\n"
	       "  mc_Bytes is %lu\n",
	       mc->mc_Next, mc->mc_Bytes);
	goto exit;
    }

    printf("Testing initial no-access protection...\n");
    TestRead((UBYTE *)TestArea + page);

    /*
     * Insert the area into system list.
     * We do it manually because in future AddMemList() will call KrnInitMemory() itself.
     */
#if defined(__AROSPLATFORM_SMP__)
    if (ExecLockBase)
        ObtainSystemLock(&SysBase->MemList, SPINLOCK_MODE_WRITE, LOCKF_FORBID);
    else
        Forbid();
#else
    Forbid();
#endif
    Enqueue(&SysBase->MemList, &TestArea->mh_Node);
#if defined(__AROSPLATFORM_SMP__)
    if (ExecLockBase)
        ReleaseSystemLock(&SysBase->MemList, LOCKF_FORBID);
    else
        Permit();
#else
    Permit();
#endif

    printf("Allocating region1 (two read-write pages)...\n");
    region1 = KrnAllocPages(NULL, 2 * page, MEMF_FAST);
    printf("region1 at 0x%p\n", region1);
    DumpState(TestArea);

    printf("Freeing region1...\n");
    KrnFreePages(region1, 2 * page);
    printf("Done!\n");
    DumpState(TestArea);

    printf("Allocating region1 (3 read-only pages)...\n");
    region1 = KrnAllocPages(NULL, 3 * page, MEMF_FAST);
    printf("region1 at 0x%p\n", region1);
    DumpState(TestArea);

    printf("Allocating region2 (4 write-only ;-) pages)...\n");
    region2 = KrnAllocPages(NULL, 4 * page, MEMF_FAST);
    printf("region2 at 0x%p\n", region2);
    DumpState(TestArea);

    printf("Attempting to allocate page with wrong flags...\n");
    region3 = KrnAllocPages(NULL, page, MEMF_CHIP|MEMF_FAST);
    printf("Region at 0x%p\n", region3);
    if (region3)
    {
	printf("WARNING!!! This should have been NULL!\n");
	KrnFreePages(region3, page);
    }

    printf("Freeing region1...\n");
    KrnFreePages(region1, 3 * page);
    printf("Done!\n");
    DumpState(TestArea);

    printf("Freeing region2...\n");
    KrnFreePages(region2, 4 * page);
    printf("Done!\n");
    DumpState(TestArea);

    printf("Allocating region1 (one read-write page)...\n");
    region1 = KrnAllocPages(NULL, page, MEMF_FAST);
    printf("region1 at 0x%p\n", region1);
    DumpState(TestArea);

    printf("Freeing region1...\n");
    KrnFreePages(region1, page);
    printf("Done!\n");
    DumpState(TestArea);

    printf("Now we'll try to fragment the memory\n");

    printf("Allocating region1 (2 pages)...\n");
    region1 = KrnAllocPages(NULL, 2 * page, MEMF_FAST);
    printf("region1 at 0x%p\n", region1);
    DumpState(TestArea);

    printf("Allocating region2 (3 pages)...\n");
    region2 = KrnAllocPages(NULL, 3 * page, MEMF_FAST);
    printf("region2 at 0x%p\n", region2);
    DumpState(TestArea);

    printf("Allocating region 3 (1 page)...\n");
    region3 = KrnAllocPages(NULL, page, MEMF_FAST);
    printf("Region at 0x%p\n", region3);
    DumpState(TestArea);
    
    printf("Allocating region 4 (2 pages)...\n");
    region4 = KrnAllocPages(NULL, 2 * page, MEMF_FAST);
    printf("region4 at 0x%p\n", region1);
    DumpState(TestArea);
    
    printf("Freeing region1...\n");
    KrnFreePages(region1, 2 * page);
    printf("Done!\n");
    DumpState(TestArea);

    printf("Freeing region3...\n");
    KrnFreePages(region3, page);
    printf("Done!\n");
    DumpState(TestArea);

    printf("Allocating region 3 (1 page) again...\n");
    region3 = KrnAllocPages(NULL, page, MEMF_FAST);
    printf("Region at 0x%p\n", region3);
    DumpState(TestArea);

    printf("Freeing region2...\n");
    KrnFreePages(region2, 3 * page);
    printf("Done!\n");
    DumpState(TestArea);
    
    printf("Freeing region3...\n");
    KrnFreePages(region3, page);
    printf("Done!\n");
    DumpState(TestArea);

    printf("Freeing region4...\n");
    KrnFreePages(region4, 2 * page);
    printf("Done!\n");
    DumpState(TestArea);

exit:
    if (TestArea->mh_Node.ln_Succ)
    {
	Forbid();
	Remove(&TestArea->mh_Node);
	Permit();
    }
    FreeMem(TestArea, TestLength);

#else
    printf("The test can't be built for this kernel.resource implementation\n");
#endif

    return 0;
}
示例#15
0
BOOL CM__Hidd_ColorMap__SetColors(OOP_Class *cl, OOP_Object *o,
				  struct pHidd_ColorMap_SetColors *msg)
{
    struct colormap_data    *data;
    ULONG   	    	    numnew;
    ULONG   	    	    i, col_idx;
    HIDDT_Color     	    *col;
    HIDDT_PixelFormat 	    *pf;

    data = OOP_INST_DATA(cl, o);

    numnew = msg->firstColor + msg->numColors;
    
    /* See if there is enpugh space in the array  */
    
    if (numnew > data->clut.entries)
    {
     	/* Reallocate and copy */
	HIDDT_Color *newmap;
	
	newmap = AllocMem(sizeof (*newmap) * numnew, MEMF_ANY);
	if (NULL == newmap)
	    return FALSE;
	    
	memcpy(newmap, data->clut.colors, sizeof (*newmap) * data->clut.entries);
	
	FreeMem(data->clut.colors, sizeof (*newmap) * data->clut.entries);
	
	data->clut.colors  = newmap;
	data->clut.entries = numnew;
    }
     
    /* Insert the new colors */
    col_idx = msg->firstColor;
    col = &data->clut.colors[msg->firstColor];
    pf = (HIDDT_PixelFormat *)msg->pixFmt;
    
    for (i = 0; i < msg->numColors; i ++)
    {    
    	/* Set the color */
	*col = msg->colors[i];
	
	/* Set the pixval using the supplied pixel format */
	if (IS_TRUECOLOR(pf))
	{
	    /* Map the color to a HIDDT_Pixel */
	    msg->colors[i].pixval = col->pixval = int_map_truecolor(col, pf);
	
	}
	else
	{
	    msg->colors[i].pixval = col->pixval = (HIDDT_Pixel)col_idx;
	}
	
/*	bug("ColMap::SetColors: col %d (%x %x %x %x) mapped to %x\n"
		, col_idx
		, col->red, col->green, col->blue, col->alpha
		, msg->colors[i].pixval);
	
*/

	col ++;
	col_idx ++;
    }
    
    return TRUE;
}
示例#16
0
AROS_UFH3(void, packet_reply,
          AROS_UFHA(struct ph_mount *, mount,     A1),
          AROS_UFHA(APTR,              dummy,   A5),
          AROS_UFHA(struct ExecBase *, SysBase, A6)) {   

    AROS_USERFUNC_INIT

    struct DosPacket *dp;
    struct ph_packet *pkt;
    struct IOFileSys *iofs;
    struct ph_handle *handle;

    /* retrieve the message and fish the packet out */
    dp = (struct DosPacket *) GetMsg(&(mount->reply_port))->mn_Node.ln_Name;
    pkt = (struct ph_packet *) dp->dp_Link;

    D(bug("[packet] got reply packet %d (%s)\n", dp->dp_Type, act_str(dp->dp_Type)));

    /* get the iofs back */
    iofs = (struct IOFileSys *) dp->dp_Arg7;

    /* dos error code comes back in Res2 */
    if (dp->dp_Res1 == DOSFALSE) {
        iofs->io_DosError = dp->dp_Res2;

        /* do any cleanup from the request (eg freeing memory) */
        switch (dp->dp_Type) {
            case ACTION_FINDINPUT:
            case ACTION_FINDOUTPUT:
            case ACTION_FINDUPDATE:
                FreeMem((APTR) BADDR(dp->dp_Arg1), sizeof(struct ph_handle));
                break;

            case ACTION_SAME_LOCK:
                /* DOSFALSE & no error means the locks are different */
                if (iofs->io_DosError == 0)
                    iofs->io_Union.io_SAME_LOCK.io_Same = LOCK_DIFFERENT;
                break;

            case ACTION_PARENT:
                /* no error means they tried to go up past the root. The
                 * packet system allows this, IOFS does not */
                if (iofs->io_DosError == 0)
                    iofs->io_DosError = ERROR_OBJECT_NOT_FOUND;
                break;

            /* a zero result is not an error for the following three packet
             * types. We shouldn't really be here */
            case ACTION_SEEK:
                iofs->io_Union.io_SEEK.io_Offset = dp->dp_Res1;
                iofs->io_DosError = 0;
                break;
            case ACTION_READ:
        	iofs->io_Union.io_READ.io_Length = dp->dp_Res1; 
        	iofs->io_DosError = 0;
        	break;
            case ACTION_SET_FILE_SIZE:
                iofs->io_DosError = 0;
                break;
        }

        /* kill the packet */
        DeletePool(pkt->pool);

        D(bug("[packet] returning error %ld\n", iofs->io_DosError));

        /* and tell them */
        ReplyMsg((APTR) iofs);

        return;
    }

    /* no error */
    iofs->io_DosError = 0;
    
    /* populate the iofs with the results. note that for packets that only
     * return success/failure we have nothing to do, so they're not listed
     * here */
    switch (dp->dp_Type) {

        case ACTION_COPY_DIR:
        case ACTION_COPY_DIR_FH:
        case ACTION_LOCATE_OBJECT:
        case ACTION_PARENT:
        case ACTION_PARENT_FH:
            handle = (struct ph_handle *) AllocMem(sizeof(struct ph_handle), MEMF_PUBLIC | MEMF_CLEAR);
            if (handle == NULL) {
                iofs->io_DosError = ERROR_NO_FREE_STORE;
                break;
            }

            /* we'll need the lock they gave us for future operations */
            handle->actual = (void *) dp->dp_Res1;
            handle->is_lock = TRUE;
            handle->mount = mount;

            iofs->IOFS.io_Unit = (struct Unit *) handle;

            break;

        case ACTION_FINDINPUT:
        case ACTION_FINDOUTPUT:
        case ACTION_FINDUPDATE: {
            /* handlers return "internal data" (typically a lock, though we
             * can't assume that) in fh_Arg1. we need to keep it for later
             * filehandle operations.
             * the calls that need this data (e.g. ACTION_READ/WRITE/SEEK)
             * take it directly in dp_Arg1 */
            handle = (struct ph_handle *) BADDR(dp->dp_Arg1);
            handle->actual = (void *) handle->fh.fh_Arg1;
            handle->is_lock = FALSE;
            handle->mount = mount;

            iofs->IOFS.io_Unit = (struct Unit *) handle;

            break;
        }

        case ACTION_FREE_LOCK:
        case ACTION_END:
            /* free up our data */
            handle = (struct ph_handle *) iofs->IOFS.io_Unit;
            FreeMem((APTR) handle, sizeof(struct ph_handle));
            iofs->IOFS.io_Unit = NULL;
            break;

        case ACTION_READ:
            if (dp->dp_Res1 == -1)
        	iofs->io_DosError = dp->dp_Res2;
            iofs->io_Union.io_READ.io_Length = dp->dp_Res1;
            break;

        case ACTION_WRITE:
            iofs->io_Union.io_WRITE.io_Length = dp->dp_Res1;
            break;

        case ACTION_SEEK:
            if (dp->dp_Res1 == -1)
                iofs->io_DosError = dp->dp_Res2;
            else
                iofs->io_Union.io_SEEK.io_Offset = dp->dp_Res1;
            break;

        case ACTION_SET_FILE_SIZE:
            if (dp->dp_Res1 == -1)
                iofs->io_DosError = dp->dp_Res2;
            break;

        case ACTION_SAME_LOCK:
            iofs->io_Union.io_SAME_LOCK.io_Same = LOCK_SAME;
            break;

        case ACTION_EXAMINE_OBJECT:
        case ACTION_EXAMINE_FH: {
            struct FileInfoBlock *fib = (struct FileInfoBlock *) BADDR(dp->dp_Arg2);
            struct ExAllData *ead = iofs->io_Union.io_EXAMINE.io_ead;
            ULONG size = iofs->io_Union.io_EXAMINE.io_Size;
            ULONG mode = iofs->io_Union.io_EXAMINE.io_Mode;
            ULONG comment_len = 0, filename_len = 0;

            iofs->io_DirPos = fib->fib_DiskKey;

            /* make sure we have enough room for everything that came back */
            if (size < sizeof(struct ExAllData) +
                       (mode >= ED_COMMENT ? (comment_len = fib->fib_Comment[0]) : 0) +
                       (mode >= ED_NAME    ? (filename_len = fib->fib_FileName[0]) : 0)) {
                iofs->io_DosError = ERROR_BUFFER_OVERFLOW;
                FreeMem(fib, sizeof(struct FileInfoBlock));
                break;
            }

            /* copy stuff from the fib to the ead */
            switch (mode) {
                case ED_OWNER:
                    ead->ed_OwnerUID = fib->fib_OwnerUID;
                    ead->ed_OwnerGID = fib->fib_OwnerGID;

                case ED_COMMENT:
                    /* store the comment in the spare space after the ead and
                     * the filename */
                    ead->ed_Comment = (UBYTE *) ead + sizeof(struct ExAllData) + filename_len + 1;
                    strcpy(ead->ed_Comment,
                        mkcstr(pkt->pool, fib->fib_Comment));

                case ED_DATE:
                    ead->ed_Days = fib->fib_Date.ds_Days;
                    ead->ed_Mins = fib->fib_Date.ds_Minute;
                    ead->ed_Ticks = fib->fib_Date.ds_Tick;

                case ED_PROTECTION:
                    ead->ed_Prot = fib->fib_Protection;
                    
                case ED_SIZE:
                    ead->ed_Size = fib->fib_Size;

                case ED_TYPE:
                    ead->ed_Type = fib->fib_EntryType;

                case ED_NAME:
                    /* store the name in the spare space after the ead */
                    ead->ed_Name = (UBYTE *) ead + sizeof(struct ExAllData);
                    strcpy(ead->ed_Name, mkcstr(pkt->pool, fib->fib_FileName));
               
                case 0:
                    ead->ed_Next = NULL;
                    break;

                default:
                    iofs->io_DosError = ERROR_BAD_NUMBER;
                    break;
            }

            FreeMem(fib, sizeof(struct FileInfoBlock));

            break;
        }

        case ACTION_EXAMINE_NEXT: {
            struct FileInfoBlock *fib = iofs->io_Union.io_EXAMINE_NEXT.io_fib;
            strcpy(fib->fib_FileName, mkcstr(pkt->pool, fib->fib_FileName));
            strcpy(fib->fib_Comment, mkcstr(pkt->pool, fib->fib_Comment));
            break;
        }

        case ACTION_IS_FILESYSTEM:
            iofs->io_Union.io_IS_FILESYSTEM.io_IsFilesystem = TRUE;
            break;

        case ACTION_CREATE_DIR:
            handle = (struct ph_handle *) AllocMem(sizeof(struct ph_handle), MEMF_PUBLIC | MEMF_CLEAR);
            if (handle == NULL) {
                iofs->io_DosError = ERROR_NO_FREE_STORE;
                break;
            }

            /* we'll need the lock they gave us for future operations */
            handle->actual = (void *) dp->dp_Res1;
            handle->is_lock = TRUE;
            handle->mount = mount;

            iofs->IOFS.io_Unit = (struct Unit *) handle;

            break;

        case ACTION_READ_LINK:
            iofs->io_Union.io_READ_SOFTLINK.io_Size = dp->dp_Res1;
            iofs->io_DosError = dp->dp_Res1 < 0 ? dp->dp_Res2 : 0;
            break;

        case ACTION_MORE_CACHE:
            iofs->io_Union.io_MORE_CACHE.io_NumBuffers = dp->dp_Res1;
    }

    /* done with the packet */
    DeletePool(pkt->pool);

    /* send it back */
    ReplyMsg((APTR) iofs);

    AROS_USERFUNC_EXIT
}
示例#17
0
文件: memory.c 项目: akadata/IanOS
//===============================================================================
// Allocate some kernel memory from the heap. sizeRequested = amount to allocate
// Returns in RAX address of allocated memory.
//===============================================================================
void *AllocKMem(size_t sizeRequested)
{
	return (AllocMem(sizeRequested, firstFreeKMem));
}
示例#18
0
int download(void) {
    int cnt,freedlonly=FALSE, global = 0, matchall = 0;
    char *nextfile,*nextnext;
    struct Fil *filpek;
    struct TransferFiles *tf;
    if(Servermem->inne[nodnr].upload+1==0) {
        puttekn("\r\n\nVARNING!! Uploads = -1",-1);
        return(0);
    }
    if(Servermem->cfg.uldlratio[Servermem->inne[nodnr].status] && Servermem->cfg.uldlratio[Servermem->inne[nodnr].status] < (Servermem->inne[nodnr].download+1)/(Servermem->inne[nodnr].upload+1)) {
        sprintf(outbuffer,"\r\n\nDu måste ladda upp en fil per %d filer du laddar ner.\r\n",Servermem->cfg.uldlratio[Servermem->inne[nodnr].status]);
        puttekn(outbuffer,-1);
        puttekn("Endast filer med fri download tillåts.\n\r",-1);
        freedlonly=TRUE;
    }
    if(area2==-1) {
        puttekn("\r\n\nDu befinner dig inte i någon area!\r\n",-1);
        return(0);
    }
    if((!global && Servermem->areor[area2].flaggor & AREA_NODOWNLOAD) && (Servermem->inne[nodnr].status < Servermem->cfg.st.laddaner)) {
        puttekn("\n\n\rDu har ingen rätt att ladda ner från den här arean!\n\r",-1);
        return(0);
    }
    if(!argument[0]) {
        puttekn("\r\n\nSkriv: Download <filnamn> [<filnamn> [<filnamn> [...]]]\r\n",-1);
        return(0);
    }
    nextfile=argument;
    if(nextfile[0] == '-')
    {
        puttekn("\r\n\nTest\r\n",-1);
        if(nextfile[1] == 'g' || nextfile[1] == 'G')
            global = 1;

        if(nextfile[1] == 'a' || nextfile[1] == 'A')
            matchall = 1;

        if(!global && !matchall)
        {
            puttekn("\r\n\nOkänd option, bara -A eller -G stödjs.\r\n",-1);
            return(0);
        }

        nextfile=hittaefter(nextfile);
    }

    nextnext=hittaefter(nextfile);
    puttekn("\n\n\r",-1);
    NewList((struct List *)&tf_list);
    while(nextfile[0])
    {
        for(cnt=0; nextfile[cnt]!=' ' && nextfile[cnt]!=0; cnt++);
        nextfile[cnt]=0;
        if(!global && !(filpek=parsefil(nextfile,area2))) {
            sprintf(outbuffer,"Finns ingen fil som matchar \"%s\"\n\r",nextfile);
            puttekn(outbuffer,-1);
            nextfile=nextnext;
            nextnext=hittaefter(nextnext);
            continue;
        }
        if(!filpek && global && !(filpek=parsefilallareas(nextfile)))
        {
            sprintf(outbuffer,"Finns ingen fil som matchar \"%s\"\n\r",nextfile);
            puttekn(outbuffer,-1);
            nextfile=nextnext;
            nextnext=hittaefter(nextnext);
            continue;
        }

        if(filpek->status>Servermem->inne[nodnr].status && Servermem->inne[nodnr].status<Servermem->cfg.st.laddaner)
        {
            sprintf(outbuffer,"Du har ingen rätt att ladda ner %s!\n\r",filpek->namn);
            puttekn(outbuffer,-1);
            nextfile=nextnext;
            nextnext=hittaefter(nextnext);
            continue;
        }
        if(freedlonly && !(filpek->flaggor & FILE_FREEDL))
        {
            nextfile=nextnext;
            nextnext=hittaefter(nextnext);
            continue;
        }
        if(!(tf=(struct TransferFiles *)AllocMem(sizeof(struct TransferFiles),MEMF_CLEAR))) {
            puttekn("Kunde inte allokera en TransferFiles-struktur\n\r",-1);
            nextfile=nextnext;
            nextnext=hittaefter(nextnext);
            continue;
        }
        sprintf(tf->path,"%s%s",Servermem->areor[area2].dir[filpek->dir],filpek->namn);
        tf->filpek=filpek;
        AddTail((struct List *)&tf_list,(struct Node *)tf);
        sprintf(outbuffer,"Skickar filen %s. Storlek: %d %s\r\n",filpek->namn,filpek->size,(filpek->flaggor & FILE_FREEDL) ? "(Fri download)" : "");
        puttekn(outbuffer,-1);
        nextfile=nextnext;
        nextnext=hittaefter(nextnext);
    }
    if(!tf_list.mlh_Head->mln_Succ) {
        puttekn("\n\rInga filer att skicka.\n\r",-1);
        return(0);
    }
    Servermem->action[nodnr] = DOWNLOAD;
    Servermem->varmote[nodnr] = area2;
    Servermem->vilkastr[nodnr] = NULL;
    sendbinfile();
    if(Servermem->cfg.logmask & LOG_DOWNLOAD) {
        for(tf=(struct TransferFiles *)tf_list.mlh_Head; tf->node.mln_Succ; tf=(struct TransferFiles *)tf->node.mln_Succ)
            if(tf->sucess) {
                LogEvent(USAGE_LOG, INFO, "%s laddar ner %s (%d cps)",
                         getusername(inloggad), tf->filpek->namn, tf->cps);
            }
    }
    for(tf=(struct TransferFiles *)tf_list.mlh_Head; tf->node.mln_Succ; tf=(struct TransferFiles *)tf->node.mln_Succ) {
        if(tf->sucess) {
            if(!(tf->filpek->flaggor & FILE_FREEDL)) Servermem->inne[nodnr].download++;
            Statstr.dl++;
            raisefiledl(tf->filpek);
            sprintf(outbuffer,"%s, %d cps\n\r",tf->filpek->namn,tf->cps);
            puttekn(outbuffer,-1);
        } else {
            sprintf(outbuffer,"%s misslyckades.\n\r",tf->filpek->namn);
            puttekn(outbuffer,-1);
        }
    }
    while(tf=(struct TransferFiles *)RemHead((struct List *)&tf_list))
        FreeMem(tf,sizeof(struct TransferFiles));

    if(carrierdropped()) return(1);
    else return(0);
}
示例#19
0
/*
==================
DividePlane
==================
*/
static void
DividePlane(surface_t *in, plane_t *split, surface_t **front,
	    surface_t **back)
{
    face_t *facet, *next;
    face_t *frontlist, *backlist;
    face_t *frontfrag, *backfrag;
    surface_t *news;
    plane_t *inplane;

    inplane = &pPlanes[in->planenum];
    *front = *back = NULL;

    // parallel case is easy
    if (VectorCompare(inplane->normal, split->normal)) {
	// check for exactly on node
	if (inplane->dist == split->dist) {
	    facet = in->faces;
	    in->faces = NULL;
	    in->onnode = true;

	    // divide the facets to the front and back sides
	    news = AllocMem(SURFACE, 1, true);
	    *news = *in;

	    // Prepend each face in facet list to either in or news lists
	    for (; facet; facet = next) {
		next = facet->next;
		if (facet->planeside == 1) {
		    facet->next = news->faces;
		    news->faces = facet;
		} else {
		    facet->next = in->faces;
		    in->faces = facet;
		}
	    }

	    if (in->faces)
		*front = in;
	    else
		FreeMem(in, SURFACE, 1);

	    if (news->faces)
		*back = news;
	    else
		FreeMem(news, SURFACE, 1);

	    return;
	}

	if (inplane->dist > split->dist)
	    *front = in;
	else
	    *back = in;
	return;
    }
// do a real split.  may still end up entirely on one side
// OPTIMIZE: use bounding box for fast test
    frontlist = NULL;
    backlist = NULL;

    for (facet = in->faces; facet; facet = next) {
	next = facet->next;
	SplitFace(facet, split, &frontfrag, &backfrag);
	if (frontfrag) {
	    frontfrag->next = frontlist;
	    frontlist = frontfrag;
	}
	if (backfrag) {
	    backfrag->next = backlist;
	    backlist = backfrag;
	}
    }

    // if nothing actually got split, just move the in plane
    if (frontlist == NULL) {
	*back = in;
	in->faces = backlist;
	return;
    }

    if (backlist == NULL) {
	*front = in;
	in->faces = frontlist;
	return;
    }

    // stuff got split, so allocate one new plane and reuse in
    news = AllocMem(SURFACE, 1, true);
    *news = *in;
    news->faces = backlist;
    *back = news;

    in->faces = frontlist;
    *front = in;

    // recalc bboxes and flags
    CalcSurfaceInfo(news);
    CalcSurfaceInfo(in);
}
示例#20
0
int upload(void) {	/* Ändrad för nikfiles.data 960707 JÖ */
    int area,ret,editret,dirnr;
    long tid;
    struct EditLine *el;
    FILE *fp;
    __aligned struct FileInfoBlock info;
    struct Fil *allokpek;
    char nikfilename[100],errbuff[100],filnamn[50],tmpfullname[100], outbuffer[81];
    UBYTE tn;
    struct TransferFiles *tf;

    if(Servermem->cfg.ar.preup1) sendautorexx(Servermem->cfg.ar.preup1);
    if(area2==-1) {
        puttekn("\r\nI vilken area? ",-1);
    } else {
        sprintf(outbuffer,"\r\nI vilken area? (<RETURN> för %s)",Servermem->areor[area2].namn);
        puttekn(outbuffer,-1);
    }
    if(getstring(EKO,40,NULL)) return(1);
    if((area=parsearea(inmat))==-1) {
        puttekn("\n\rFinns ingen sådan area!\n\r",-1);
        return(0);
    } else if(area==-3) {
        if(area2==-1) return(0);
        area=area2;
    }
    if(!arearatt(area, inloggad, &Servermem->inne[nodnr])) {
        puttekn("\n\rFinns ingen sådan area!\n\r",-1);
        return(0);
    }
    if((Servermem->areor[area].flaggor & AREA_NOUPLOAD) && (Servermem->inne[nodnr].status < Servermem->cfg.st.laddaner)) {
        puttekn("\n\n\rDu har ingen rätt att ladda upp till den arean!\n\r",-1);
        return(0);
    }
    Servermem->action[nodnr] = UPLOAD;
    Servermem->varmote[nodnr] = area;
    Servermem->vilkastr[nodnr] = NULL;
    if(ret=recbinfile(Servermem->cfg.ultmp)) {
        while(tf=(struct TransferFiles *)RemHead((struct List *)&tf_list))
            FreeMem(tf,sizeof(struct TransferFiles));
        if(carrierdropped()) return(1);
        return(0);
    }

    /* printf("Filnamn = %s\n",FilePart(tf->Filnamn));
    printf("Cps = %d\n\n",tf->cps); */

    for(tf=(struct TransferFiles *)tf_list.mlh_Head; tf->node.mln_Succ; tf=(struct TransferFiles *)tf->node.mln_Succ) {
        strcpy(xprfilnamn,tf->Filnamn);
        if(stcgfn(filnamn,xprfilnamn)>40) puttekn("\r\nVARNING! Filnamnet större än 40 tecken!\r\n",-1);
        if(!filnamn[0]) {
            puttekn("\r\n\nHmm... Filen har inget namn. Skriv ett brev till sysop.\r\n",-1);
            continue;
        }
        if(!valnamn(filnamn,area,errbuff)) {
            for(;;) {
                puttekn(errbuff,-1);
                puttekn("\r\nNytt namn: ",-1);
                if(getstring(EKO,40,NULL)) {
                    DeleteFile(xprfilnamn);
                    return(1);
                }
                if(!inmat[0]) continue;
                if(valnamn(inmat,area,errbuff)) break;
            }
            strcpy(filnamn,inmat);
            sprintf(tmpfullname,"%s%s",Servermem->cfg.ultmp,filnamn);
            if(!Rename(xprfilnamn,tmpfullname)) {
                sprintf(outbuffer,"\r\n\nKunde inte döpa om filen från '%s'\r\ntill '%s'.\r\n",xprfilnamn,tmpfullname);
                puttekn(outbuffer,-1);
                DeleteFile(xprfilnamn);
                continue;
            }
        } else strcpy(tmpfullname,xprfilnamn);
        if(!(allokpek=(struct Fil *)AllocMem(sizeof(struct Fil),MEMF_PUBLIC | MEMF_CLEAR))) {
            puttekn("\r\n\nKunde inte allokera minne för filen!\r\n",-1);
            continue;
        }
        time(&tid);
        allokpek->tid=allokpek->validtime=tid;
        allokpek->uppladdare=inloggad;
        if(dfind(&info,tmpfullname,0)) {
            sprintf(outbuffer,"\r\nHittar inte filen %s!\r\n",tmpfullname);
            puttekn(outbuffer,-1);
            FreeMem(allokpek,sizeof(struct Fil));
            continue;
        }
        allokpek->size=info.fib_Size;

        sprintf(outbuffer,"\r\n\r\nFilnamn: %s", filnamn);
        puttekn(outbuffer,-1);
        puttekn("\r\nVilken status ska behövas för att ladda ner filen? (0)",-1);
        if(getstring(EKO,3,NULL)) {
            FreeMem(allokpek,sizeof(struct Fil));
            return(1);
        }
        allokpek->status=atoi(inmat);
        if(Servermem->inne[nodnr].status >= Servermem->cfg.st.filer) {
            puttekn("\n\rSka filen valideras? ",-1);
            if(jaellernej('j','n',1)) puttekn("Ja",-1);
            else {
                puttekn("Nej",-1);
                allokpek->flaggor|=FILE_NOTVALID;
            }
            puttekn("\n\rSka filen ha fri download? ",-1);
            if(jaellernej('j','n',2)) {
                puttekn("Ja",-1);
                allokpek->flaggor|=FILE_FREEDL;
            } else puttekn("Nej",-1);
        } else if(Servermem->cfg.cfgflags & NICFG_VALIDATEFILES) allokpek->flaggor|=FILE_NOTVALID;
        sendfile("NiKom:Texter/Nyckelhjälp.txt");
        puttekn("\r\nVilka söknycklar ska filen ha? (? för att få en lista)\r\n",-1);
        if(editkey(allokpek->nycklar)) {
            FreeMem(allokpek,sizeof(struct Fil));
            return(1);
        }
        puttekn("\r\nBeskrivning:\r\n",-1);
        if(getstring(EKO,70,NULL)) {
            FreeMem(allokpek,sizeof(struct Fil));
            return(1);
        }
        strcpy(allokpek->beskr,inmat);
        dirnr = ChooseDirectoryInFileArea(
                    area, allokpek->nycklar, allokpek->size);
        if(dirnr==-1) {
            puttekn("\r\n\nKunde inte hitta något lämpligt directory för filen!\r\n",-1);
            DeleteFile(tmpfullname);
            FreeMem(allokpek,sizeof(struct Fil));
            continue;
        }
        allokpek->dir=dirnr;
        strcpy(allokpek->namn,filnamn);
        sprintf(inmat,"%s %s",tmpfullname,Servermem->areor[area].dir[dirnr]);
        argument=inmat;
        sendrexx(10);
        AddTail((struct List *)&Servermem->areor[area].ar_list,(struct Node *)allokpek);
        if(writefiles(area)) {
            puttekn("\r\n\nKunde inte skriva till datafilen\r\n",-1);

        }

        Servermem->inne[nodnr].upload++;
        Statstr.ul++;
        if(Servermem->cfg.logmask & LOG_UPLOAD) {
            LogEvent(USAGE_LOG, INFO, "%s laddar upp %s",
                     getusername(inloggad), allokpek->namn);
        }
        if(Servermem->cfg.ar.postup1) sendautorexx(Servermem->cfg.ar.postup1);
        puttekn("\r\n\nVill du skriva en längre beskrivning? (J/n) ",-1);
        while((tn=gettekn())!='j' && tn!='J' && tn!='n' && tn!='N' && tn!=13);
        if(tn=='j' || tn=='J') {
            puttekn("\r\n\nOk, går in i editorn.\r\n",-1);
            if((editret=edittext(NULL))==1) return(1);
            else if(editret==2) continue;
            sprintf(nikfilename,"%slongdesc/%s.long",Servermem->areor[area].dir[dirnr],filnamn);
            if(!(fp=fopen(nikfilename,"w"))) {
                puttekn("\r\n\nKunde inte öppna longdesc-filen\r\n",-1);
                freeeditlist();
                continue;
            }
            for(el=(struct EditLine *)edit_list.mlh_Head; el->line_node.mln_Succ; el=(struct EditLine *)el->line_node.mln_Succ) {
                if(fputs(el->text,fp)) {
                    freeeditlist();
                    fclose(fp);
                    continue;
                }
                fputc('\n',fp);
            }
            freeeditlist();
            fclose(fp);
            puttekn("\r\n",-1);
            allokpek->flaggor|=FILE_LONGDESC;
            updatefile(area,allokpek);
        }
    }

    while(tf=(struct TransferFiles *)RemHead((struct List *)&tf_list))
        FreeMem(tf,sizeof(struct TransferFiles));

    return(0);
}
示例#21
0
文件: ini.c 项目: mingpen/OpenNT
BOOLEAN
CreateIniFileReference(
    PWSTR Name,
    PINI_FILE_REFERENCE *ReturnedReference
    )
{
    PINI_FILE_REFERENCE p;
    PINI_SECTION_REFERENCE p1;
    PINI_VARIABLE_REFERENCE p2;
    PWSTR SectionName;
    PWSTR VariableName;
    PWSTR VariableValue;
    UNICODE_STRING UnicodeString;
    PLIST_ENTRY Head, Next;
    ULONG n, n1;
    BOOLEAN Result;
    HANDLE FindHandle;
    WIN32_FIND_DATA FindFileData;

    p = FindIniFileReference( Name );
    if (p != NULL) {
        *ReturnedReference = p;
        return TRUE;
        }

    p = AllocMem( sizeof( *p ) );
    if (p == NULL) {
        return FALSE;
        }

    p->Name = Name;
    InitializeListHead( &p->SectionReferencesListHead );
    InsertTailList( &IniReferenceListHead, &p->Entry );
    FindHandle = FindFirstFile( Name, &FindFileData );
    if (FindHandle == INVALID_HANDLE_VALUE) {
        p->Created = TRUE;
        *ReturnedReference = p;
        return TRUE;
        }
    FindClose( FindHandle );
    p->BackupLastWriteTime = FindFileData.ftLastWriteTime;

    GrowTemporaryBuffer( n = 0xF000 );
    SectionName = TemporaryBuffer;

    Result = TRUE;
    n1 = GetPrivateProfileStringW( NULL,
                                   NULL,
                                   L"",
                                   SectionName,
                                   n,
                                   Name
                                 );
    if (n1 == 0 || n1 == n-2) {
        Result = FALSE;
        }
    else {
        while (*SectionName != UNICODE_NULL) {
            p1 = AllocMem( sizeof( *p1 ) );
            if (p1 == NULL) {
                Result = FALSE;
                break;
                }

            RtlInitUnicodeString( &UnicodeString, SectionName );
            p1->Name = AddName( &UnicodeString );
            if (FindIniSectionReference( p, p1->Name, FALSE )) {
                FreeMem( &p1 );
                }
            else {
                InitializeListHead( &p1->VariableReferencesListHead );
                InsertTailList( &p->SectionReferencesListHead, &p1->Entry );
                }
            while (*SectionName++ != UNICODE_NULL) {
                }
            }
        }

    VariableName = TemporaryBuffer;
    Head = &p->SectionReferencesListHead;
    Next = Head->Flink;
    while (Result && (Head != Next)) {
        p1 = CONTAINING_RECORD( Next, INI_SECTION_REFERENCE, Entry );
        n1 = GetPrivateProfileSectionW( p1->Name,
                                        VariableName,
                                        n,
                                        Name
                                      );
        if (n1 == n-2) {
            Result = FALSE;
            break;
            }

        while (*VariableName != UNICODE_NULL) {
            VariableValue = VariableName;
            while (*VariableValue != UNICODE_NULL && *VariableValue != L'=') {
                VariableValue += 1;
                }

            if (*VariableValue != L'=') {
                Result = FALSE;
                break;
                }
            *VariableValue++ = UNICODE_NULL;

            p2 = AllocMem( sizeof( *p2 ) + ((wcslen( VariableValue ) + 1) * sizeof( WCHAR )) );
            if (p2 == NULL) {
                Result = FALSE;
                break;
                }
            RtlInitUnicodeString( &UnicodeString, VariableName );
            p2->Name = AddName( &UnicodeString );
            p2->OriginalValue = (PWSTR)(p2+1);
            wcscpy( p2->OriginalValue, VariableValue );
            InsertTailList( &p1->VariableReferencesListHead, &p2->Entry );

            VariableName = VariableValue;
            while (*VariableName++ != UNICODE_NULL) {
                }
            }

        Next = Next->Flink;
        }


    if (Result) {
        *ReturnedReference = p;
        }
    else {
        DestroyIniFileReference( p );
        }

    return Result;
}
示例#22
0
int recbinfile(char *dir) {
    int xprreturkod;
    char zmodeminit[100];

    ulfiles = 0;
    if(access(dir,0)) {
        puttekn("\r\nDirectoryt finns inte!\r\n",-1);
        return 2;
    }

    if(Servermem->cfg.diskfree != 0
            && !HasPartitionEnoughFreeSpace(dir, Servermem->cfg.diskfree)) {
        puttekn("\r\nTyvärr, gränsen för hur full disken får bli har överskridits!\r\n",-1);
        return 2;
    }

    if(Servermem->cfg.ar.preup2) {
        sendautorexx(Servermem->cfg.ar.preup2);
    }
    sprintf(zmodeminit,"%s%s",zinitstring,dir);
    if(!(XProtocolBase = (struct Library *) OpenLibrary("xprzmodem.library", 0L))) {
        puttekn("\r\n\nKunde inte öppna xprzmodem.library!\r\n",-1);
        return 2;
    }
    if(!(xio = (struct XPR_IO *)
               AllocMem(sizeof(struct XPR_IO), MEMF_PUBLIC | MEMF_CLEAR))) {
        puttekn("\r\n\nKunde inte allokera en io-struktur\r\n",-1);
        CloseLibrary(XProtocolBase);
        return 2;
    }
    NewList((struct List *)&tf_list);

    puttekn("\r\nDu kan börja sända med Zmodem. Du kan nu skicka fler filer!",-1);
    puttekn("\r\nTryck Ctrl-X några gånger för att avbryta.\r\n",-1);
    AbortIO((struct IORequest *)serreadreq);
    WaitIO((struct IORequest *)serreadreq);
    if(!CheckIO((struct IORequest *)inactivereq)) {
        AbortIO((struct IORequest *)inactivereq);
        WaitIO((struct IORequest *)inactivereq);
    }
    xpr_setup(xio);
    xio->xpr_filename = zmodeminit;
    XProtocolSetup(xio);
    xprreturkod = XProtocolReceive(xio);
    Delay(30);
    XProtocolCleanup(xio);
    CloseLibrary(XProtocolBase);
    if(!CheckIO((struct IORequest *)serreadreq)) {
        AbortIO((struct IORequest *)serreadreq);
        WaitIO((struct IORequest *)serreadreq);
        printf("Serreadreq avbruten!!\n");
    }
    if(!CheckIO((struct IORequest *)timerreq)) {
        AbortIO((struct IORequest *)timerreq);
        WaitIO((struct IORequest *)timerreq);
        printf("Timerreq avbruten!!\n");
    }
    FreeMem(xio,sizeof(struct XPR_IO));
    Delay(100);
    serchangereq->IOSer.io_Command=CMD_CLEAR;
    DoIO((struct IORequest *)serchangereq);
    serchangereq->IOSer.io_Command=CMD_FLUSH;
    DoIO((struct IORequest *)serchangereq);
    serreqtkn();
    updateinactive();
    if(Servermem->cfg.ar.postup2) {
        sendautorexx(Servermem->cfg.ar.postup2);
    }

    if(ulfiles > 0) {
        puttekn("\r\n\nÖverföringen lyckades.\r\n",-1);
        return 0;
    }
    else {
        puttekn("\r\n\nÖverföringen misslyckades.\r\n",-1);
        return 2;
    }
}
示例#23
0
void processMsg(void)
{
  struct IntuiMessage *msg;
  struct DropMessage *dm;
  int    source,target;

  while(!ende)
  {
    WaitPort(win->UserPort);
    while((msg = GTD_GetIMsg(win->UserPort)) != 0)
    {
      imsg = *msg;

      if (imsg.Class == IDCMP_OBJECTDROP)
      {
        if ((dm = imsg.IAddress) != 0)
        {
          if (!dm->dm_Object.od_Owner && dm->dm_Target)
          {
            target = dm->dm_Target->GadgetID;
            switch(target)
            {
              case 1:
              case 2:
                source = dm->dm_Gadget->GadgetID;
                if (source < 3)
                {
                  source--;  target--;
                  GT_SetGadgetAttrs(lvgad[0],win,NULL,GTLV_Labels,~0L,TAG_END);
                  GT_SetGadgetAttrs(lvgad[1],win,NULL,GTLV_Labels,~0L,TAG_END);
                  if (target)
                    MoveTo(dm->dm_Object.od_Object,&list[source],dm->dm_SourceEntry,&list[target],dm->dm_TargetEntry);
                  else
                  {
                    Remove(dm->dm_Object.od_Object);
                    AddTail(&list[target],dm->dm_Object.od_Object);
                  }
                  GT_SetGadgetAttrs(lvgad[0],win,NULL,GTLV_Labels,&list[0],TAG_END);
                  GT_SetGadgetAttrs(lvgad[1],win,NULL,GTLV_Labels,&list[1],TAG_END);
                }
                else
                {
                  target--;
                  GT_SetGadgetAttrs(lvgad[target],win,NULL,GTLV_Labels,~0L,TAG_END);
                  if ((node = AllocMem(sizeof(struct Node),MEMF_CLEAR | MEMF_PUBLIC)) != 0)
                  {
                    node->ln_Name = in.in_Name;
                    InsertAt(&list[target],node,dm->dm_TargetEntry);
                  }
                  GT_SetGadgetAttrs(lvgad[target],win,NULL,GTLV_Labels,&list[target],TAG_END);
                }
                break;
              case 3:
                DisplayBeep(NULL);
                break;
              case 4:
              case 5:
                source = dm->dm_Gadget->GadgetID-1;
                GT_SetGadgetAttrs(lvgad[source],win,NULL,GTLV_Labels,~0L,TAG_END);
                if (target == 4)
                {
                  if ((node = AllocMem(sizeof(struct Node),MEMF_CLEAR | MEMF_PUBLIC)) != 0)
                  {
                    node->ln_Name = ((struct ImageNode *)dm->dm_Object.od_Object)->in_Name;
                    AddTail(&list[source],node);
                  }
                }
                else
                {
                  Remove((struct Node *)dm->dm_Object.od_Object);
                  FreeMem(dm->dm_Object.od_Object,sizeof(struct Node));
                }
                GT_SetGadgetAttrs(lvgad[source],win,NULL,GTLV_Labels,&list[source],TAG_END);
                break;
            }
          }
          else if (!dm->dm_Object.od_Owner)
          {
            DisplayBeep(NULL);   // unsupported drag?!
          }
          else if (!stricmp(dm->dm_Object.od_Owner,"dragtest"))
          {
            char t[256];

            if (GTD_GetString(&dm->dm_Object,t,256))
              ErrorRequest("I do not want a node from a clone of mine.\nEspecially, I don't like \"%s\".",t);
          }
          else if (!strcmp(dm->dm_Object.od_Owner,"intuition"))
            ErrorRequest("An object from a custom gadget?\nThat's nothing for me.",dm->dm_Object.od_Owner);
          else
            ErrorRequest("An object from %s?\nSounds interesting.",dm->dm_Object.od_Owner);
        }
        else
          DisplayBeep(NULL);
      }
      GTD_ReplyIMsg(msg);

      switch(imsg.Class)
      {
        case IDCMP_GADGETDOWN:
          break;
        case IDCMP_GADGETUP:
          switch(((struct Gadget *)imsg.IAddress)->GadgetID)
          {
            case 3:
              GT_SetGadgetAttrs(lvgad[0],win,NULL,GTLV_Labels,~0L,TAG_END);
              if ((node = AllocMem(sizeof(struct Node),MEMF_CLEAR | MEMF_PUBLIC)) != 0)
              {
                node->ln_Name = in.in_Name;
                AddTail(&list[0],node);
              }
              GT_SetGadgetAttrs(lvgad[0],win,NULL,GTLV_Labels,&list[0],TAG_END);
              break;
          }
          break;
        case IDCMP_CLOSEWINDOW:
          ende = TRUE;
          break;
      }
    }
  }
}
示例#24
0
int sendbinfile(void) {
    struct TransferFiles *tf;
    int xprreturkod,cnt=0;
    if(!(XProtocolBase=(struct Library *)OpenLibrary("xprzmodem.library",0L)))
    {
        puttekn("\r\n\nKunde inte öppna xprzmodem.library!\r\n",-1);
        return(2);
    }
    if(!(xio=(struct XPR_IO *)AllocMem(sizeof(struct XPR_IO),MEMF_PUBLIC | MEMF_CLEAR))) {
        puttekn("\r\n\nKunde inte allokera en io-struktur\r\n",-1);
        CloseLibrary(XProtocolBase);
        return(2);
    }
    puttekn("\r\nDu kan börja ta emot med Zmodem.\r\n",-1);
    puttekn("Tryck Ctrl-X några gånger för att avbryta.\r\n",-1);
    AbortIO((struct IORequest *)serreadreq);
    WaitIO((struct IORequest *)serreadreq);
    if(!CheckIO((struct IORequest *)inactivereq)) {
        AbortIO((struct IORequest *)inactivereq);
        WaitIO((struct IORequest *)inactivereq);
    }

    xpr_setup(xio);
    xio->xpr_filename=zinitstring;
    XProtocolSetup(xio);
    xio->xpr_filename="Hejhopp";
    xprreturkod=XProtocolSend(xio);
    Delay(30);
    XProtocolCleanup(xio);
    CloseLibrary(XProtocolBase);
    if(!CheckIO((struct IORequest *)serreadreq)) {
        AbortIO((struct IORequest *)serreadreq);
        WaitIO((struct IORequest *)serreadreq);
        printf("Serreadreq avbruten!!\n");
    }
    if(!CheckIO((struct IORequest *)timerreq)) {
        AbortIO((struct IORequest *)timerreq);
        WaitIO((struct IORequest *)timerreq);
        printf("Timerreq avbruten!!\n");
    }
    FreeMem(xio,sizeof(struct XPR_IO));
    Delay(100);
    serchangereq->IOSer.io_Command=CMD_CLEAR;
    DoIO((struct IORequest *)serchangereq);
    serchangereq->IOSer.io_Command=CMD_FLUSH;
    DoIO((struct IORequest *)serchangereq);
    serreqtkn();
    updateinactive();
    if(Servermem->cfg.logmask & LOG_SENDFILE) {
        for(tf=(struct TransferFiles *)tf_list.mlh_Head; tf->node.mln_Succ; tf=(struct TransferFiles *)tf->node.mln_Succ)
            if(tf->sucess) {
                LogEvent(USAGE_LOG, INFO, "Skickar filen %s till %s",
                         tf->path, getusername(inloggad));
            }
    }
    for(tf=(struct TransferFiles *)tf_list.mlh_Head; tf->node.mln_Succ; tf=(struct TransferFiles *)tf->node.mln_Succ)
        if(tf->sucess) cnt++;
    if(cnt==1) strcpy(outbuffer,"\n\n\rFörde över 1 fil.\n\n\r");
    else sprintf(outbuffer,"\n\n\rFörde över %d filer.\n\n\r",cnt);
    puttekn(outbuffer,-1);
    return(0);
}
示例#25
0
int ReadILBM (struct IFFHandle * iff,
              struct Window * window, ULONG Width, ULONG Height, UWORD Depth,
              BOOL Compression, BOOL masking)
{
    struct RastPort * rp = window->RPort;
    BYTE * planes[MAX_PLANES];
    int t,x,bit,byte,row,pen = 0,lastpen;

    printf ("ReadILBM iff=%p win=%p Size=%ldx%ld Depth=%d %s%s\n",
            iff, window, Width, Height, Depth,
            Compression ? "C":"",
            masking ? "M":""
           );

    planes[0] = AllocMem (Width*Depth + ((masking) ? Width : 0), MEMF_ANY);

    if (!planes[0])
        return FALSE;

    for (t=1; t<Depth; t++)
        planes[t] = planes[t-1] + Width;

    if (masking)
        planes[t] = planes[t-1] + Width;

    for ( ; t<MAX_PLANES; t++)
        planes[t] = NULL;

    for (row=0; row<Height; row++)
    {
        if (!ReadRow (iff, planes, Width, Depth, Compression, masking))
        {
            FreeMem (planes[0], Width*Depth + ((masking) ? Width : 0));
            return FALSE;
        }

        /* printf ("row %d, %08lx\n", row, *(ULONG*)planes[0]); */

        lastpen = -1;

        Move (rp, 0, row);

        for (x=0; x<Width; x++)
        {
            bit = 0x80 >> (x & 7);
            byte = x / 8;

            for (pen=t=0; t<Depth; t++)
                if (planes[t][byte] & bit)
                    pen |= 1L << t;

            if (lastpen == -1)
                lastpen = pen;

            /* SetAPen (rp, pen);
            WritePixel (rp, x, row); */

            if (lastpen != pen)
            {
                SetAPen (rp, lastpen);
                Draw (rp, x+1, row);
                lastpen = pen;
            }
        }

        SetAPen (rp, pen);
        Draw (rp, Width, row);
    }

    return TRUE;
}
示例#26
0
int __saveds __asm LIBCreateUser(register __d0 LONG nodnummer, register __a0 struct TagItem *taglist, register __a6 struct NiKomBase *NiKomBase)
{
	struct User *newuser;
	struct ShortUser *allokpek;
	struct Mote *motpek=(struct Mote *)NiKomBase->Servermem->mot_list.mlh_Head;
	long tid, anvnummer = -1;
	char dirnamn[100],filnamn[40], bitmap[MAXTEXTS/8];
	BPTR lock,fh;
	ULONG tmp;
	
	if(!(newuser=AllocMem(sizeof(struct User),MEMF_CLEAR | MEMF_PUBLIC))) return(-1);

	strcpy(newuser->namn,(char *)GetTagData(US_Name,NULL,taglist));
	if(newuser->namn == NULL)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}
	else
		if(NiKomBase->Servermem != NULL)
		{
			if(parsenamn(newuser->namn, NiKomBase) != -1)
			{
				FreeMem(newuser,sizeof(struct User));
				return(-3);
			}
		}
		else
		{
			sprintf(filnamn,"NiKom:Users/0/0/Data");
			if(fh=Open(filnamn, MODE_OLDFILE))
			{
				Close(fh);
				FreeMem(newuser,sizeof(struct User));
				return(-6);
			}
			anvnummer = 0;
		}

	strcpy(newuser->gata,(char *)GetTagData(US_Street,NULL,taglist));
	if(newuser->gata == NULL)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}

	strcpy(newuser->postadress,(char *)GetTagData(US_Address,NULL,taglist));
	if(newuser->postadress == NULL)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}

	strcpy(newuser->land,(char *)GetTagData(US_Country,NULL,taglist));
	if(newuser->land == NULL)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}

	strcpy(newuser->prompt,(char *)GetTagData(US_Prompt,NULL,taglist));
	if(newuser->land == NULL)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}

	strcpy(newuser->telefon,(char *)GetTagData(US_Phonenumber,NULL,taglist));
	if(newuser->telefon == NULL)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}

	strcpy(newuser->annan_info,(char *)GetTagData(US_OtherInfo,NULL,taglist));
	if(newuser->annan_info == NULL)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}

	strcpy(newuser->losen,(char *)GetTagData(US_Password,NULL,taglist));
	if(newuser->losen == NULL)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}

	tmp = GetTagData(US_Status,-1,taglist);
	if(tmp == -1)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}
	else
	{
		newuser->status = tmp;
	}

	tmp = GetTagData(US_Rader, -2,taglist);
	if(tmp == -2)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}
	else
	{
		newuser->rader = tmp;
	}

	tmp = GetTagData(US_Charset,-1,taglist);
	if(tmp == -1)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}
	else
	{
		newuser->chrset = tmp;
	}

	tmp = GetTagData(US_Flags,-1,taglist);
	if(tmp == -1)
	{
		FreeMem(newuser,sizeof(struct User));
		return(-2);
	}
	else
	{
		newuser->flaggor = tmp;
	}

	if(newuser->flaggor == -1)
		newuser->flaggor = NiKomBase->Servermem->cfg.defaultflags;

	if(newuser->rader == -1)
		newuser->rader = NiKomBase->Servermem->cfg.defaultrader;

	if(NiKomBase->Servermem->cfg.cfgflags & NICFG_CRYPTEDPASSWORDS)
		strcpy(newuser->losen, LIBCryptPassword(newuser->losen, NiKomBase));

	newuser->tot_tid = 0L;
	newuser->senast_in = 0L;
	newuser->read = 0L;
	newuser->skrivit = 0L;
	newuser->upload = 0;
	newuser->download = 0;
	newuser->loggin = 0;
	newuser->grupper = 0L;
	newuser->defarea = 0L;
	newuser->shell = 0;
	newuser->brevpek = 0;

	memset((void *)newuser->motmed, 0, MAXMOTE/8);
	memset((void *)newuser->motratt, 0, MAXMOTE/8);

	time(&tid);
	newuser->forst_in = tid;

	memset((void *)bitmap,~0,MAXTEXTS/8);

	if(anvnummer == -1)
	{
		anvnummer = ((struct ShortUser *)NiKomBase->Servermem->user_list.mlh_TailPred)->nummer+1;
		newuser->textpek = NiKomBase->Servermem->info.lowtext;
		newuser->status = NiKomBase->Servermem->cfg.defaultstatus;
		newuser->protokoll = NiKomBase->Servermem->cfg.defaultprotokoll;

		for(;motpek->mot_node.mln_Succ;motpek=(struct Mote *)motpek->mot_node.mln_Succ)
		{
			if(motpek->status & (SKRIVSTYRT | SLUTET)) BAMCLEAR(newuser->motratt,motpek->nummer);
			else BAMSET(newuser->motratt,motpek->nummer);
		}

		if(!(allokpek=(struct ShortUser *)AllocMem(sizeof(struct ShortUser),MEMF_CLEAR | MEMF_PUBLIC)))
		{
			FreeMem(newuser,sizeof(struct User));
			return(-1);
		}
		strcpy(allokpek->namn,newuser->namn);
		allokpek->nummer=anvnummer;
		allokpek->status=newuser->status;
		AddTail((struct List *)&NiKomBase->Servermem->user_list,(struct Node *)allokpek);

		if(nodnummer != -1) memcpy((void *)&NiKomBase->Servermem->inne[nodnummer],(void *)newuser,sizeof(newuser));
	}
	else
	{
		newuser->textpek = newuser->protokoll = 0;
	}

	LIBLockNiKomBase(NiKomBase);

	sprintf(dirnamn,"NiKom:Users/%d",anvnummer/100);
	if(!(lock=Lock(dirnamn,ACCESS_READ)))
		if(!(lock=CreateDir(dirnamn)))
		{
			FreeMem(newuser,sizeof(struct User));
			return(-4);
		}
	UnLock(lock);
	sprintf(dirnamn,"NiKom:Users/%d/%d",anvnummer/100,anvnummer);
	if(!(lock=Lock(dirnamn,ACCESS_READ)))
		if(!(lock=CreateDir(dirnamn)))
		{
			FreeMem(newuser,sizeof(struct User));
			return(-4);
		}
	UnLock(lock);

	sprintf(filnamn,"NiKom:Users/%d/%d/Data",anvnummer/100,anvnummer);
	if(!(fh=Open(filnamn,MODE_NEWFILE)))
	{
		FreeMem(newuser,sizeof(struct User));
		LIBUnLockNiKomBase(NiKomBase);
		return(-4);
	}
	if(Write(fh,(void *)newuser,sizeof(struct User))==-1) {
		Close(fh);
		FreeMem(newuser,sizeof(struct User));
		LIBUnLockNiKomBase(NiKomBase);
		return(-4);
	}
	Close(fh);
	sprintf(filnamn,"NiKom:Users/%d/%d/Bitmap0",anvnummer/100,anvnummer);
	if(!(fh=Open(filnamn,MODE_NEWFILE)))
	{
		FreeMem(newuser,sizeof(struct User));
		LIBUnLockNiKomBase(NiKomBase);
		return(-4);
	}
	if(Write(fh,(void *)bitmap,MAXTEXTS/8)==-1) {
		Close(fh);
		FreeMem(newuser,sizeof(struct User));
		LIBUnLockNiKomBase(NiKomBase);
		return(-4);
	}
	Close(fh);
	sprintf(filnamn,"Nikom:Users/%d/%d/.firstletter",anvnummer/100,anvnummer);
	if(!(fh=Open(filnamn,MODE_NEWFILE)))
	{
		FreeMem(newuser,sizeof(struct User));
		LIBUnLockNiKomBase(NiKomBase);
		return(-4);
	}
	Write(fh,"0",1);
	Close(fh);
	sprintf(filnamn,"Nikom:Users/%d/%d/.nextletter",anvnummer/100,anvnummer);
	if(!(fh=Open(filnamn,MODE_NEWFILE)))
	{
		FreeMem(newuser,sizeof(struct User));
		LIBUnLockNiKomBase(NiKomBase);
		return(-4);
	}
	Write(fh,"0",1);
	Close(fh);
	LIBUnLockNiKomBase(NiKomBase);
	return(anvnummer);
}
示例#27
0
文件: pr_02_1.c 项目: marojas11/MC-1
void AllocArrays ()
{
  AllocMem (mol, nMol, Mol);
}
示例#28
0
void AllocArrays ()
{
  AllocMem (mol, nMol, Mol);
  AllocMem (site, nMol * sitesMol, Site);
  AllocMem (mSite, sitesMol, MSite);
}
示例#29
0
int32_t main(int32_t argc, char **argv)
{
    char *filename, *openMode="rb";
    FILE *ADFFile;
    int32_t write=0;
    struct IOStdReq *ioreq;
    struct MsgPort *port;

    UBYTE *buffer;
    char devicebuf[256];
    char *devicename = "trackdisk.device";
    char devicenum = 0;
    int32_t i;
    int32_t starttr = 0, endtr = 79;
    int32_t sectors = 11;

    for (i = 1; i < argc;) {
	if (argv[i][0] != '-' || argv[i][2] != 0) {
	    usage();
	    exit(1);
	}
	switch (argv[i][1]) {
	 case 'h':
	    sectors = 22;
	    i++;
	    break;
	case 'd':
	    if (i+2 >= argc) {
		usage();
		exit(1);
	    }
	    devicenum = atoi(argv[i+2]);
	    sprintf(devicebuf, "%s.device", argv[i+1]);
	    devicename = devicebuf;
	    i += 3;
	    break;
	case 's':
	    if (i+1 >= argc) {
		usage();
		exit(1);
	    }
	    starttr = atoi(argv[i+1]);
	    i += 2;
	    break;
	case 'e':
	    if (i+1 >= argc) {
		usage();
		exit(1);
	    }
	    endtr = atoi(argv[i+1]);
	    i += 2;
	    break;
	case 'w':
	    if (i+1 >= argc) {
		usage();
		exit(1);
	    }
	    filename=argv[i+1];
	    write=1;
	    i += 2;
	    break;
	default:
	    usage();
	    exit(1);
	}
    }
    fprintf(stderr,"Using %s unit %d\n", devicename, devicenum);
    fprintf(stderr,"Tracks are %d sectors\n", sectors);
    fprintf(stderr,"First track %d, last track %d\n", starttr, endtr);

    buffer = AllocMem(512, MEMF_CHIP);
    if (write) {
	ADFFile = fopen(filename,openMode);

	if (!ADFFile) {
	    fprintf(stderr,"Error while opening input file\n");
	    exit (1);
	}
    }

    port = CreatePort(0, 0);
    if (port) {
	ioreq = CreateStdIO(port);
	if (ioreq) {
	    if (OpenDevice(devicename, devicenum, (struct IORequest *) ioreq, 0) == 0) {
		int32_t tr, sec;

		ioreq->io_Command = write ? CMD_WRITE : CMD_READ;
		ioreq->io_Length = 512;
		ioreq->io_Data = buffer;
		for (tr = starttr*2; tr < (endtr+1)*2; tr++) {
		    fprintf(stderr,"Track: %d\r",tr/2);
		    for (sec = 0; sec < sectors; sec++) {
			fflush(stderr);
			if (write)
			    if (fread(buffer, sizeof(UBYTE), 512, ADFFile) < 512) {
				fprintf(stderr, "Error: ADF file to short?\n");
				exit(1);
			    }
			ioreq->io_Offset = 512 * (tr * sectors + sec);
			DoIO( (struct IORequest *) ioreq);
			if (!write)
			    fwrite(buffer, sizeof(UBYTE), 512, stdout);
		    }
		}
		if (write) {		/* Make sure the last track is written to disk */
		    ioreq->io_Command = CMD_UPDATE;
		    DoIO( (struct IORequest *) ioreq);
		}
		ioreq->io_Command = TD_MOTOR;	/* Turn Disk-motor off */
		ioreq->io_Length = 0;
		DoIO( (struct IORequest *) ioreq);
		CloseDevice( (struct IORequest *) ioreq);
	    } else
		fprintf(stderr,"Unable to open %s unit %d\n", devicename, devicenum);
	    DeleteStdIO(ioreq);
	}
	DeletePort(port);
    }
    fprintf(stderr,"\n");
    FreeMem(buffer, 512);
    if (write)
	fclose (ADFFile);
    return 0;
}
示例#30
0
int recbinfile(char *dir) {
	int xprreturkod,bytesfree;
	char zmodeminit[100];
	struct InfoData *id;
	BPTR lock;

	ulfiles = 0;
	if(access(dir,0)) {
		puttekn("\r\nDirectoryt finns inte!\r\n",-1);
		return(2);
	}
	if(!(id=AllocMem(sizeof(struct InfoData),MEMF_CLEAR))) {
		puttekn("\r\nKunde inte allokera en InfoData-struktur!\r\n",-1);
		return(2);
	}
	if(!(lock=Lock(dir,ACCESS_READ))) {
		puttekn("\r\nKunde inte få ett Lock för directoryt!\r\n",-1);
		FreeMem(id,sizeof(struct InfoData));
		return(2);
	}
	if(!Info(lock,id)) {
		puttekn("\r\nKunde inte få info om devicet!\r\n",-1);
		UnLock(lock);
		FreeMem(id,sizeof(struct InfoData));
		return(2);
	}
	bytesfree=(id->id_NumBlocks - id->id_NumBlocksUsed)*id->id_BytesPerBlock;
	UnLock(lock);
	FreeMem(id,sizeof(struct InfoData));
	if(bytesfree < Servermem->cfg.diskfree) {
		puttekn("\r\nTyvärr, gränsen för hur full disken får bli har överskridits!\r\n",-1);
		return(2);
	}
	if(Servermem->cfg.ar.preup2) sendrexx(Servermem->cfg.ar.preup2);
	sprintf(zmodeminit,"%s%s",zinitstring,dir);
	if(!(XProtocolBase=(struct Library *)OpenLibrary("xprzmodem.library",0L))) {
		puttekn("\r\n\nKunde inte öppna xprzmodem.library!\r\n",-1);
		return(2);
	}
	if(!(xio=(struct XPR_IO *)AllocMem(sizeof(struct XPR_IO),MEMF_PUBLIC | MEMF_CLEAR))) {
		puttekn("\r\n\nKunde inte allokera en io-struktur\r\n",-1);
		CloseLibrary(XProtocolBase);
		return(2);
	}
	NewList((struct List *)&tf_list);

	puttekn("\r\nDu kan börja sända med Zmodem. Du kan nu skicka fler filer!",-1);
	puttekn("\r\nTryck Ctrl-X några gånger för att avbryta.\r\n",-1);
	AbortIO((struct IORequest *)serreadreq);
	WaitIO((struct IORequest *)serreadreq);
	if(!CheckIO((struct IORequest *)inactivereq)) {
		AbortIO((struct IORequest *)inactivereq);
		WaitIO((struct IORequest *)inactivereq);
	}
	xpr_setup(xio);
	xio->xpr_filename=zmodeminit;
	XProtocolSetup(xio);
	xprreturkod=XProtocolReceive(xio);
	Delay(30);
	XProtocolCleanup(xio);
	CloseLibrary(XProtocolBase);
	if(!CheckIO((struct IORequest *)serreadreq)) {
		AbortIO((struct IORequest *)serreadreq);
		WaitIO((struct IORequest *)serreadreq);
		printf("Serreadreq avbruten!!\n");
	}
	if(!CheckIO((struct IORequest *)timerreq)) {
		AbortIO((struct IORequest *)timerreq);
		WaitIO((struct IORequest *)timerreq);
		printf("Timerreq avbruten!!\n");
	}
	FreeMem(xio,sizeof(struct XPR_IO));
	Delay(100);
	serchangereq->IOSer.io_Command=CMD_CLEAR;
	DoIO((struct IORequest *)serchangereq);
	serchangereq->IOSer.io_Command=CMD_FLUSH;
	DoIO((struct IORequest *)serchangereq);
	serreqtkn();
	updateinactive();
	if(Servermem->cfg.ar.postup2) sendrexx(Servermem->cfg.ar.postup2);
/*	if(Servermem->cfg.logmask & LOG_RECFILE) {
		sprintf(outbuffer,"Tar emot filen %s från %s",xprfilnamn,getusername(inloggad));
		logevent(outbuffer);
	}
	if(xprreturkod) {
		puttekn("\r\n\nÖverföringen lyckades.\r\n",-1);
		sprintf(outbuffer,"Hastighet: %d cps\n\r",cps);
		puttekn(outbuffer,-1);
		return(0);
	} else {
		puttekn("\r\n\nÖverföringen misslyckades.\r\n",-1);
		return(2);
	} Removed by Tomas Kärki 22/1 1996 */

	if(ulfiles > 0) {
		puttekn("\r\n\nÖverföringen lyckades.\r\n",-1);
		return(0);
	}
	else {
		puttekn("\r\n\nÖverföringen misslyckades.\r\n",-1);
		return(2);
	}
}