Exemplo n.º 1
0
ubyte	*gr_ibitblt_create_mask_sub( grsBitmap * mask_bmp, int sx, int sy, int sw, int sh, int srowSize, int destType )
{
	int x,y;
	ubyte pixel;
	int draw_mode = MODE_NONE;
	int source_offset = 0;
	int dest_offset = 0;
	int num_to_draw, draw_start_source, draw_start_dest;
	int esi, edi;
	int code_size;
	ubyte *code;
	uint temp;

	Assert( (!(mask_bmp->bmProps.flags&BM_FLAG_RLE)) );

	if ( destType == BM_SVGA )
		code_size = gr_ibitblt_find_code_size_svga( mask_bmp, sx, sy, sw, sh, srowSize );
	else
		code_size = gr_ibitblt_find_code_size( mask_bmp, sx, sy, sw, sh, srowSize );

	code = D2_ALLOC( code_size );
	if ( code == NULL )
		return NULL;

	Code_pointer = code;

	if ( destType == BM_SVGA ) {
		// MOV EBX, gr_vesa_setpage
		*Code_pointer++ = OPCODE_MOV_EBX;
		temp = (uint)gr_vesa_setpage;
		memcpy( Code_pointer, &temp, sizeof(int) );
		Code_pointer += sizeof(int);
		// MOV EAX, 0
		*Code_pointer++ = OPCODE_MOV_EAX;
		temp = 0;
		memcpy( Code_pointer, &temp, sizeof(int) );
		Code_pointer += sizeof(int);
		// CALL EBX
		*Code_pointer++ = OPCODE_CALL_EBX1;
		*Code_pointer++ = OPCODE_CALL_EBX2;

		ibitblt_svga_page = 0;
		is_svga = 1;
		linear_address = 0;
	} else {
		is_svga = 0;
	}
	esi = source_offset = 0;
	edi = dest_offset = 0;
	draw_start_source = draw_start_dest = 0;

	for ( y=sy; y<sy+sh; y++ ) {
		for ( x=sx; x<sx+sw; x++ ) {
			dest_offset = y*mask_bmp->bmProps.rowSize+x;
			pixel = mask_bmp->bmTexBuf[dest_offset];
			if ( pixel!=255 ) {
				switch ( draw_mode) {
				case MODE_DRAW:
					move_and_draw( draw_start_source-esi, draw_start_dest-edi, num_to_draw );
					esi = draw_start_source + num_to_draw;
					edi = draw_start_dest + num_to_draw;
					// fall through!!!
				case MODE_NONE:
				case MODE_SKIP:
					break;
				}
				draw_mode = MODE_SKIP;
			} else {
				switch ( draw_mode) {
				case MODE_SKIP:
				case MODE_NONE:
					draw_start_source = source_offset;
					draw_start_dest = dest_offset;
					num_to_draw = 0;
					// fall through
				case MODE_DRAW:
					num_to_draw++;
					break;
				}
				draw_mode = MODE_DRAW;
			}
			source_offset++;
		}
		if ( draw_mode == MODE_DRAW ) {
			move_and_draw( draw_start_source-esi, draw_start_dest-edi, num_to_draw );
			esi = draw_start_source + num_to_draw;
			edi = draw_start_dest + num_to_draw;
		}
		draw_mode = MODE_NONE;
		source_offset += (srowSize - sw);
	}
	*Code_pointer++ = OPCODE_RET;

	if ( Code_pointer >= &code[code_size-1] )
		Error( "ibitblt overwrote allocated code block\n" );

	////printf( "Code is %d bytes\n", Code_pointer - code );

	return code;
}
std::optional<ImageData2D> JpegImporter::doImage2D(UnsignedInt) {
    /* Initialize structures */
    jpeg_decompress_struct file;
    JSAMPARRAY rows = nullptr;
    unsigned char* data = nullptr;

    /* Fugly error handling stuff */
    /** @todo Get rid of this crap */
    struct ErrorManager {
        jpeg_error_mgr jpegErrorManager;
        std::jmp_buf setjmpBuffer;
    } errorManager;
    file.err = jpeg_std_error(&errorManager.jpegErrorManager);
    errorManager.jpegErrorManager.error_exit = [](j_common_ptr info) {
        info->err->output_message(info);
        std::longjmp(reinterpret_cast<ErrorManager*>(info->err)->setjmpBuffer, 1);
    };
    if(setjmp(errorManager.setjmpBuffer)) {
        Error() << "Trade::JpegImporter::image2D(): error while reading JPEG file";

        jpeg_destroy_decompress(&file);
        delete[] rows;
        delete[] data;
        return std::nullopt;
    }

    /* Open file */
    jpeg_create_decompress(&file);
    jpeg_mem_src(&file, _in.begin(), _in.size());

    /* Read file header, start decompression */
    jpeg_read_header(&file, true);
    jpeg_start_decompress(&file);

    /* Image size and type */
    const Vector2i size(file.output_width, file.output_height);
    static_assert(BITS_IN_JSAMPLE == 8, "Only 8-bit JPEG is supported");
    constexpr const ImageType type = ImageType::UnsignedByte;

    /* Image format */
    ImageFormat format;
    switch(file.out_color_space) {
        case JCS_GRAYSCALE:
            CORRADE_INTERNAL_ASSERT(file.out_color_components == 1);
            #ifdef MAGNUM_TARGET_GLES
            format = Context::current() && Context::current()->isExtensionSupported<Extensions::GL::EXT::texture_rg>() ?
                ImageFormat::Red : ImageFormat::Luminance;
            #else
            format = ImageFormat::Red;
            #endif
            break;
        case JCS_RGB:
            CORRADE_INTERNAL_ASSERT(file.out_color_components == 3);
            format = ImageFormat::RGB;
            break;

        /** @todo RGBA (only in libjpeg-turbo and probably ignored) */

        default:
            Error() << "Trade::JpegImporter::image2D(): unsupported color space" << file.out_color_space;
    }

    /* Initialize data array */
    data = new unsigned char[size.product()*file.out_color_components*BITS_IN_JSAMPLE/8];

    /* Read image row by row */
    rows = new JSAMPROW[size.y()];
    const Int stride = size.x()*file.out_color_components*BITS_IN_JSAMPLE/8;
    for(Int i = 0; i != size.y(); ++i)
        rows[i] = data + (size.y() - i - 1)*stride;
    while(file.output_scanline < file.output_height)
        jpeg_read_scanlines(&file, rows+file.output_scanline, file.output_height-file.output_scanline);
    delete[] rows;
    rows = nullptr;

    /* Cleanup */
    jpeg_finish_decompress(&file);
    jpeg_destroy_decompress(&file);

    return Trade::ImageData2D(format, type, size, data);
}
 SignatureSha256(const Signature& signature)
   : Signature(signature)
 {
   if (getType() != Signature::Sha256)
     throw Error("Incorrect signature type");
 }
Exemplo n.º 4
0
 void GifImage::setExifData(const ExifData& /*exifData*/)
 {
     // Todo: implement me!
     throw(Error(32, "Exif metadata", "GIF"));
 }
Exemplo n.º 5
0
 void GifImage::setComment(const std::string& /*comment*/)
 {
     // not supported
     throw(Error(32, "Image comment", "GIF"));
 }
Exemplo n.º 6
0
void LineSum::Line_Sum_Report (int number)
{
    int stop, stops, run, runs, period, per, num, time;
    int on, off, ride, total, max_ride, *total_rider, *max_load;
    char buffer [FIELD_BUFFER];
    bool last_stop_flag, stop_flag, line_flag;

    Rider_Data *rider_ptr;
    Offset_Data *offset_ptr;

    Show_Message ("Creating a Line Summary Report -- Record");
    Set_Progress (100);

    //---- initialize the selection sets ----

    set_ptr = select_set [number];
    if (set_ptr == NULL) return;

    Header_Number (LINE_SUM);

    //---- initialize the report data ----

    if (!Break_Check (rider_data.Num_Records () + 6)) {
        Print (1);
        Line_Sum_Header ();
    }
    num = set_ptr->Num_Periods () + 1;

    total_rider = new int [num];
    max_load = new int [num];

    if (total_rider == NULL || max_load == NULL) {
        Error ("Insufficient Space for %d Time Periods", num);
    }
    memset (total_rider, '\0', num * sizeof (int));
    memset (max_load, '\0', num * sizeof (int));

    //---- process each route ----

    for (rider_ptr = rider_data.First_Key (); rider_ptr; rider_ptr = rider_data.Next_Key ()) {
        Show_Progress ();

        //---- check the selection criteria ----

        if (!set_ptr->Select_Modes (rider_ptr->Mode ())) continue;
        if (!set_ptr->Select_Routes (rider_ptr->Route ())) continue;

        stops = rider_ptr->Stops ();
        runs = rider_ptr->Runs ();

        //---- check for stops in the subarea ----

        if (offset_flag && set_ptr->Subarea_Flag ()) {
            line_flag = false;

            for (stop=1; stop <= stops; stop++) {
                offset_ptr = stop_offset.Get (rider_ptr->Stop (stop));
                if (offset_ptr == NULL) continue;

                if (set_ptr->In_Subarea (offset_ptr->X (), offset_ptr->Y ())) {
                    line_flag = true;
                    break;
                }
            }
            if (!line_flag) continue;
        }

        //---- print the line label ----

        str_fmt (buffer, sizeof (buffer), "%s %d", Transit_Code ((Transit_Type) rider_ptr->Mode ()), rider_ptr->Route ());

        Print (1, "%16.16s", buffer);

        //---- process each time period ----

        for (per=1; per < num; per++) {

            total = max_ride = 0;

            for (run=1; run <= runs; run++) {
                switch (set_ptr->Time_Method ()) {
                case RUN_START:
                    time = rider_ptr->Time (run, 1);
                    break;
                case RUN_END:
                    time = rider_ptr->Time (run, stops);
                    break;
                case RUN_MID:
                    time = (rider_ptr->Time (run, 1) + rider_ptr->Time (run, stops)) / 2;
                    break;
                case SCHED_START:
                    time = rider_ptr->Schedule (run, 1);
                    break;
                case SCHED_END:
                    time = rider_ptr->Schedule (run, stops);
                    break;
                case SCHED_MID:
                    time = (rider_ptr->Schedule (run, 1) + rider_ptr->Schedule (run, stops)) / 2;
                    break;
                }
                period = set_ptr->Time_Period (Resolve (time));

                if (period < per) continue;
                if (period > per) break;

                //---- sum the line ridership ----

                ride = 0;
                last_stop_flag = stop_flag = true;

                for (stop=1; stop <= stops; stop++) {
                    on = rider_ptr->Board (run, stop);
                    off = rider_ptr->Alight (run, stop);

                    if (offset_flag && set_ptr->Subarea_Flag ()) {
                        offset_ptr = stop_offset.Get (rider_ptr->Stop (stop));
                        if (offset_ptr == NULL) continue;

                        stop_flag = set_ptr->In_Subarea (offset_ptr->X (), offset_ptr->Y ());

                        if (stop_flag && !last_stop_flag) {
                            total += ride;
                        }
                        last_stop_flag = stop_flag;
                    }
                    ride += on - off;

                    if (stop_flag) {
                        total += on;
                        if (ride > max_ride) max_ride = ride;
                    }
                }
            }
            Print (0, "  %7d %7d", total, max_ride);

            total_rider [per] += total;
            if (max_ride > max_load [per]) max_load [per] = max_ride;
        }

        //---- add the row totals ----

        if (num > 2) {
            total = max_ride = 0;

            for (run=1; run <= runs; run++) {
                switch (set_ptr->Time_Method ()) {
                case RUN_START:
                    time = rider_ptr->Time (run, 1);
                    break;
                case RUN_END:
                    time = rider_ptr->Time (run, stops);
                    break;
                case RUN_MID:
                    time = (rider_ptr->Time (run, 1) + rider_ptr->Time (run, stops)) / 2;
                    break;
                case SCHED_START:
                    time = rider_ptr->Schedule (run, 1);
                    break;
                case SCHED_END:
                    time = rider_ptr->Schedule (run, stops);
                    break;
                case SCHED_MID:
                    time = (rider_ptr->Schedule (run, 1) + rider_ptr->Schedule (run, stops)) / 2;
                    break;
                }
                period = set_ptr->Time_Period (Resolve (time));
                if (period == 0) continue;

                //---- sum the line ridership ----

                ride = 0;
                last_stop_flag = stop_flag = true;

                for (stop=1; stop <= stops; stop++) {
                    on = rider_ptr->Board (run, stop);
                    off = rider_ptr->Alight (run, stop);

                    if (offset_flag && set_ptr->Subarea_Flag ()) {
                        offset_ptr = stop_offset.Get (rider_ptr->Stop (stop));
                        if (offset_ptr == NULL) continue;

                        stop_flag = set_ptr->In_Subarea (offset_ptr->X (), offset_ptr->Y ());

                        if (stop_flag && !last_stop_flag) {
                            total += ride;
                        }
                        last_stop_flag = stop_flag;
                    }
                    ride += on - off;

                    if (stop_flag) {
                        total += off;
                        if (ride > max_ride) max_ride = ride;
                    }
                }
            }
            Print (0, "  %7d %7d", total, max_ride);

            total_rider [0] += total;
            if (max_ride > max_load [0]) max_load [0] = max_ride;
        }
    }
    End_Progress ();

    //---- print the period totals ----

    Print (2, "           Total");

    for (per=1; per <= num; per++) {
        if (per == num) {
            if (num > 2) {
                per = 0;
            } else {
                break;
            }
        }
        Print (0, " %8d %7d", total_rider [per], max_load [per]);
        if (per == 0) break;
    }
    delete [] total_rider;
    delete [] max_load;

    Header_Number (0);
}
Exemplo n.º 7
0
XF86ConfLayoutPtr
xf86parseLayoutSection (void)
{
	int has_ident = FALSE;
	int token;
	parsePrologue (XF86ConfLayoutPtr, XF86ConfLayoutRec)

	while ((token = xf86getToken (LayoutTab)) != ENDSECTION)
	{
		switch (token)
		{
		case COMMENT:
			ptr->lay_comment = xf86addComment(ptr->lay_comment, val.str);
			break;
		case IDENTIFIER:
			if (xf86getSubToken (&(ptr->lay_comment)) != STRING)
				Error (QUOTE_MSG, "Identifier");
			if (has_ident == TRUE)
				Error (MULTIPLE_MSG, "Identifier");
			ptr->lay_identifier = val.str;
			has_ident = TRUE;
			break;
		case INACTIVE:
			{
				XF86ConfInactivePtr iptr;

				iptr = calloc (1, sizeof (XF86ConfInactiveRec));
				iptr->list.next = NULL;
				if (xf86getSubToken (&(ptr->lay_comment)) != STRING) {
					free (iptr);
					Error (INACTIVE_MSG);
				}
				iptr->inactive_device_str = val.str;
				ptr->lay_inactive_lst = (XF86ConfInactivePtr)
					xf86addListItem ((glp) ptr->lay_inactive_lst, (glp) iptr);
			}
			break;
		case SCREEN:
			{
				XF86ConfAdjacencyPtr aptr;
				int absKeyword = 0;

				aptr = calloc (1, sizeof (XF86ConfAdjacencyRec));
				aptr->list.next = NULL;
				aptr->adj_scrnum = -1;
				aptr->adj_where = CONF_ADJ_OBSOLETE;
				aptr->adj_x = 0;
				aptr->adj_y = 0;
				aptr->adj_refscreen = NULL;
				if ((token = xf86getSubToken (&(ptr->lay_comment))) == NUMBER)
					aptr->adj_scrnum = val.num;
				else
					xf86unGetToken (token);
				token = xf86getSubToken(&(ptr->lay_comment));
				if (token != STRING) {
					free(aptr);
					Error (SCREEN_MSG);
				}
				aptr->adj_screen_str = val.str;

				token = xf86getSubTokenWithTab(&(ptr->lay_comment), AdjTab);
				switch (token)
				{
				case RIGHTOF:
					aptr->adj_where = CONF_ADJ_RIGHTOF;
					break;
				case LEFTOF:
					aptr->adj_where = CONF_ADJ_LEFTOF;
					break;
				case ABOVE:
					aptr->adj_where = CONF_ADJ_ABOVE;
					break;
				case BELOW:
					aptr->adj_where = CONF_ADJ_BELOW;
					break;
				case RELATIVE:
					aptr->adj_where = CONF_ADJ_RELATIVE;
					break;
				case ABSOLUTE:
					aptr->adj_where = CONF_ADJ_ABSOLUTE;
					absKeyword = 1;
					break;
				case EOF_TOKEN:
					free(aptr);
					Error (UNEXPECTED_EOF_MSG);
					break;
				default:
					xf86unGetToken (token);
					token = xf86getSubToken(&(ptr->lay_comment));
					if (token == STRING)
						aptr->adj_where = CONF_ADJ_OBSOLETE;
					else
						aptr->adj_where = CONF_ADJ_ABSOLUTE;
				}
				switch (aptr->adj_where)
				{
				case CONF_ADJ_ABSOLUTE:
					if (absKeyword) 
						token = xf86getSubToken(&(ptr->lay_comment));
					if (token == NUMBER)
					{
						aptr->adj_x = val.num;
						token = xf86getSubToken(&(ptr->lay_comment));
						if (token != NUMBER) {
							free(aptr);
							Error(INVALID_SCR_MSG);
						}
						aptr->adj_y = val.num;
					} else {
						if (absKeyword) {
							free(aptr);
							Error(INVALID_SCR_MSG);
						} else
							xf86unGetToken (token);
					}
					break;
				case CONF_ADJ_RIGHTOF:
				case CONF_ADJ_LEFTOF:
				case CONF_ADJ_ABOVE:
				case CONF_ADJ_BELOW:
				case CONF_ADJ_RELATIVE:
					token = xf86getSubToken(&(ptr->lay_comment));
					if (token != STRING) {
						free(aptr);
						Error(INVALID_SCR_MSG);
					}
					aptr->adj_refscreen = val.str;
					if (aptr->adj_where == CONF_ADJ_RELATIVE)
					{
						token = xf86getSubToken(&(ptr->lay_comment));
						if (token != NUMBER) {
							free(aptr);
							Error(INVALID_SCR_MSG);
						}
						aptr->adj_x = val.num;
						token = xf86getSubToken(&(ptr->lay_comment));
						if (token != NUMBER) {
							free(aptr);
							Error(INVALID_SCR_MSG);
						}
						aptr->adj_y = val.num;
					}
					break;
				case CONF_ADJ_OBSOLETE:
					/* top */
					aptr->adj_top_str = val.str;

					/* bottom */
					if (xf86getSubToken (&(ptr->lay_comment)) != STRING) {
						free(aptr);
						Error (SCREEN_MSG);
					}
					aptr->adj_bottom_str = val.str;

					/* left */
					if (xf86getSubToken (&(ptr->lay_comment)) != STRING) {
						free(aptr);
						Error (SCREEN_MSG);
					}
					aptr->adj_left_str = val.str;

					/* right */
					if (xf86getSubToken (&(ptr->lay_comment)) != STRING) {
						free(aptr);
						Error (SCREEN_MSG);
					}
					aptr->adj_right_str = val.str;

				}
				ptr->lay_adjacency_lst = (XF86ConfAdjacencyPtr)
					xf86addListItem ((glp) ptr->lay_adjacency_lst, (glp) aptr);
			}
			break;
		case INPUTDEVICE:
			{
				XF86ConfInputrefPtr iptr;

				iptr = calloc (1, sizeof (XF86ConfInputrefRec));
				iptr->list.next = NULL;
				iptr->iref_option_lst = NULL;
				if (xf86getSubToken (&(ptr->lay_comment)) != STRING) {
					free(iptr);
					Error (INPUTDEV_MSG);
				}
				iptr->iref_inputdev_str = val.str;
				while ((token = xf86getSubToken (&(ptr->lay_comment))) == STRING)
				{
					iptr->iref_option_lst =
						xf86addNewOption (iptr->iref_option_lst, val.str, NULL);
				}
				xf86unGetToken (token);
				ptr->lay_input_lst = (XF86ConfInputrefPtr)
					xf86addListItem ((glp) ptr->lay_input_lst, (glp) iptr);
			}
			break;
		case OPTION:
			ptr->lay_option_lst = xf86parseOption(ptr->lay_option_lst);
			break;
		case EOF_TOKEN:
			Error (UNEXPECTED_EOF_MSG);
			break;
		default:
			Error (INVALID_KEYWORD_MSG, xf86tokenString ());
			break;
		}
	}

	if (!has_ident)
		Error (NO_IDENT_MSG);

#ifdef DEBUG
	printf ("Layout section parsed\n");
#endif

	return ptr;
}
Exemplo n.º 8
0
/*
 * Read the next TIFF directory from a file
 * and convert it to the internal format.
 * We read directories sequentially.
 */
static uint64
ReadDirectory(int fd, unsigned int ix, uint64 off)
{
	uint16 dircount;
	uint32 direntrysize;
	void* dirmem = NULL;
	uint64 nextdiroff = 0;
	uint32 n;
	uint8* dp;

	if (off == 0)			/* no more directories */
		goto done;
#if defined(__WIN32__) && defined(_MSC_VER)
	if (_lseeki64(fd, (__int64)off, SEEK_SET) != (__int64)off) {
#else
	if (lseek(fd, (off_t)off, SEEK_SET) != (off_t)off) {
#endif
		Fatal("Seek error accessing TIFF directory");
		goto done;
	}
	if (!bigtiff) {
		if (read(fd, (char*) &dircount, sizeof (uint16)) != sizeof (uint16)) {
			ReadError("directory count");
			goto done;
		}
		if (swabflag)
			TIFFSwabShort(&dircount);
		direntrysize = 12;
	} else {
		uint64 dircount64 = 0;
		if (read(fd, (char*) &dircount64, sizeof (uint64)) != sizeof (uint64)) {
			ReadError("directory count");
			goto done;
		}
		if (swabflag)
			TIFFSwabLong8(&dircount64);
		if (dircount64>0xFFFF) {
			Error("Sanity check on directory count failed");
			goto done;
		}
		dircount = (uint16)dircount64;
		direntrysize = 20;
	}
	dirmem = _TIFFmalloc(dircount * direntrysize);
	if (dirmem == NULL) {
		Fatal("No space for TIFF directory");
		goto done;
	}
	n = read(fd, (char*) dirmem, dircount*direntrysize);
	if (n != dircount*direntrysize) {
		n /= direntrysize;
		Error(
#if defined(__WIN32__) && defined(_MSC_VER)
	    "Could only read %lu of %u entries in directory at offset %#I64x",
		      (unsigned long)n, dircount, (unsigned __int64) off);
#else
	    "Could only read %lu of %u entries in directory at offset %#llx",
		      (unsigned long)n, dircount, (unsigned long long) off);
#endif
		dircount = n;
		nextdiroff = 0;
	} else {
		if (!bigtiff) {
Exemplo n.º 9
0
int main(int argc, char* argv[])
{
   CLState_p        state;
   StructFOFSpec_p  ctrl;
   PStack_p         prob_names = PStackAlloc();
   int              i;
   AxFilterSet_p    filters;
   Scanner_p        in;
   DStr_p           corename;
   char             *tname;

   assert(argv[0]);
   
   InitIO(NAME);
   DocOutputFormat = tstp_format;
   OutputFormat = TSTPFormat;

   state = process_options(argc, argv);


   OpenGlobalOut(outname);

   if(filtername)
   {
      filters = AxFilterSetAlloc();
      in = CreateScanner(StreamTypeFile, filtername, true, NULL);
      AxFilterSetParse(in, filters);
      DestroyScanner(in);
   }
   else
   {
      filters = AxFilterSetCreateInternal(AxFilterDefaultSet);
   }
   if(dumpfilter)
   {
      AxFilterSetPrint(GlobalOut, filters);
   }

   if(state->argc < 1)
   {
      Error("Usage: e_axfilter <problem> [<options>]\n", USAGE_ERROR);
   }    
   
   for(i=0; state->argv[i]; i++)
   {
      PStackPushP(prob_names,  state->argv[i]);      
   }
   /* Base name is the stripped base of the first argument */
   tname = FileNameStrip(state->argv[0]);
   corename = DStrAlloc();
   DStrAppendStr(corename, tname);
   FREE(tname);
   
   ctrl = StructFOFSpecAlloc();
   StructFOFSpecParseAxioms(ctrl, prob_names, parse_format);
   StructFOFSpecInitDistrib(ctrl);
   StructFOFSpecResetShared(ctrl);

   for(i=0; i<AxFilterSetElements(filters); i++)
   {
      /* SigPrint(stdout,ctrl->sig); */

      filter_problem(ctrl, 
                     AxFilterSetGetFilter(filters,i),
                     DStrView(corename));
   }

   StructFOFSpecFree(ctrl);
   DStrFree(corename);
   AxFilterSetFree(filters);
   CLStateFree(state);
   PStackFree(prob_names);

   OutClose(GlobalOut);
   ExitIO();
#ifdef CLB_MEMORY_DEBUG
   MemFlushFreeList();
   MemDebugPrintStats(stdout);
#endif
  
   return 0;
}
Exemplo n.º 10
0
/*
====================
W_LumpLength

Returns the buffer size needed to load the given lump
====================
*/
int W_LumpLength (int lump)
{
    if (lump >= numlumps)
        Error ("W_LumpLength: %i >= numlumps",lump);
    return lumpinfo[lump].size;
}
void *GL_APIENTRY MapBufferRangeEXT(GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access)
{
    EVENT("(GLenum target = 0x%X, GLintptr offset = %d, GLsizeiptr length = %d, GLbitfield access = 0x%X)",
          target, offset, length, access);

    Context *context = GetValidGlobalContext();
    if (context)
    {
        if (!ValidBufferTarget(context, target))
        {
            context->recordError(Error(GL_INVALID_ENUM));
            return NULL;
        }

        if (offset < 0 || length < 0)
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return NULL;
        }

        Buffer *buffer = context->getState().getTargetBuffer(target);

        if (buffer == NULL)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        // Check for buffer overflow
        size_t offsetSize = static_cast<size_t>(offset);
        size_t lengthSize = static_cast<size_t>(length);

        if (!rx::IsUnsignedAdditionSafe(offsetSize, lengthSize) ||
            offsetSize + lengthSize > static_cast<size_t>(buffer->getSize()))
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return NULL;
        }

        // Check for invalid bits in the mask
        GLbitfield allAccessBits = GL_MAP_READ_BIT |
                                   GL_MAP_WRITE_BIT |
                                   GL_MAP_INVALIDATE_RANGE_BIT |
                                   GL_MAP_INVALIDATE_BUFFER_BIT |
                                   GL_MAP_FLUSH_EXPLICIT_BIT |
                                   GL_MAP_UNSYNCHRONIZED_BIT;

        if (access & ~(allAccessBits))
        {
            context->recordError(Error(GL_INVALID_VALUE));
            return NULL;
        }

        if (length == 0 || buffer->isMapped())
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        // Check for invalid bit combinations
        if ((access & (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)) == 0)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        GLbitfield writeOnlyBits = GL_MAP_INVALIDATE_RANGE_BIT |
                                   GL_MAP_INVALIDATE_BUFFER_BIT |
                                   GL_MAP_UNSYNCHRONIZED_BIT;

        if ((access & GL_MAP_READ_BIT) != 0 && (access & writeOnlyBits) != 0)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        if ((access & GL_MAP_WRITE_BIT) == 0 && (access & GL_MAP_FLUSH_EXPLICIT_BIT) != 0)
        {
            context->recordError(Error(GL_INVALID_OPERATION));
            return NULL;
        }

        Error error = buffer->mapRange(offset, length, access);
        if (error.isError())
        {
            context->recordError(error);
            return NULL;
        }

        return buffer->getMapPointer();
    }

    return NULL;
}
Exemplo n.º 12
0
bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding )
{
	if ( !file ) 
	{
		SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	// Delete the existing data:
	Clear();
	location.Clear();

	// Get the file size, so we can pre-allocate the string. HUGE speed impact.
	long length = 0;
	fseek( file, 0, SEEK_END );
	length = ftell( file );
	fseek( file, 0, SEEK_SET );

	// Strange case, but good to handle up front.
	if ( length <= 0 )
	{
		SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	// If we have a file, assume it is all one big XML file, and read it in.
	// The document parser may decide the document ends sooner than the entire file, however.
	TIXML_STRING data;
	data.reserve( length );

	// Subtle bug here. TinyXml did use fgets. But from the XML spec:
	// 2.11 End-of-Line Handling
	// <snip>
	// <quote>
	// ...the XML processor MUST behave as if it normalized all line breaks in external 
	// parsed entities (including the document entity) on input, before parsing, by translating 
	// both the two-character sequence #xD #xA and any #xD that is not followed by #xA to 
	// a single #xA character.
	// </quote>
	//
	// It is not clear fgets does that, and certainly isn't clear it works cross platform. 
	// Generally, you expect fgets to translate from the convention of the OS to the c/unix
	// convention, and not work generally.

	/*
	while( fgets( buf, sizeof(buf), file ) )
	{
		data += buf;
	}
	*/

	char* buf = new char[ length+1 ];
	buf[0] = 0;

	if ( fread( buf, length, 1, file ) != 1 ) {
		delete [] buf;
		SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	const char* lastPos = buf;
	const char* p = buf;

	buf[length] = 0;
	while( *p ) {
		assert( p < (buf+length) );
		if ( *p == 0xa ) {
			// Newline character. No special rules for this. Append all the characters
			// since the last string, and include the newline.
			data.append( lastPos, (p-lastPos+1) );	// append, include the newline
			++p;									// move past the newline
			lastPos = p;							// and point to the new buffer (may be 0)
			assert( p <= (buf+length) );
		}
		else if ( *p == 0xd ) {
			// Carriage return. Append what we have so far, then
			// handle moving forward in the buffer.
			if ( (p-lastPos) > 0 ) {
				data.append( lastPos, p-lastPos );	// do not add the CR
			}
			data += (char)0xa;						// a proper newline

			if ( *(p+1) == 0xa ) {
				// Carriage return - new line sequence
				p += 2;
				lastPos = p;
				assert( p <= (buf+length) );
			}
			else {
				// it was followed by something else...that is presumably characters again.
				++p;
				lastPos = p;
				assert( p <= (buf+length) );
			}
		}
		else {
			++p;
		}
	}
	// Handle any left over characters.
	if ( p-lastPos ) {
		data.append( lastPos, p-lastPos );
	}		
	delete [] buf;
	buf = 0;

	Parse( data.c_str(), 0, encoding );

	if (  Error() )
        return false;
    else
		return true;
}
Exemplo n.º 13
0
static int ReadTriggerInfo (CFile& cf)
{
	int		h, i, j;
	CTrigger	*trigP;

if (gameFileInfo.triggers.count && (gameFileInfo.triggers.offset > -1)) {
#if TRACE
	console.printf(CON_DBG, "   loading CTrigger data ...\n");
#endif
	if (!gameData.trigs.Create (gameFileInfo.triggers.count, false)) {
		Error ("Not enough memory for trigger data");
		return -1;
		}
	if (cf.Seek (gameFileInfo.triggers.offset, SEEK_SET)) {
		Error ("Error seeking to trigger data\n(file damaged or invalid)");
		return -1;
		}
	for (i = 0, trigP = TRIGGERS.Buffer (); i < gameFileInfo.triggers.count; i++, trigP++) {
		if (gameTopFileInfo.fileinfoVersion >= 31) 
			trigP->Read (cf, 0);
		else {
			tTriggerV30 trig;
			int t, nType = 0, flags = 0;
			if (gameTopFileInfo.fileinfoVersion == 30)
				V30TriggerRead (trig, cf);
			else {
				tTriggerV29 trig29;
				V29TriggerRead (trig29, cf);
				trig.flags = trig29.flags;
				trig.nLinks	= (char) trig29.nLinks;
				trig.value = trig29.value;
				trig.time = trig29.time;
				for (t = 0; t < trig.nLinks; t++) {
					trig.segments [t] = trig29.segments [t];
					trig.sides [t] = trig29.sides [t];
					}
				}
			//Assert(trig.flags & TRIGGER_ON);
			trig.flags &= ~TRIGGER_ON;
			if (trig.flags & TRIGGER_CONTROL_DOORS)
				nType = TT_OPEN_DOOR;
			else if (trig.flags & TRIGGER_SHIELD_DAMAGE)
				nType = TT_SHIELD_DAMAGE;
			else if (trig.flags & TRIGGER_ENERGY_DRAIN)
				nType = TT_ENERGY_DRAIN;
			else if (trig.flags & TRIGGER_EXIT)
				nType = TT_EXIT;
			else if (trig.flags & TRIGGER_MATCEN)
				nType = TT_MATCEN;
			else if (trig.flags & TRIGGER_ILLUSION_OFF)
				nType = TT_ILLUSION_OFF;
			else if (trig.flags & TRIGGER_SECRET_EXIT)
				nType = TT_SECRET_EXIT;
			else if (trig.flags & TRIGGER_ILLUSION_ON)
				nType = TT_ILLUSION_ON;
			else if (trig.flags & TRIGGER_UNLOCK_DOORS)
				nType = TT_UNLOCK_DOOR;
			else if (trig.flags & TRIGGER_OPEN_WALL)
				nType = TT_OPEN_WALL;
			else if (trig.flags & TRIGGER_CLOSE_WALL)
				nType = TT_CLOSE_WALL;
			else if (trig.flags & TRIGGER_ILLUSORY_WALL)
				nType = TT_ILLUSORY_WALL;
			else
				Int3();
			if (trig.flags & TRIGGER_ONE_SHOT)
				flags = TF_ONE_SHOT;

			trigP->nType = nType;
			trigP->flags = flags;
			trigP->nLinks = trig.nLinks;
			trigP->nLinks = trig.nLinks;
			trigP->value = trig.value;
			trigP->time = trig.time;
			for (t = 0; t < trig.nLinks; t++) {
				trigP->segments [t] = trig.segments [t];
				trigP->sides [t] = trig.sides [t];
				}
			}
		if (trigP->nLinks < 0)
			trigP->nLinks = 0;
		else if (trigP->nLinks > MAX_TRIGGER_TARGETS)
			trigP->nLinks = MAX_TRIGGER_TARGETS;
		for (h = trigP->nLinks, j = 0; j < h; ) {
			if ((trigP->segments [j] >= 0) && (trigP->segments [j] < gameData.segs.nSegments) &&
				 (trigP->sides [j] >= 0) && (trigP->sides [j] < 6))
				j++;
			else if (--h) {
				trigP->segments [j] = trigP->segments [h];
				trigP->sides [j] = trigP->sides [h];
				}
			}
		trigP->nLinks = h;
		}
	}

if (gameTopFileInfo.fileinfoVersion >= 33) {
	gameData.trigs.m_nObjTriggers = cf.ReadInt ();
	if (gameData.trigs.m_nObjTriggers) {
		if (!gameData.trigs.Create (gameData.trigs.m_nObjTriggers, true)) {
			Error ("Not enough memory for object trigger data");
			return -1;
			}
		for (i = 0; i < gameData.trigs.m_nObjTriggers; i++)
			OBJTRIGGERS [i].Read (cf, 1);
		for (i = 0; i < gameData.trigs.m_nObjTriggers; i++) {
			gameData.trigs.objTriggerRefs [i].prev = cf.ReadShort ();
			gameData.trigs.objTriggerRefs [i].next = cf.ReadShort ();
			gameData.trigs.objTriggerRefs [i].nObject = cf.ReadShort ();
			}
		}
	if (gameTopFileInfo.fileinfoVersion < 36) {
		if (!gameData.trigs.firstObjTrigger.Create (700)) {
			Error ("Not enough memory for object trigger data");
			return -1;
			}
		for (i = 0; i < 700; i++)
			gameData.trigs.firstObjTrigger [i] = cf.ReadShort ();
		}
	else {
		gameData.trigs.firstObjTrigger.Clear (0xff);
		if (!gameData.trigs.firstObjTrigger.Create (LEVEL_OBJECTS)) {
			Error ("Not enough memory for object trigger data");
			return -1;
			}
		for (i = cf.ReadShort (); i; i--) {
			j = cf.ReadShort ();
			gameData.trigs.firstObjTrigger [j] = cf.ReadShort ();
			}
		}
	}
else {
	gameData.trigs.m_nObjTriggers = 0;
	OBJTRIGGERS.Clear ();
	gameData.trigs.objTriggerRefs.Clear (0xff);
	gameData.trigs.firstObjTrigger.Clear (0xff);
	}
return 0;
}
Exemplo n.º 14
0
inline Try<Diff> diff(const std::string& from, const std::string& to)
{
  // Initialize the Apache Portable Runtime subsystem, as necessary
  // for using the svn library.
  initialize();

  // Note that svn_pool_create wraps apr_pool_create_ex, which is
  // thread safe, see: http://goo.gl/NX0hps.
  apr_pool_t* pool = svn_pool_create(NULL);

  // First we need to produce a text delta stream by diffing 'source'
  // against 'target'.
  svn_string_t source;
  source.data = from.data();
  source.len = from.length();

  svn_string_t target;
  target.data = to.data();
  target.len = to.length();

  svn_txdelta_stream_t* delta;

#if SVN_VER_MAJOR >= 1 && SVN_VER_MINOR >= 8
  svn_txdelta2(
      &delta,
      svn_stream_from_string(&source, pool),
      svn_stream_from_string(&target, pool),
      false,
      pool);
#else
  svn_txdelta(
      &delta,
      svn_stream_from_string(&source, pool),
      svn_stream_from_string(&target, pool),
      pool);
#endif

  // Now we want to convert this text delta stream into an svndiff
  // format based diff. Setup the handler that will consume the text
  // delta and produce the svndiff.
  svn_txdelta_window_handler_t handler;
  void* baton = NULL;
  svn_stringbuf_t* diff = svn_stringbuf_create_ensure(1024, pool);

#if SVN_VER_MAJOR >= 1 && SVN_VER_MINOR >= 7
  svn_txdelta_to_svndiff3(
      &handler,
      &baton,
      svn_stream_from_stringbuf(diff, pool),
      0,
      SVN_DELTA_COMPRESSION_LEVEL_DEFAULT,
      pool);
#elif SVN_VER_MAJOR >= 1 && SVN_VER_MINOR >= 4
  svn_txdelta_to_svndiff2(
      &handler,
      &baton,
      svn_stream_from_stringbuf(diff, pool),
      0,
      pool);
#else
  svn_txdelta_to_svndiff(
      svn_stream_from_stringbuf(diff, pool),
      pool,
      &handler,
      &baton);
#endif

  // Now feed the text delta to the handler.
  svn_error_t* error = svn_txdelta_send_txstream(delta, handler, baton, pool);

  if (error != NULL) {
    char buffer[1024];
    std::string message(svn_err_best_message(error, buffer, 1024));
    svn_pool_destroy(pool);
    return Error(message);
  }

  Diff d(std::string(diff->data, diff->len));

  svn_pool_destroy(pool);

  return d;
}
Exemplo n.º 15
0
void WriteCFile (const StrBuf* Data, const Collection* A, const Bitmap* B)
/* Write the contents of Data to a file in C format */
{
    FILE*       F;
    const char* D;
    unsigned    Size;


    /* Get the name of the image */
    const StrBuf* S = GetBitmapName (B);

    /* Get the file name */
    const char* Name = NeedAttrVal (A, "name", "write");

    /* Check the number of bytes per line */
    unsigned BytesPerLine = GetBytesPerLine (A);

    /* Get the number base */
    unsigned Base = GetBase (A);

    /* Get the identifier */
    const char* Ident = GetIdentifier (A);

    /* Open the output file */
    F = fopen (Name, "w");
    if (F == 0) {
        Error ("Cannot open output file `%s': %s", Name, strerror (errno));
    }

    /* Write a readable header */
    fprintf (F,
             "/*\n"
             " * This file was generated by %s %s from\n"
             " * %.*s (%ux%u, %u colors%s)\n"
             " */\n"
             "\n",
             ProgName,
             GetVersionAsString (),
             SB_GetLen (S), SB_GetConstBuf (S),
             GetBitmapWidth (B), GetBitmapHeight (B),
             GetBitmapColors (B),
             BitmapIsIndexed (B)? ", indexed" : "");

    /* If an identifier was given, output #defines for width, height, the
     * number of colors and declare a variable for the data.
     */
    if (Ident) {
        fprintf (F,
                 "#define %s_COLORS       %u\n"
                 "#define %s_WIDTH        %u\n"
                 "#define %s_HEIGHT       %u\n"
                 "const unsigned char %s[] = {\n",
                 Ident, GetBitmapColors (B),
                 Ident, GetBitmapWidth (B),
                 Ident, GetBitmapHeight (B),
                 Ident);
    }

    /* Write the data */
    D    = SB_GetConstBuf (Data);
    Size = SB_GetLen (Data);
    while (Size) {

        unsigned I;

        /* Output one line */
        unsigned Chunk = Size;
        if (Chunk > BytesPerLine) {
            Chunk = BytesPerLine;
        }
        fputs ("    ", F);
        for (I = 0; I < Chunk; ++I) {
            switch (Base) {
                case 10:
                    fprintf (F, "%u,", *D++ & 0xFF);
                    break;
                case 16:
                    fprintf (F, "0x%02X,", *D++ & 0xFF);
                    break;

            }
        }
        fputc ('\n', F);

        /* Bump the counters */
        Size -= Chunk;
    }

    /* Terminate the array if we had an identifier */
    if (Ident) {
        fputs ("};\n", F);
    }

    /* Close the file */
    if (fclose (F) != 0) {
        Error ("Error closing output file `%s': %s", Name, strerror (errno));
    }
}
Exemplo n.º 16
0
void Parser::optimise_call(ExprNode *node)
{
	DBL result = 0.0;
	bool have_result = true;;

	if(node->op != OP_CALL)
		return;
	if(node->child == NULL)
		return;
	if(node->child->op != OP_CONSTANT)
		return;

	switch(node->call.token)
	{
		case SIN_TOKEN:
			result = sin(node->child->number);
			break;
		case COS_TOKEN:
			result = cos(node->child->number);
			break;
		case TAN_TOKEN:
			result = tan(node->child->number);
			break;
		case ASIN_TOKEN:
			result = asin(node->child->number);
			break;
		case ACOS_TOKEN:
			result = acos(node->child->number);
			break;
		case ATAN_TOKEN:
			result = atan(node->child->number);
			break;
		case SINH_TOKEN:
			result = sinh(node->child->number);
			break;
		case COSH_TOKEN:
			result = cosh(node->child->number);
			break;
		case TANH_TOKEN:
			result = tanh(node->child->number);
			break;
		case ASINH_TOKEN:
			result = asinh(node->child->number);
			break;
		case ACOSH_TOKEN:
			result = acosh(node->child->number);
			break;
		case ATANH_TOKEN:
			result = atanh(node->child->number);
			break;
		case ABS_TOKEN:
			result = fabs(node->child->number);
			break;
		case RADIANS_TOKEN:
			result = node->child->number * M_PI / 180.0;
			break;
		case DEGREES_TOKEN:
			result = node->child->number * 180.0 / M_PI;
			break;
		case FLOOR_TOKEN:
			result = floor(node->child->number);
			break;
		case INT_TOKEN:
			result = (int)(node->child->number);
			break;
		case CEIL_TOKEN:
			result = ceil(node->child->number);
			break;
		case SQRT_TOKEN:
			result = sqrt(node->child->number);
			break;
		case EXP_TOKEN:
			result = exp(node->child->number);
			break;
		case LN_TOKEN:
			if(node->child->number > 0.0)
				result = log(node->child->number);
			else
				Error("Domain error in 'ln'.");
			break;
		case LOG_TOKEN:
			if(node->child->number > 0.0)
				result = log10(node->child->number);
			else
				Error("Domain error in 'log'.");
			break;
		case MIN_TOKEN:
			have_result = false;
			break;
		case MAX_TOKEN:
			have_result = false;
			break;
		case ATAN2_TOKEN:
			have_result = false;
			break;
		case POW_TOKEN:
			have_result = false;
			break;
		case MOD_TOKEN:
			have_result = false;
			break;
		case SELECT_TOKEN:
			have_result = false;
			break;
		case FUNCT_ID_TOKEN:
			have_result = false;
			break;
		case VECTFUNCT_ID_TOKEN:
			have_result = false;
			break;
		default:
			have_result = false;
			break;
	}

	if(have_result == true)
	{
		POV_FREE(node->call.name);
		node->number = result;
		node->op = OP_CONSTANT;
		POV_FREE(node->child);
		node->child = NULL;
	}
}
Exemplo n.º 17
0
bool TripPrep::Trip_Check (int hhold, int origin, int destination, int start, int end, int mode, int purpose, int vehicle)
{
	int org, des, period, start_period, end_period;

	Location_Data *loc_ptr;
	Factor_Data *factor_ptr;
	Vehicle_Data *veh_ptr;

	//---- household selection ----

	if (traveler_flag) {
		if (!traveler_range.In_Range (hhold)) return (false);
	}

	//---- mode selection -----

	if (mode < 0 || mode >= MAX_MODE) {
		Warning ("Mode %d is Out of Range (0..%d)", mode, MAX_MODE-1);
		return (false);
	}
	if (!trip_mode [mode]) return (false);

	//---- purpose selection ----

	if (purpose_flag) {
		if (!purpose_range.In_Range (purpose)) return (false);
	}

	//---- get the mid trip time ----

	start_period = time_periods.In_Index (start);
	end_period = time_periods.In_Index (end);

	period = time_periods.In_Index ((start + end + 1) / 2);

	if (period == 0) {
		period = start_period;

		if (period == 0) {
			period = end_period;
		}
	}
	if (period == 0) return (false);

	//---- set the origin ----

	if (location_flag && origin >= 0 && destination >= 0) {
		loc_ptr = location_data.Get (origin);

		if (loc_ptr == NULL) {
			if (origin != 0) {
				Warning ("Location %d was Not Found in the Location File", origin);
			}
			return (false);
		}
		if (select_org_flag) {
			if (!In_Polygon (UnRound (loc_ptr->X ()), UnRound (loc_ptr->Y ()), &select_origin.points)) return (false);
		}
		org = loc_ptr->Zone ();

		if (org_zone_flag) {
			if (!org_zone_range.In_Range (org)) return (false);
		}

		//---- set the destination ----

		loc_ptr = location_data.Get (destination);

		if (loc_ptr == NULL) {
			if (destination != 0) {
				Warning ("Location %d was Not Found in the Location File", destination);
			}
			return (false);
		}
		if (select_des_flag) {
			if (!In_Polygon (UnRound (loc_ptr->X ()), UnRound (loc_ptr->Y ()), &select_destination.points)) return (false);
		}
		des = loc_ptr->Zone ();

		if (des_zone_flag) {
			if (!des_zone_range.In_Range (des)) return (false);
		}

		//---- apply the probability factor ----

		if (factor_flag) {
			if (zone_equiv_flag) {
				origin = zone_equiv.Zone_Group (org);
				destination = zone_equiv.Zone_Group (des);
			} else {
				origin = org;
				destination = des;
			}
			factor_ptr = factor_data.Get (origin, destination, time_equiv.Period ((start + end + 1) / 2));

			if (factor_ptr != NULL) {
				if (!factor_ptr->Bucket_Factor (1.0)) return (false);
			}
		}
	}

	//---- apply selection percentage ----

	if (prob_flag) {
		if (random2.Probability () > probability) return (false);
	}

	//---- add vehicle to the list ----

	if (vehicle > 0) {

		//---- synthetic OD data ----

		if (synod_flag) {
			veh_ptr = vehicle_data.Get (vehicle);

			//---- process trucks ----

			if (veh_ptr->Type () == 2) {
				org_target [org] -= 1;
				des_target [des] -= 1;
				if (org_target [org] < 0) org_target [org] = 0.0;
				if (des_target [des] < 0) des_target [des] = 0.0;
			} else {
				if (hhold_range.In_Range (veh_ptr->Household ())) {
					veh_count [org] [des] += 1;
					next_veh [vehicle_data.Record_Index ()] = first_veh [org] [des];
					first_veh [org] [des] = vehicle_data.Record_Index ();
				}
			}
		}
		if (vehicle_list.Get_Index (vehicle) == 0) {
			if (!vehicle_list.Add (vehicle)) {
				Error ("Adding Vehicle %d to the List", vehicle);
			}
		}
	}
	return (true);
}
Exemplo n.º 18
0
std::string Authenticator::computeDigestResponse(std::string &method, std::string &uri) {
#if HAVE_DECL_MD5 || HAVE_DECL_GNUTLS_FINGERPRINT
    // The "response" field is computed as:
    //    md5(md5(<username>:<realm>:<password>):<nonce>:md5(<cmd>:<url>))
    size_t md5len = 16;
    unsigned char md5buf[md5len];
    char md5HexBuf[md5len*2+1];
    
    // Step 1: md5(<username>:<realm>:<password>)
    std::string ha1Data = username() + ":" + realm() + ":" + password();
	Debug( 2, "HA1 pre-md5: %s", ha1Data.c_str() );
#if HAVE_DECL_MD5
    MD5((unsigned char*)ha1Data.c_str(), ha1Data.length(), md5buf);
#elif HAVE_DECL_GNUTLS_FINGERPRINT
    gnutls_datum_t md5dataha1 = { (unsigned char*)ha1Data.c_str(), ha1Data.length() };
    gnutls_fingerprint( GNUTLS_DIG_MD5, &md5dataha1, md5buf, &md5len );
#endif
    for ( unsigned int j = 0; j < md5len; j++ )
    {
        sprintf(&md5HexBuf[2*j], "%02x", md5buf[j] );
    }
    md5HexBuf[md5len*2]='\0';
    std::string ha1Hash = md5HexBuf;
    
    // Step 2: md5(<cmd>:<url>)
    std::string ha2Data = method + ":" + uri;
	Debug( 2, "HA2 pre-md5: %s", ha2Data.c_str() );
#if HAVE_DECL_MD5
    MD5((unsigned char*)ha2Data.c_str(), ha2Data.length(), md5buf );
#elif HAVE_DECL_GNUTLS_FINGERPRINT
    gnutls_datum_t md5dataha2 = { (unsigned char*)ha2Data.c_str(), ha2Data.length() };
    gnutls_fingerprint( GNUTLS_DIG_MD5, &md5dataha2, md5buf, &md5len );
#endif
    for ( unsigned int j = 0; j < md5len; j++ )
    {
        sprintf( &md5HexBuf[2*j], "%02x", md5buf[j] );
    }
    md5HexBuf[md5len*2]='\0';
    std::string ha2Hash = md5HexBuf;

    // Step 3: md5(ha1:<nonce>:ha2)
    std::string digestData = ha1Hash + ":" + nonce();
	if ( ! fQop.empty() ) {
		digestData += ":" + stringtf("%08x", nc) + ":"+fCnonce + ":" + fQop;
		nc ++;
		// if qop was specified, then we have to include t and a cnonce and an nccount
	}
	digestData += ":" + ha2Hash;
	Debug( 2, "pre-md5: %s", digestData.c_str() );
#if HAVE_DECL_MD5
    MD5((unsigned char*)digestData.c_str(), digestData.length(), md5buf);
#elif HAVE_DECL_GNUTLS_FINGERPRINT
    gnutls_datum_t md5datadigest = { (unsigned char*)digestData.c_str(), digestData.length() };
    gnutls_fingerprint( GNUTLS_DIG_MD5, &md5datadigest, md5buf, &md5len );
#endif
    for ( unsigned int j = 0; j < md5len; j++ )
    {
        sprintf( &md5HexBuf[2*j], "%02x", md5buf[j] );
    }
    md5HexBuf[md5len*2]='\0';
   
    return md5HexBuf;
#else // HAVE_DECL_MD5
	Error( "You need to build with gnutls or openssl installed to use digest authentication" );
#endif // HAVE_DECL_MD5
    return( 0 );
}
Exemplo n.º 19
0
void
Declarator::InitFromType(const Type *baseType, DeclSpecs *ds) {
    bool hasUniformQual = ((typeQualifiers & TYPEQUAL_UNIFORM) != 0);
    bool hasVaryingQual = ((typeQualifiers & TYPEQUAL_VARYING) != 0);
    bool isTask =         ((typeQualifiers & TYPEQUAL_TASK) != 0);
    bool isExported =     ((typeQualifiers & TYPEQUAL_EXPORT) != 0);
    bool isConst =        ((typeQualifiers & TYPEQUAL_CONST) != 0);
    bool isUnmasked =     ((typeQualifiers & TYPEQUAL_UNMASKED) != 0);

    if (hasUniformQual && hasVaryingQual) {
        Error(pos, "Can't provide both \"uniform\" and \"varying\" qualifiers.");
        return;
    }
    if (kind != DK_FUNCTION && isTask) {
        Error(pos, "\"task\" qualifier illegal in variable declaration.");
        return;
    }
    if (kind != DK_FUNCTION && isUnmasked) {
        Error(pos, "\"unmasked\" qualifier illegal in variable declaration.");
        return;
    }
    if (kind != DK_FUNCTION && isExported) {
        Error(pos, "\"export\" qualifier illegal in variable declaration.");
        return;
    }

    Variability variability(Variability::Unbound);
    if (hasUniformQual)
        variability = Variability::Uniform;
    else if (hasVaryingQual)
        variability = Variability::Varying;

    if (kind == DK_BASE) {
        // All of the type qualifiers should be in the DeclSpecs for the
        // base declarator
        AssertPos(pos, typeQualifiers == 0);
        AssertPos(pos, child == NULL);
        type = baseType;
    }
    else if (kind == DK_POINTER) {
        /* For now, any pointer to an SOA type gets the slice property; if
           we add the capability to declare pointers as slices or not,
           we'll want to set this based on a type qualifier here. */
        const Type *ptrType = new PointerType(baseType, variability, isConst,
                                              baseType->IsSOAType());
        if (child != NULL) {
            child->InitFromType(ptrType, ds);
            type = child->type;
            name = child->name;
        }
        else
            type = ptrType;
    }
    else if (kind == DK_REFERENCE) {
        if (hasUniformQual) {
            Error(pos, "\"uniform\" qualifier is illegal to apply to references.");
            return;
        }
        if (hasVaryingQual) {
            Error(pos, "\"varying\" qualifier is illegal to apply to references.");
            return;
        }
        if (isConst) {
            Error(pos, "\"const\" qualifier is to illegal apply to references.");
            return;
        }
        // The parser should disallow this already, but double check.
        if (CastType<ReferenceType>(baseType) != NULL) {
            Error(pos, "References to references are illegal.");
            return;
        }

        const Type *refType = new ReferenceType(baseType);
        if (child != NULL) {
            child->InitFromType(refType, ds);
            type = child->type;
            name = child->name;
        }
        else
            type = refType;
    }
    else if (kind == DK_ARRAY) {
        if (Type::Equal(baseType, AtomicType::Void)) {
            Error(pos, "Arrays of \"void\" type are illegal.");
            return;
        }
        if (CastType<ReferenceType>(baseType)) {
            Error(pos, "Arrays of references (type \"%s\") are illegal.",
                  baseType->GetString().c_str());
            return;
        }

        const Type *arrayType = new ArrayType(baseType, arraySize);
        if (child != NULL) {
            child->InitFromType(arrayType, ds);
            type = child->type;
            name = child->name;
        }
        else
            type = arrayType;
    }
    else if (kind == DK_FUNCTION) {
        llvm::SmallVector<const Type *, 8> args;
        llvm::SmallVector<std::string, 8> argNames;
        llvm::SmallVector<Expr *, 8> argDefaults;
        llvm::SmallVector<SourcePos, 8> argPos;

        // Loop over the function arguments and store the names, types,
        // default values (if any), and source file positions each one in
        // the corresponding vector.
        for (unsigned int i = 0; i < functionParams.size(); ++i) {
            Declaration *d = functionParams[i];

            if (d == NULL) {
                AssertPos(pos, m->errorCount > 0);
                continue;
            }
            if (d->declarators.size() == 0) {
                // function declaration like foo(float), w/o a name for the
                // parameter; wire up a placeholder Declarator for it
                d->declarators.push_back(new Declarator(DK_BASE, pos));
                d->declarators[0]->InitFromDeclSpecs(d->declSpecs);
            }

            AssertPos(pos, d->declarators.size() == 1);
            Declarator *decl = d->declarators[0];
            if (decl == NULL || decl->type == NULL) {
                AssertPos(pos, m->errorCount > 0);
                continue;
            }

            if (decl->name == "") {
                // Give a name to any anonymous parameter declarations
                char buf[32];
                sprintf(buf, "__anon_parameter_%d", i);
                decl->name = buf;
            }
            decl->type = decl->type->ResolveUnboundVariability(Variability::Varying);

            if (d->declSpecs->storageClass != SC_NONE)
                Error(decl->pos, "Storage class \"%s\" is illegal in "
                      "function parameter declaration for parameter \"%s\".",
                      lGetStorageClassName(d->declSpecs->storageClass),
                      decl->name.c_str());
            if (Type::Equal(decl->type, AtomicType::Void)) {
                Error(decl->pos, "Parameter with type \"void\" illegal in function "
                      "parameter list.");
                decl->type = NULL;
            }

            const ArrayType *at = CastType<ArrayType>(decl->type);
            if (at != NULL) {
                // As in C, arrays are passed to functions as pointers to
                // their element type.  We'll just immediately make this
                // change now.  (One shortcoming of losing the fact that
                // the it was originally an array is that any warnings or
                // errors later issued that print the function type will
                // report this differently than it was originally declared
                // in the function, but it's not clear that this is a
                // significant problem.)
                const Type *targetType = at->GetElementType();
                if (targetType == NULL) {
                    AssertPos(pos, m->errorCount > 0);
                    return;
                }

                decl->type = PointerType::GetUniform(targetType, at->IsSOAType());

                // Make sure there are no unsized arrays (other than the
                // first dimension) in function parameter lists.
                at = CastType<ArrayType>(targetType);
                while (at != NULL) {
                    if (at->GetElementCount() == 0)
                        Error(decl->pos, "Arrays with unsized dimensions in "
                              "dimensions after the first one are illegal in "
                              "function parameter lists.");
                    at = CastType<ArrayType>(at->GetElementType());
                }
            }

            args.push_back(decl->type);
            argNames.push_back(decl->name);
            argPos.push_back(decl->pos);

            Expr *init = NULL;
            // Try to find an initializer expression.
            while (decl != NULL) {
                if (decl->initExpr != NULL) {
                    decl->initExpr = TypeCheck(decl->initExpr);
                    decl->initExpr = Optimize(decl->initExpr);
                    if (decl->initExpr != NULL) {
                        init = dynamic_cast<ConstExpr *>(decl->initExpr);
                        if (init == NULL)
                            init = dynamic_cast<NullPointerExpr *>(decl->initExpr);
                        if (init == NULL)
                            Error(decl->initExpr->pos, "Default value for parameter "
                                  "\"%s\" must be a compile-time constant.",
                                  decl->name.c_str());
                    }
                    break;
                }
                else
                    decl = decl->child;
            }
            argDefaults.push_back(init);
        }

        const Type *returnType = baseType;
        if (returnType == NULL) {
            Error(pos, "No return type provided in function declaration.");
            return;
        }

        if (CastType<FunctionType>(returnType) != NULL) {
            Error(pos, "Illegal to return function type from function.");
            return;
        }

        returnType = returnType->ResolveUnboundVariability(Variability::Varying);

        bool isExternC =  ds && (ds->storageClass == SC_EXTERN_C);
        bool isExported = ds && ((ds->typeQualifiers & TYPEQUAL_EXPORT) != 0);
        bool isTask =     ds && ((ds->typeQualifiers & TYPEQUAL_TASK) != 0);
        bool isUnmasked = ds && ((ds->typeQualifiers & TYPEQUAL_UNMASKED) != 0);

        if (isExported && isTask) {
            Error(pos, "Function can't have both \"task\" and \"export\" "
                  "qualifiers");
            return;
        }
        if (isExternC && isTask) {
            Error(pos, "Function can't have both \"extern \"C\"\" and \"task\" "
                  "qualifiers");
            return;
        }
        if (isExternC && isExported) {
            Error(pos, "Function can't have both \"extern \"C\"\" and \"export\" "
                  "qualifiers");
            return;
        }
        if (isUnmasked && isExported)
            Warning(pos, "\"unmasked\" qualifier is redundant for exported "
                    "functions.");

        if (child == NULL) {
            AssertPos(pos, m->errorCount > 0);
            return;
        }

        const FunctionType *functionType =
            new FunctionType(returnType, args, argNames, argDefaults,
                             argPos, isTask, isExported, isExternC, isUnmasked);

        // handle any explicit __declspecs on the function
        if (ds != NULL) {
            for (int i = 0; i < (int)ds->declSpecList.size(); ++i) {
                std::string str = ds->declSpecList[i].first;
                SourcePos pos = ds->declSpecList[i].second;

                if (str == "safe")
                    (const_cast<FunctionType *>(functionType))->isSafe = true;
                else if (!strncmp(str.c_str(), "cost", 4)) {
                    int cost = atoi(str.c_str() + 4);
                    if (cost < 0)
                        Error(pos, "Negative function cost %d is illegal.",
                              cost);
                    (const_cast<FunctionType *>(functionType))->costOverride = cost;
                }
                else
                    Error(pos, "__declspec parameter \"%s\" unknown.", str.c_str());
            }
        }

        child->InitFromType(functionType, ds);
        type = child->type;
        name = child->name;
    }
}
Exemplo n.º 20
0
void Progression::Read_Weights (void)
{
	int group, num_periods;
	double weight;
	String record;
	Strings parts;
	Str_Itr str_itr;

	Doubles weights;
	Dbls_Map_Itr grp_itr;
	Dbls_Map_Stat map_stat;
	Dbl_Itr wt_itr;

	Show_Message (String ("Reading %s -- Record") % weight_file.File_Type ());
	Set_Progress ();

	num_periods = progress_time.Num_Periods ();

	while (weight_file.Read ()) {
		Show_Progress ();

		record = weight_file.Record_String ();
		record.Parse (parts);

		if ((int) parts.size () < 2) continue;

		str_itr = parts.begin ();
		group = str_itr->Integer ();

		weights.clear ();
		weight = 1.0;

		for (++str_itr; str_itr != parts.end (); str_itr++) {
			weight = str_itr->Double ();

			if (weight < 0.01 || weight > 1000.0) {
				Error (String ("Group %d Period Weight %.2lf is Out of Range (0.01..1000.0)") % group % weight);
			}
			weights.push_back (weight);
		}

		//---- check the data ----

		while ((int) weights.size () < num_periods) {
			weights.push_back (weight);
		}

		map_stat = weight_data.insert (Dbls_Map_Data (group, weights));

		if (!map_stat.second) {
			Warning ("Duplicate Weight Group = ") << group;
		}
	}
	End_Progress ();
	weight_file.Close ();

	Print (2, "Number of Group Period Weight Records = ") << Progress_Count ();

	if (Report_Flag (WEIGHT_REPORT)) {

		//---- print the report ----

		Header_Number (WEIGHT_REPORT);

		if (!Break_Check (weight_data.size () + 6)) {
			Print (1);
			Weight_Header ();
		}

		for (grp_itr = weight_data.begin (); grp_itr != weight_data.end (); grp_itr++) {
			Print (1, String ("%5d") % grp_itr->first);

			for (wt_itr = grp_itr->second.begin (); wt_itr != grp_itr->second.end (); wt_itr++) {
				Print (0, String ("  %8.2lf") % *wt_itr);
			}
		}
		Header_Number (0);
	}
}
Exemplo n.º 21
0
 void GifImage::writeMetadata()
 {
     // Todo: implement me!
     throw(Error(31, "GIF"));
 } // GifImage::writeMetadata
Exemplo n.º 22
0
Arquivo: aes.c Projeto: prabhaks/AES
/**
 * It parses input table file and populated table with their repective values
 * It also performs sanity check for input values so that they conform to DES specification
 */
void ProcessTableCheck(FILE *tf) {
	char *key_ptr, *value_ptr;
	char buf[1024];
	int i;
	while (fgets(buf, sizeof buf, tf) != NULL) {
		key_ptr = buf;
		value_ptr = strchr(buf, '=');
		// each line must exist in format key=value
		if (value_ptr == NULL) {
			fprintf(stderr,
					"input of table file must exist in key=value pair\n");
			exit(1);
		}
		*value_ptr = '\0';
		value_ptr++;
		if (value_ptr == NULL || strcmp(value_ptr, "") == 0) {
			fprintf(stderr, "Error : %s value can not be null or empty\n",
					key_ptr);
			exit(1);
		}
		if (value_ptr[strlen(value_ptr) - 1] == '\n') {
			value_ptr[strlen(value_ptr) - 1] = '\0';
		}
		if (strcmp("S", key_ptr) == 0) {
			if (S != NULL) {
				Error("S");
			}
			if (strlen(value_ptr) != 512) {
				fprintf(stderr,
						"Error : invalid S-box, wrong number of entries.\n");
				exit(1);
			}
			S = initTable("S", value_ptr, 32, 32);
			int *count = (int *) malloc(sizeof(int) * 256);
			countValue(count, "S", S, 16, 16);
			for (i = 0; i < 256; i++) {
				if (count[i] != 1) {
					if (count[i] == 0)
						fprintf(stderr, "Error : {%02x} not found in S box\n", i);
					else
						fprintf(stderr,
								"Error : {%02x} found %d times in S box. It should occur only once\n",
								i, count[i]);
					exit(1);
				}
			}
			free(count);
		} else if (strcmp("P", key_ptr) == 0) {
			if (P != NULL) {
				Error("P");
			}
			if (strlen(value_ptr) != 8) {
				fprintf(stderr, "Error : invalid P, wrong number of entries\n");
				exit(1);
			}
			P = initTable("P", value_ptr, 2, 8);
		} else if (strcmp("INVP", key_ptr) == 0) {
			if (INVP != NULL) {
				Error("INVP");
			}
			if (strlen(value_ptr) != 8) {
				fprintf(stderr,
						"Error : invalid INVP, wrong number of entries\n");
				exit(1);
			}
			INVP = initTable("INVP", value_ptr, 2, 8);
		} else {
			fprintf(stderr, "Invalid input key %s in table file.\n", key_ptr);
			exit(1);
		}
	}
	if (!feof(tf)) {
		fprintf(stderr,
				"Error while reading input table file. Please try running this program after sometime.\n");
		exit(1);
	}
	if (P == NULL) {
		fprintf(stderr, "Error : Missing P in table file\n");
		exit(1);
	}
	if (S == NULL) {
		fprintf(stderr, "Error : Missing S in table file\n");
		exit(1);
	}
	if (INVP == NULL) {
		fprintf(stderr, "Error : Missing INVP in table file\n");
		exit(1);
	}
	unsigned char *prod = ModProduct(*P, *INVP);
	if (prod[0] != 0x00 || prod[1] != 0x00 || prod[2] != 0x00
			|| prod[3] != 0x01) {
		fprintf(stderr, "INVP is not multiplicative inverse of P\n");
		exit(1);
	}
	populateINVSTable();
	if (table_check == 1) {
		cleanUpAllTables();
	}
}
Exemplo n.º 23
0
 void GifImage::setIptcData(const IptcData& /*iptcData*/)
 {
     // Todo: implement me!
     throw(Error(32, "IPTC metadata", "GIF"));
 }
Exemplo n.º 24
0
// image filter - scale
void ImgFilter_Scale(int src_width, int src_height, int src_bpp, byte *src_pixels, byte *out_pixels, imgfilter_t scaler)
{
	int scaledwidth, scaledheight;
	unsigned int scale;
	byte *in;

	scale = ImgFilter_Size(1, scaler);
	if (scale > 1)
	{
		// Scale2X, Scale4X
		if (scaler & (FILTER_SCALE2X+FILTER_SCALE4X))
		{
			scaledwidth  = ImgFilter_Size(src_width, scaler);
			scaledheight = ImgFilter_Size(src_height, scaler);
			if (sxCheck(scale, src_bpp, src_width, src_height) != SCALEX_OK) 
				Error("ImgFilter: unsupported scale/BPP/width/height %i/%i/%i/%i\n", scale, src_bpp, src_width, src_height);
			// copy source data to temporary storage
			if (src_pixels != out_pixels)
				in = src_pixels;
			else
			{
				in = (byte *)mem_alloc(scaledwidth * scaledheight * src_bpp);
				memcpy(in, src_pixels, src_width * src_height * src_bpp);
			}
			// scale
			sxScale(scale, out_pixels, scaledwidth * src_bpp, in, src_width * src_bpp, src_bpp, src_width, src_height);
			if (src_pixels == out_pixels)
				mem_free(in);
			return;
		}
		// xBRz - 2X, 4X
		if (scaler & (FILTER_XBRZ2X+FILTER_XBRZ4X))
		{
			byte *temp_scale, *temp_scaled, *end, *out;
			xbrz::ScalerCfg scalerconfig;

			scaledwidth  = ImgFilter_Size(src_width, scaler);
			scaledheight = ImgFilter_Size(src_height, scaler);

			// create scaler config
			memcpy(&scalerconfig, &xbrz::DefaultScalerCfg, sizeof(xbrz::ScalerCfg));
			scalerconfig.luminanceWeight_ = 1;

			if (src_bpp == 1)
			{
				temp_scale = (byte *)mem_alloc(src_width * src_height * 4);
				temp_scaled = (byte *)mem_alloc(scaledwidth * scaledheight * 4);
				// keep colormap intact
				scalerconfig.noBlend = true;
				scalerconfig.diffusion = true;
				// fill temp_scale (xBRz only supports 32-bits per pixel with last 8 bits being 0)
				in = src_pixels;
				end = in + src_width * src_height;
				out = temp_scale;
				while(in < end)
				{
					out[0] = in[0];
					out[1] = in[0];
					out[2] = in[0];
					out[3] = 0;
					out += 4;
					in++;
				}
				// scale
				xbrz::scale(scale, (uint32_t *)temp_scale, (uint32_t *)temp_scaled, src_width, src_height, scalerconfig, 0, 99999999);
				mem_free(temp_scale);
				// copy out
				in = temp_scaled;
				end = in + scaledwidth * scaledheight * 4;
				out = out_pixels;
				while(in < end)
				{
					out[0] = in[0];
					in += 4;
					out++;
				}
				mem_free(temp_scaled);
			}
			else if (src_bpp == 3)
			{
				temp_scale = (byte *)mem_alloc(src_width * src_height * 4);
				temp_scaled = (byte *)mem_alloc(scaledwidth * scaledheight * 4);
				// fill temp_scale (xBRz only supports 32-bits per pixel with last 8 bits being 0)
				in = src_pixels;
				end = in + src_width * src_height * 3;
				out = temp_scale;
				while(in < end)
				{
					out[0] = in[0];
					out[1] = in[1];
					out[2] = in[2];
					out[3] = 0;
					out += 4;
					in += 3;
				}
				// scale
				xbrz::scale(scale, (uint32_t *)temp_scale, (uint32_t *)temp_scaled, src_width, src_height, scalerconfig, 0, 99999999);
				mem_free(temp_scale);
				// copy out
				in = temp_scaled;
				end = in + scaledwidth * scaledheight * 4;
				out = out_pixels;
				while(in < end)
				{
					out[0] = in[0];
					out[1] = in[1];
					out[2] = in[2];
					in += 4;
					out += 3;
				}
				mem_free(temp_scaled);
			}
			else
			{
				temp_scale = (byte *)mem_alloc(src_width * src_height * 4);
				temp_scaled = (byte *)mem_alloc(scaledwidth * scaledheight * 4);
				// fill temp_scale with RGB data (xBRz only supports 32-bits per pixel with last 8 bits being 0)
				in = src_pixels;
				end = in + src_width * src_height * 4;
				out = temp_scale;
				while(in < end)
				{
					out[0] = in[0];
					out[1] = in[1];
					out[2] = in[2];
					out[3] = 0;
					out += 4;
					in += 4;
				}
				// scale & copy out
				xbrz::scale(scale, (uint32_t *)temp_scale, (uint32_t *)temp_scaled, src_width, src_height, scalerconfig, 0, 99999999);
				in = temp_scaled;
				end = in + scaledwidth * scaledheight * 4;
				out = out_pixels;
				while(in < end)
				{
					out[0] = in[0];
					out[1] = in[1];
					out[2] = in[2];
					in += 4;
					out += 4;
				}
				// now fill with alpha
				in = src_pixels;
				end = in + src_width * src_height * 4;
				out = temp_scale;
				while(in < end)
				{
					out[0] = in[3];
					out[1] = in[3];
					out[2] = in[3];
					out[3] = 0;
					out += 4;
					in += 4;
				}
				// scale & copy out
				xbrz::scale(scale, (uint32_t *)temp_scale, (uint32_t *)temp_scaled, src_width, src_height, scalerconfig, 0, 99999999);
				in = temp_scaled;
				end = in + scaledwidth * scaledheight * 4;
				out = out_pixels;
				while(in < end)
				{
					out[3] = in[0];
					in += 4;
					out += 4;
				}
				mem_free(temp_scale);
				mem_free(temp_scaled);
			}
			return;
		}
		return;
	}

	// no scale, just copy pixels if needed
	if (src_pixels != out_pixels)
		memcpy(out_pixels, src_pixels, src_width*src_height*src_bpp);
}
Exemplo n.º 25
0
//
// SourceExpressionC::ParseAttributeScript
//
void SourceExpressionC::ParseAttributeScript(FunctionAttributes &funcAttr, SRCEXPC_PARSE_ARG1)
{
    funcAttr.script = true;

    if(!in->dropType(SourceTokenC::TT_PAREN_O)) return;

    // script-type

    SourceTokenC::Reference tok = in->get(SourceTokenC::TT_NAM);

    if(tok->data == "closed" || tok->data == "__closed" || tok->data == "__closed__")
        funcAttr.scriptType = ObjectData::ST_CLOSED;

    else if(tok->data == "open" || tok->data == "__open" || tok->data == "__open__")
        funcAttr.scriptType = ObjectData::ST_OPEN;

    else if(tok->data == "respawn" || tok->data == "__respawn" || tok->data == "__respawn__")
        funcAttr.scriptType = ObjectData::ST_RESPAWN;

    else if(tok->data == "death" || tok->data == "__death" || tok->data == "__death__")
        funcAttr.scriptType = ObjectData::ST_DEATH;

    else if(tok->data == "enter" || tok->data == "__enter" || tok->data == "__enter__")
        funcAttr.scriptType = ObjectData::ST_ENTER;

    else if(tok->data == "lightning" || tok->data == "__lightning" || tok->data == "__lightning__")
        funcAttr.scriptType = ObjectData::ST_LIGHTNING;

    else if(tok->data == "unloading" || tok->data == "__unloading" || tok->data == "__unloading__")
        funcAttr.scriptType = ObjectData::ST_UNLOADING;

    else if(tok->data == "disconnect" || tok->data == "__disconnect" || tok->data == "__disconnect__")
        funcAttr.scriptType = ObjectData::ST_DISCONNECT;

    else if(tok->data == "return" || tok->data == "__return" || tok->data == "__return__")
        funcAttr.scriptType = ObjectData::ST_RETURN;

    else
        Error(tok->pos, "unrecognized script-type '%s'", tok->data.c_str());

    // script-flag

    while(in->dropType(SourceTokenC::TT_IOR))
    {
        tok = in->get(SourceTokenC::TT_NAM);

        if(tok->data == "net" || tok->data == "__net" || tok->data == "__net__")
            funcAttr.scriptFlag |= ObjectData::SF_NET;

        else if(tok->data == "clientside" || tok->data == "__clientside" || tok->data == "__clientside__")
            funcAttr.scriptFlag |= ObjectData::SF_CLIENTSIDE;

        else
            Error(tok->pos, "unrecognized script-flag '%s'", tok->data.c_str());
    }

    // script-addr

    if(in->dropType(SourceTokenC::TT_COMMA))
    {
        if(in->peekType(SourceTokenC::TT_STR))
        {
            funcAttr.scriptName = in->get()->data;
            funcAttr.scriptAddr = -2;
        }
        else
        {
            tok = in->get(SourceTokenC::TT_INT);
            funcAttr.scriptName = "";
            funcAttr.scriptAddr = ParseInt(tok->data, context, tok->pos)->makeObject()->resolveINT();
        }
    }

    in->get(SourceTokenC::TT_PAREN_C);
}
Exemplo n.º 26
0
CValue CValueControl::Method(int iName,CValue **p)
{
    if(!pWnd)
        Error("Не было привязки окна CWnd!");
    CValue Ret;
    switch(iName)
    {
    case enVisible:
    {
        Ret=Visible();
        if(p[0]->nType!=TYPE_EMPTY)
            Visible(p[0]->GetNumber());
        break;
    }
    case enEnable:
    {
        Ret=Enable();
        if(p[0]->nType!=TYPE_EMPTY)
            Enable(p[0]->GetNumber());
        break;
    }
    case enColor:
    {
        Ret=Color();
        if(p[0]->nType!=TYPE_EMPTY)
            Color(p[0]->GetNumber(),p[1]->GetNumber(),p[2]->GetNumber());
        break;
    }
    case enCaption:
    {
        Ret=String(Caption());
        if(p[0]->nType!=TYPE_EMPTY)
        {
            Caption(p[0]->GetString());
        }
        break;
    }
    case enEnableEdit:
    {
        Ret=EnableEdit();
        if(p[0]->nType!=TYPE_EMPTY)
            EnableEdit(p[0]->GetNumber());
        break;
    }
    case enMask:
    {
        //Ret=Mask();
        if(p[0]->nType!=TYPE_EMPTY)
            Ret=String(Mask(p[0]->GetString()));
        break;
    }
    case enClose:
    {
        Close();
        break;
    }
    case enModif:
    {
        int nSet=-1;
        if(p[0]->nType!=TYPE_EMPTY)
            nSet=p[0]->GetNumber();
        return Modify(nSet);
    }
    case enFocus:
    {
        ((CWnd*)pWnd)->SetFocus();
    }
    case enSetControlRect:
    {
        int x, y, nWidth, nHeight;
        x=p[0]->GetNumber();
        y=p[1]->GetNumber();
        nWidth=p[2]->GetNumber();
        nHeight=p[3]->GetNumber();
        ASSERT(pWnd);
        ((CWnd*)pWnd)->MoveWindow(x, y, nWidth, nHeight,1);
        ((CWnd*)pWnd)->RedrawWindow();
        break;
    }
    case enGetControlRect:
    {
        CRect mRect(0,0,0,0);
        ASSERT(pWnd);
        ((CWnd*)pWnd)->GetWindowRect(&mRect);
        CWnd* pParentWnd=((CWnd*)pWnd)->GetParent();
        pParentWnd->ScreenToClient(&mRect);
        *p[0] = CValue(mRect.left);
        *p[1] = CValue(mRect.top);
        *p[2] = CValue(mRect.right - mRect.left);
        *p[3] = CValue(mRect.bottom - mRect.top);
        break;
    }
    }
    return Ret;
}
Exemplo n.º 27
0
	//--------------------------------------------------------------------------
	static void error(int error, const char* description)
	{
		Error(description);
	}
Exemplo n.º 28
0
lua_State *lua_loadscript(char *file) {
  char fullpath[LUA_PATHLEN];
  int top;
  lua_State *l;
  lua_list *n;
  char buf[1024];
  void *args[2];

  if(!cpath || !suffix)
    return NULL;

  strlcpy(buf, file, sizeof(buf));

  delchars(buf, "./\\;");

  if(lua_scriptloaded(buf))
    return NULL;

  l = lua_newstate(lua_nsmalloc, NULL);
  if(!l)
    return NULL;

  n = (lua_list *)luamalloc(sizeof(lua_list));;
  if(!n) {
    Error("lua", ERR_ERROR, "Error allocing list for %s.", buf);
    return NULL;
  }

  n->name = getsstring(buf, LUA_PATHLEN);
  if(!n->name) {
    Error("lua", ERR_ERROR, "Error allocing name item for %s.", buf);
    luafree(n);
    return NULL;
  }
  n->calls = 0;

  timerclear(&n->ru_utime);
  timerclear(&n->ru_stime);

  lua_loadlibs(l);
  lua_registerdebug(l);
  lua_registercommands(l);
  lua_registerlocalcommands(l);
  lua_registerdbcommands(l);
  lua_registersocketcommands(l);
  lua_registercryptocommands(l);
  lua_registerschedulercommands(l);

  args[0] = file;
  args[1] = l;
  triggerhook(HOOK_LUA_LOADSCRIPT, args);

#ifdef LUA_USEJIT
  lua_require(l, "lib/jit");
#endif

  lua_require(l, "lib/bootstrap");

  snprintf(fullpath, sizeof(fullpath), "%s/%s%s", cpath->content, file, suffix->content);
  if(luaL_loadfile(l, fullpath)) {
    Error("lua", ERR_ERROR, "Error loading %s.", file);
    lua_close(l);
    freesstring(n->name);
    luafree(n);
    return NULL;
  }

  n->l = l;

  n->next = NULL;
  n->prev = lua_tail;
  n->nicks = NULL;
  n->sockets = NULL;
  n->schedulers = NULL;

  if(!lua_head) { 
    lua_head = n;
  } else {
    lua_tail->next = n;
  }

  lua_tail = n;

  top = lua_gettop(l);

  if(lua_pcall(l, 0, 0, 0)) {
    Error("lua", ERR_ERROR, "Error pcalling: %s.", file);
    lua_close(l);
    freesstring(n->name);

    if(lua_head == n)
      lua_head = NULL;

    lua_tail = n->prev;
    if(lua_tail)
      lua_tail->next = NULL;

    luafree(n);
    return NULL;
  }

  lua_settop(l, top);

  Error("lua", ERR_INFO, "Loaded %s.", file);
  lua_onload(l);

  return l;
}
Exemplo n.º 29
0
mesos::internal::master::Flags::Flags()
{
  add(&Flags::version,
      "version",
      "Show version and exit.",
      false);

  add(&Flags::hostname,
      "hostname",
      "The hostname the master should advertise in ZooKeeper.\n"
      "If left unset, the hostname is resolved from the IP address\n"
      "that the slave binds to; unless the user explicitly prevents\n"
      "that, using --no-hostname_lookup, in which case the IP itself\n"
      "is used.");

  add(&Flags::hostname_lookup,
      "hostname_lookup",
      "Whether we should execute a lookup to find out the server's hostname,\n"
      "if not explicitly set (via, e.g., `--hostname`).\n"
      "True by default; if set to 'false' it will cause Mesos\n"
      "to use the IP address, unless the hostname is explicitly set.",
      true);

  add(&Flags::root_submissions,
      "root_submissions",
      "Can root submit frameworks?",
      true);

  add(&Flags::work_dir,
      "work_dir",
      "Directory path to store the persistent information stored in the \n"
      "Registry. (example: /var/lib/mesos/master)");

  // TODO(bmahler): Consider removing 'in_memory' as it was only
  // used before 'replicated_log' was implemented.
  add(&Flags::registry,
      "registry",
      "Persistence strategy for the registry;\n"
      "available options are 'replicated_log', 'in_memory' (for testing).",
      "replicated_log");

  // TODO(vinod): Instead of specifying the quorum size consider
  // specifying the number of masters or the list of masters.
  add(&Flags::quorum,
      "quorum",
      "The size of the quorum of replicas when using 'replicated_log' based\n"
      "registry. It is imperative to set this value to be a majority of\n"
      "masters i.e., quorum > (number of masters)/2.");

  add(&Flags::zk_session_timeout,
      "zk_session_timeout",
      "ZooKeeper session timeout.",
      ZOOKEEPER_SESSION_TIMEOUT);

  // TODO(bmahler): Set the default to true in 0.20.0.
  add(&Flags::registry_strict,
      "registry_strict",
      "Whether the Master will take actions based on the persistent\n"
      "information stored in the Registry. Setting this to false means\n"
      "that the Registrar will never reject the admission, readmission,\n"
      "or removal of a slave. Consequently, 'false' can be used to\n"
      "bootstrap the persistent state on a running cluster.\n"
      "NOTE: This flag is *experimental* and should not be used in\n"
      "production yet.",
      false);

  add(&Flags::registry_fetch_timeout,
      "registry_fetch_timeout",
      "Duration of time to wait in order to fetch data from the registry\n"
      "after which the operation is considered a failure.",
      Seconds(60));

  add(&Flags::registry_store_timeout,
      "registry_store_timeout",
      "Duration of time to wait in order to store data in the registry\n"
      "after which the operation is considered a failure.",
      Seconds(5));

  add(&Flags::log_auto_initialize,
      "log_auto_initialize",
      "Whether to automatically initialize the replicated log used for the\n"
      "registry. If this is set to false, the log has to be manually\n"
      "initialized when used for the very first time.",
      true);

  add(&Flags::slave_reregister_timeout,
      "slave_reregister_timeout",
      "The timeout within which all slaves are expected to re-register\n"
      "when a new master is elected as the leader. Slaves that do not\n"
      "re-register within the timeout will be removed from the registry\n"
      "and will be shutdown if they attempt to communicate with master.\n"
      "NOTE: This value has to be at least " +
        stringify(MIN_SLAVE_REREGISTER_TIMEOUT) + ".",
      MIN_SLAVE_REREGISTER_TIMEOUT);

  // TODO(bmahler): Add a 'Percentage' abstraction for flags.
  // TODO(bmahler): Add a --production flag for production defaults.
  add(&Flags::recovery_slave_removal_limit,
      "recovery_slave_removal_limit",
      "For failovers, limit on the percentage of slaves that can be removed\n"
      "from the registry *and* shutdown after the re-registration timeout\n"
      "elapses. If the limit is exceeded, the master will fail over rather\n"
      "than remove the slaves.\n"
      "This can be used to provide safety guarantees for production\n"
      "environments. Production environments may expect that across Master\n"
      "failovers, at most a certain percentage of slaves will fail\n"
      "permanently (e.g. due to rack-level failures).\n"
      "Setting this limit would ensure that a human needs to get\n"
      "involved should an unexpected widespread failure of slaves occur\n"
      "in the cluster.\n"
      "Values: [0%-100%]",
      stringify(RECOVERY_SLAVE_REMOVAL_PERCENT_LIMIT * 100.0) + "%");

  // TODO(vinod): Add a 'Rate' abstraction in stout and the
  // corresponding parser for flags.
  add(&Flags::slave_removal_rate_limit,
      "slave_removal_rate_limit",
      "The maximum rate (e.g., 1/10mins, 2/3hrs, etc) at which slaves will\n"
      "be removed from the master when they fail health checks. By default\n"
      "slaves will be removed as soon as they fail the health checks.\n"
      "The value is of the form <Number of slaves>/<Duration>.");

  add(&Flags::webui_dir,
      "webui_dir",
      "Directory path of the webui files/assets",
      PKGDATADIR "/webui");

  add(&Flags::whitelist,
      "whitelist",
      "Path to a file with a list of slaves\n"
      "(one per line) to advertise offers for.\n"
      "Path could be of the form 'file:///path/to/file' or '/path/to/file'.");

  add(&Flags::user_sorter,
      "user_sorter",
      "Policy to use for allocating resources\n"
      "between users. May be one of:\n"
      "  dominant_resource_fairness (drf)",
      "drf");

  add(&Flags::framework_sorter,
      "framework_sorter",
      "Policy to use for allocating resources\n"
      "between a given user's frameworks. Options\n"
      "are the same as for user_allocator.",
      "drf");

  add(&Flags::allocation_interval,
      "allocation_interval",
      "Amount of time to wait between performing\n"
      " (batch) allocations (e.g., 500ms, 1sec, etc).",
      DEFAULT_ALLOCATION_INTERVAL);

  add(&Flags::cluster,
      "cluster",
      "Human readable name for the cluster,\n"
      "displayed in the webui.");

  add(&Flags::roles,
      "roles",
      "A comma-separated list of the allocation roles that frameworks\n"
      "in this cluster may belong to. This flag is deprecated;\n"
      "if it is not specified, any role name can be used.");

  add(&Flags::weights,
      "weights",
      "A comma-separated list of role/weight pairs\n"
      "of the form 'role=weight,role=weight'. Weights\n"
      "are used to indicate forms of priority.");

  // TODO(adam-mesos): Deprecate --authenticate for --authenticate_frameworks.
  // See MESOS-4386 for details.
  add(&Flags::authenticate_frameworks,
      "authenticate",
      "If authenticate is 'true' only authenticated frameworks are allowed\n"
      "to register. If 'false' unauthenticated frameworks are also\n"
      "allowed to register.",
      false);

  add(&Flags::authenticate_slaves,
      "authenticate_slaves",
      "If 'true' only authenticated slaves are allowed to register.\n"
      "If 'false' unauthenticated slaves are also allowed to register.",
      false);

  add(&Flags::authenticate_http,
      "authenticate_http",
      "If 'true' only authenticated requests for HTTP endpoints supporting\n"
      "authentication are allowed.\n"
      "If 'false' unauthenticated HTTP endpoint requests are also allowed.\n",
      false);

  add(&Flags::credentials,
      "credentials",
      "Either a path to a text file with a list of credentials,\n"
      "each line containing 'principal' and 'secret' separated by "
      "whitespace,\n"
      "or, a path to a JSON-formatted file containing credentials.\n"
      "Path could be of the form 'file:///path/to/file' or '/path/to/file'."
      "\n"
      "JSON file Example:\n"
      "{\n"
      "  \"credentials\": [\n"
      "    {\n"
      "      \"principal\": \"sherman\",\n"
      "      \"secret\": \"kitesurf\"\n"
      "    }\n"
      "  ]\n"
      "}\n"
      "Text file Example:\n"
      "username secret");

  add(&Flags::acls,
      "acls",
      "The value could be a JSON-formatted string of ACLs\n"
      "or a file path containing the JSON-formatted ACLs used\n"
      "for authorization. Path could be of the form 'file:///path/to/file'\n"
      "or '/path/to/file'.\n"
      "\n"
      "Note that if the flag --authorizers is provided with a value different\n"
      "than '" + DEFAULT_AUTHORIZER + "', the ACLs contents will be ignored.\n"
      "\n"
      "See the ACLs protobuf in authorizer.proto for the expected format.\n"
      "\n"
      "Example:\n"
      "{\n"
      "  \"register_frameworks\": [\n"
      "    {\n"
      "      \"principals\": { \"type\": \"ANY\" },\n"
      "      \"roles\": { \"values\": [\"a\"] }\n"
      "    }\n"
      "  ],\n"
      "  \"run_tasks\": [\n"
      "    {\n"
      "      \"principals\": { \"values\": [\"a\", \"b\"] },\n"
      "      \"users\": { \"values\": [\"c\"] }\n"
      "    }\n"
      "  ],\n"
      "  \"teardown_frameworks\": [\n"
      "    {\n"
      "      \"principals\": { \"values\": [\"a\", \"b\"] },\n"
      "      \"framework_principals\": { \"values\": [\"c\"] }\n"
      "    }\n"
      "  ],\n"
      "  \"set_quotas\": [\n"
      "    {\n"
      "      \"principals\": { \"values\": [\"a\"] },\n"
      "      \"roles\": { \"values\": [\"a\", \"b\"] }\n"
      "    }\n"
      "  ],\n"
      "  \"remove_quotas\": [\n"
      "    {\n"
      "      \"principals\": { \"values\": [\"a\"] },\n"
      "      \"quota_principals\": { \"values\": [\"a\"] }\n"
      "    }\n"
      "  ]\n"
      "}");

  add(&Flags::firewall_rules,
      "firewall_rules",
      "The value could be a JSON-formatted string of rules or a\n"
      "file path containing the JSON-formatted rules used in the endpoints\n"
      "firewall. Path must be of the form 'file:///path/to/file'\n"
      "or '/path/to/file'.\n"
      "\n"
      "See the Firewall message in flags.proto for the expected format.\n"
      "\n"
      "Example:\n"
      "{\n"
      "  \"disabled_endpoints\" : {\n"
      "    \"paths\" : [\n"
      "      \"/files/browse\",\n"
      "      \"/slave(0)/stats.json\"\n"
      "    ]\n"
      "  }\n"
      "}");

  add(&Flags::rate_limits,
      "rate_limits",
      "The value could be a JSON-formatted string of rate limits\n"
      "or a file path containing the JSON-formatted rate limits used\n"
      "for framework rate limiting.\n"
      "Path could be of the form 'file:///path/to/file'\n"
      "or '/path/to/file'.\n"
      "\n"
      "See the RateLimits protobuf in mesos.proto for the expected format.\n"
      "\n"
      "Example:\n"
      "{\n"
      "  \"limits\": [\n"
      "    {\n"
      "      \"principal\": \"foo\",\n"
      "      \"qps\": 55.5\n"
      "    },\n"
      "    {\n"
      "      \"principal\": \"bar\"\n"
      "    }\n"
      "  ],\n"
      "  \"aggregate_default_qps\": 33.3\n"
      "}");

#ifdef WITH_NETWORK_ISOLATOR
  add(&Flags::max_executors_per_slave,
      "max_executors_per_slave",
      "Maximum number of executors allowed per slave. The network\n"
      "monitoring/isolation technique imposes an implicit resource\n"
      "acquisition on each executor (# ephemeral ports), as a result\n"
      "one can only run a certain number of executors on each slave.");
#endif // WITH_NETWORK_ISOLATOR

  // TODO(karya): When we have optimistic offers, this will only
  // benefit frameworks that accidentally lose an offer.
  add(&Flags::offer_timeout,
      "offer_timeout",
      "Duration of time before an offer is rescinded from a framework.\n"
      "This helps fairness when running frameworks that hold on to offers,\n"
      "or frameworks that accidentally drop offers.");

  // This help message for --modules flag is the same for
  // {master,slave,tests}/flags.hpp and should always be kept in
  // sync.
  // TODO(karya): Remove the JSON example and add reference to the
  // doc file explaining the --modules flag.
  add(&Flags::modules,
      "modules",
      "List of modules to be loaded and be available to the internal\n"
      "subsystems.\n"
      "\n"
      "Use --modules=filepath to specify the list of modules via a\n"
      "file containing a JSON-formatted string. 'filepath' can be\n"
      "of the form 'file:///path/to/file' or '/path/to/file'.\n"
      "\n"
      "Use --modules=\"{...}\" to specify the list of modules inline.\n"
      "\n"
      "Example:\n"
      "{\n"
      "  \"libraries\": [\n"
      "    {\n"
      "      \"file\": \"/path/to/libfoo.so\",\n"
      "      \"modules\": [\n"
      "        {\n"
      "          \"name\": \"org_apache_mesos_bar\",\n"
      "          \"parameters\": [\n"
      "            {\n"
      "              \"key\": \"X\",\n"
      "              \"value\": \"Y\"\n"
      "            }\n"
      "          ]\n"
      "        },\n"
      "        {\n"
      "          \"name\": \"org_apache_mesos_baz\"\n"
      "        }\n"
      "      ]\n"
      "    },\n"
      "    {\n"
      "      \"name\": \"qux\",\n"
      "      \"modules\": [\n"
      "        {\n"
      "          \"name\": \"org_apache_mesos_norf\"\n"
      "        }\n"
      "      ]\n"
      "    }\n"
      "  ]\n"
      "}");

  add(&Flags::authenticators,
      "authenticators",
      "Authenticator implementation to use when authenticating frameworks\n"
      "and/or slaves. Use the default '" + DEFAULT_AUTHENTICATOR + "', or\n"
      "load an alternate authenticator module using --modules.",
      DEFAULT_AUTHENTICATOR);

  add(&Flags::allocator,
      "allocator",
      "Allocator to use for resource allocation to frameworks.\n"
      "Use the default '" + DEFAULT_ALLOCATOR + "' allocator, or\n"
      "load an alternate allocator module using --modules.",
      DEFAULT_ALLOCATOR);

  add(&Flags::hooks,
      "hooks",
      "A comma-separated list of hook modules to be\n"
      "installed inside master.");

  add(&Flags::slave_ping_timeout,
      "slave_ping_timeout",
      "The timeout within which each slave is expected to respond to a\n"
      "ping from the master. Slaves that do not respond within\n"
      "max_slave_ping_timeouts ping retries will be asked to shutdown.\n"
      "NOTE: The total ping timeout (slave_ping_timeout multiplied by\n"
      "max_slave_ping_timeouts) should be greater than the ZooKeeper\n"
      "session timeout to prevent useless re-registration attempts.\n",
      DEFAULT_SLAVE_PING_TIMEOUT,
      [](const Duration& value) -> Option<Error> {
        if (value < Seconds(1) || value > Minutes(15)) {
          return Error("Expected --slave_ping_timeout to be between " +
                       stringify(Seconds(1)) + " and " +
                       stringify(Minutes(15)));
        }
        return None();
      });

  add(&Flags::max_slave_ping_timeouts,
      "max_slave_ping_timeouts",
      "The number of times a slave can fail to respond to a\n"
      "ping from the master. Slaves that do not respond within\n"
      "max_slave_ping_timeouts ping retries will be asked to shutdown.\n",
      DEFAULT_MAX_SLAVE_PING_TIMEOUTS,
      [](size_t value) -> Option<Error> {
        if (value < 1) {
          return Error("Expected --max_slave_ping_timeouts to be at least 1");
        }
        return None();
      });

  add(&Flags::authorizers,
      "authorizers",
      "Authorizer implementation to use when authorizating actions that\n"
      "required it.\n"
      "Use the default '" + DEFAULT_AUTHORIZER + "', or\n"
      "load an alternate authorizer module using --modules.\n"
      "\n"
      "Note that if the flag --authorizers is provided with a value different\n"
      "than the default '" + DEFAULT_AUTHORIZER + "', the ACLs passed\n"
      "through the --acls flag will be ignored.\n"
      "\n"
      "Currently there's no support for multiple authorizers.",
      DEFAULT_AUTHORIZER);

  add(&Flags::http_authenticators,
      "http_authenticators",
      "HTTP authenticator implementation to use when handling requests to\n"
      "authenticated endpoints. Use the default\n"
      "'" + DEFAULT_HTTP_AUTHENTICATOR + "', or load an alternate HTTP\n"
      "authenticator module using --modules.\n"
      "\n"
      "Currently there is no support for multiple HTTP authenticators.",
      DEFAULT_HTTP_AUTHENTICATOR);

  add(&Flags::max_completed_frameworks,
      "max_completed_frameworks",
      "Maximum number of completed frameworks to store in memory.",
      DEFAULT_MAX_COMPLETED_FRAMEWORKS);

  add(&Flags::max_completed_tasks_per_framework,
      "max_completed_tasks_per_framework",
      "Maximum number of completed tasks per framework to store in memory.",
      DEFAULT_MAX_COMPLETED_TASKS_PER_FRAMEWORK);
}
Exemplo n.º 30
0
	bool MD5MeshParser::Parse()
	{
		while (Advance(false))
		{
			switch (m_currentLine[0])
			{
				#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
				case 'M': // MD5Version
					if (m_currentLine.GetWord(0) != "MD5Version")
						UnrecognizedLine();
					break;

				case 'c': // commandline
					if (m_currentLine.GetWord(0) != "commandline")
						UnrecognizedLine();
					break;
				#endif

				case 'j': // joints
					#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
					if (!m_currentLine.StartsWith("joints {"))
					{
						UnrecognizedLine();
						break;
					}
					#endif

					if (!ParseJoints())
					{
						Error("Failed to parse joints");
						return false;
					}
					break;

				case 'm': // mesh
				{
					#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
					if (m_currentLine != "mesh {")
					{
						UnrecognizedLine();
						break;
					}
					#endif

					if (m_meshIndex >= m_meshes.size())
					{
						#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
						Warning("More meshes than registred");
						#endif

						m_meshes.push_back(Mesh());
					}

					if (!ParseMesh())
					{
						NazaraError("Failed to parse mesh");
						return false;
					}

					m_meshIndex++;
					break;
				}

				case 'n': // num[Frames/Joints]
				{
					unsigned int count;
					if (std::sscanf(&m_currentLine[0], "numJoints %u", &count) == 1)
					{
						#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
						if (!m_joints.empty())
							Warning("Joint count is already defined");
						#endif

						m_joints.resize(count);
					}
					else if (std::sscanf(&m_currentLine[0], "numMeshes %u", &count) == 1)
					{
						#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
						if (!m_meshes.empty())
							Warning("Mesh count is already defined");
						#endif

						m_meshes.resize(count);
					}
					#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
					else
						UnrecognizedLine();
					#endif
					break;
				}

				default:
					#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
					UnrecognizedLine();
					#endif
					break;
			}
		}

		return true;
	}