示例#1
0
Appcast Appcast::Load(const std::string& xml)
{
    XML_Parser p = XML_ParserCreateNS(NULL, NS_SEP);
    if ( !p )
        throw std::runtime_error("Failed to create XML parser.");

    ContextData ctxt(p);

    XML_SetUserData(p, &ctxt);
    XML_SetElementHandler(p, OnStartElement, OnEndElement);
    XML_SetCharacterDataHandler(p, OnText);

    XML_Status st = XML_Parse(p, xml.c_str(), (int)xml.size(), XML_TRUE);

    if ( st == XML_STATUS_ERROR )
    {
        std::string msg("XML parser error: ");
        msg.append(XML_ErrorString(XML_GetErrorCode(p)));
        XML_ParserFree(p);
        throw std::runtime_error(msg);
    }

    XML_ParserFree(p);

    if (ctxt.items.empty())
        return Appcast(); // invalid

    /*
     * Search for first <item> which specifies with the attribute sparkle:os set to "windows"
     * or "windows-x64"/"windows-x86" based on this modules bitness and meets the minimum
     * os version, if set. If none, use the first item that meets the minimum os version, if set.
     */
    std::vector<Appcast>::iterator it = std::find_if(ctxt.items.begin(), ctxt.items.end(), is_suitable_windows_item);
    if (it != ctxt.items.end())
        return *it;
    else
    {
        it = std::find_if(ctxt.items.begin(), ctxt.items.end(), is_windows_version_acceptable);
        if (it != ctxt.items.end())
            return *it;
        else 
            return Appcast(); // There are no items that meet the set minimum os version
    }
}
int _xml_papi_hwi_setup_all_presets(char *arch, hwi_dev_notes_t *notes) {
   int done = 0;
   FILE *fp = fopen("./papi_events.xml", "r");
   XML_Parser p = XML_ParserCreate(NULL);

   if(!p) {
      PAPIERROR("Couldn't allocate memory for XML parser.");
      return(PAPI_ESYS);
   }
   XML_SetElementHandler(p, _xml_start, _xml_end);
   XML_SetCharacterDataHandler(p, _xml_content);
   if(fp==NULL) {
      PAPIERROR("Error opening Preset XML file.");
      return(PAPI_ESYS);
   }

   xml_arch = arch;

   do {
      int len;
      void *buffer = XML_GetBuffer(p, BUFFSIZE);

      if(buffer==NULL) {
         PAPIERROR("Couldn't allocate memory for XML buffer.");
         return(PAPI_ESYS);
      }
      len = fread(buffer, 1, BUFFSIZE, fp);
      if(ferror(fp)) {
         PAPIERROR("XML read error.");
         return(PAPI_ESYS);
      }
      done = feof(fp);
      if(!XML_ParseBuffer(p, len, len == 0)) {
         PAPIERROR("Parse error at line %d:\n%s\n",
         XML_GetCurrentLineNumber(p),
         XML_ErrorString(XML_GetErrorCode(p)));
         return(PAPI_ESYS);
      }
      if(error) return(PAPI_ESYS);
   } while(!done);
   XML_ParserFree(p);
   fclose(fp);
   return(PAPI_OK);
}
示例#3
0
int
mb_kbd_config_load(MBKeyboard *kbd, char *variant)
{
  char                  *data;
  XML_Parser             p;
  MBKeyboardConfigState *state;

  if ((data = config_load_file(kbd, variant)) == NULL)
    util_fatal_error("Couldn't find a keyboard config file\n");

  p = XML_ParserCreate(NULL);

  if (!p) 
    util_fatal_error("Couldn't allocate memory for XML parser\n");

  if (variant && !strstr(kbd->config_file, variant))
    fprintf(stderr, 
	    "matchbox-keyboard: *Warning* Unable to locate variant: %s\n"
	    "                   falling back to %s\n",
	    variant, kbd->config_file);

  state = util_malloc0(sizeof(MBKeyboardConfigState));

  state->keyboard = kbd;
  state->parser = p;

  XML_SetElementHandler(p, config_xml_start_cb, NULL);

  /* XML_SetCharacterDataHandler(p, chars); */

  XML_SetUserData(p, (void *)state);

  if (! XML_Parse(p, data, strlen(data), 1)) {
    fprintf(stderr, 
	    "matchbox-keyboard:%s:%d: XML Parse error:%s\n",
	    kbd->config_file,
	    XML_GetCurrentLineNumber(p),
	    XML_ErrorString(XML_GetErrorCode(p)));
    util_fatal_error("XML Parse failed.\n");
  }

  return 1;
}
示例#4
0
文件: apr_xml.c 项目: Ga-vin/apache
static apr_status_t do_parse(apr_xml_parser *parser,
                             const char *data, apr_size_t len,
                             int is_final)
{
    if (parser->xp == NULL) {
        parser->error = APR_XML_ERROR_PARSE_DONE;
    }
    else {
        int rv = XML_Parse(parser->xp, data, (int)len, is_final);

        if (rv == 0) {
            parser->error = APR_XML_ERROR_EXPAT;
            parser->xp_err = XML_GetErrorCode(parser->xp);
        }
    }

    /* ### better error code? */
    return parser->error ? APR_EGENERAL : APR_SUCCESS;
}
示例#5
0
xps_item_t *
xps_parse_xml(xps_context_t *ctx, byte *buf, int len)
{
    xps_parser_t parser;
    XML_Parser xp;
    int code;

    parser.ctx = ctx;
    parser.root = NULL;
    parser.head = NULL;
    parser.error = NULL;
    parser.compat = 0;

    xp = XML_ParserCreateNS(NULL, ' ');
    if (!xp)
    {
        gs_throw(-1, "xml error: could not create expat parser");
        return NULL;
    }

    XML_SetUserData(xp, &parser);
    XML_SetParamEntityParsing(xp, XML_PARAM_ENTITY_PARSING_NEVER);
    XML_SetStartElementHandler(xp, (XML_StartElementHandler)on_open_tag);
    XML_SetEndElementHandler(xp, (XML_EndElementHandler)on_close_tag);
    XML_SetCharacterDataHandler(xp, (XML_CharacterDataHandler)on_text);

    code = XML_Parse(xp, (char*)buf, len, 1);
    if (code == 0)
    {
        if (parser.root)
            xps_free_item(ctx, parser.root);
        XML_ParserFree(xp);
        gs_throw1(-1, "xml error: %s", XML_ErrorString(XML_GetErrorCode(xp)));
        return NULL;
    }

    XML_ParserFree(xp);

    if (parser.compat)
        xps_process_compatibility(ctx, parser.root);

    return parser.root;
}
SkXMLPullParser::EventType SkXMLPullParser::onNextToken()
{
    if (Data::RETURN_END_TAG == fImpl->fData.fState)
    {
        fImpl->fData.fState = Data::NORMAL;
        fCurr.fName = fImpl->fData.fEndTag; // restore name from (below) save
        return SkXMLPullParser::END_TAG;
    }

    fImpl->fData.fAlloc.reuse();

    XML_Parser p = fImpl->fData.fParser;
    XML_Status status;

    status = XML_ResumeParser(p);
    
CHECK_STATUS:
    switch (status) {
    case XML_STATUS_OK:
        return SkXMLPullParser::END_DOCUMENT;

    case XML_STATUS_ERROR:
        if (XML_GetErrorCode(p) != XML_ERROR_NOT_SUSPENDED)
        {
            reportError(p);
            return SkXMLPullParser::ERROR;
        }
        status = XML_Parse(p, (const char*)fImpl->fBuffer, fImpl->fBufferLen, true);
        goto CHECK_STATUS;

    case XML_STATUS_SUSPENDED:
        if (Data::MISSED_START_TAG == fImpl->fData.fState)
        {
            // return a start_tag, and clear the flag so we return end_tag next
            SkASSERT(SkXMLPullParser::END_TAG == fCurr.fEventType);
            fImpl->fData.fState = Data::RETURN_END_TAG;
            fImpl->fData.fEndTag = fCurr.fName;  // save this pointer            
            return SkXMLPullParser::START_TAG;
        }
        break;
    }
    return fCurr.fEventType;
}
示例#7
0
/************************************************************************
* 函数名: my_xml_parse
* 作  者: sx
* 描  述: 1.封装了expat的解析函数,供xml2struct内部调用
*         2.内部函数
* 输入参数: PARSER_FUN_PARAM *pf,数据集合
*           char *xml_string,顾名思义
* 输出参数: 无
* 返回值: 0表示成功,>0表示错误编号
************************************************************************/
int my_xml_parse(PARSER_FUN_PARAM *pf, char *xml_string, int xml_len)
{
    XML_Parser p;

    p = XML_ParserCreate( NULL );
    if (!p)
    {
        logger(TLOG_ERROR,  "XML_ParserCreate failed!\n" );
        return -1;
    }

//	logger(TLOG_NOTICE,  "XML_ParserCreate success!\n" );

    /* 向句柄上设定准备开始和结束签条 */
    XML_SetElementHandler( p, start_xml, end_xml );

    /* 设置元素内文本的处理函数 */
    XML_SetCharacterDataHandler( p, chardatahandle );

    /* 一次性解析完 */
    //xml_len = strlen( xml_string );

    /* 设置一个共享的数据结构给各各处理函数使用 */
    XML_SetUserData( p, pf );

    /* 把GBK,GB2312等不识别的编码,过滤掉,因为目前仅认为传过来的是英文 */
    XML_SetUnknownEncodingHandler( p, XMLEncodingHandle, 0 );
    if (XML_Parse( p, xml_string, xml_len, 1 ) == XML_STATUS_ERROR)
    {
#if 1
        logger(TLOG_ERROR, "Parse error at line %" XML_FMT_INT_MOD "u:\n%s\n",
            XML_GetCurrentLineNumber( p ),
            XML_ErrorString(XML_GetErrorCode( p ) ) );
        /* 释放被解析器使用的内存。*/
#endif
        XML_ParserFree( p );
		logger(TLOG_ERROR,  "XML_Parse failed!\n" );
        return -1;
    }
    /* 释放被解析器使用的内存。*/
    XML_ParserFree( p );
    return pf->ret_err;
}
示例#8
0
void 
OMXMLReaderExpat::entityDeclHandler(const XML_Char *entityName, 
    int is_parameter_entity, const XML_Char *value, int value_length, 
    const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, 
    const XML_Char *notationName)
{
    TRACE("OMXMLReaderExpat::entityDeclHandler");

    // only report unparsed (external) entity declarations
    if (is_parameter_entity == 0 && value == 0 && systemId != 0 && notationName != 0)
    {
        wchar_t* workBuffer = getWorkBuffer(xmlStringLen(entityName) + 1);
        OMUInt32 strLen = readCharacters(workBuffer, entityName, 0);
        _name = workBuffer;
        
        workBuffer = getWorkBuffer(xmlStringLen(systemId) + 1);
        strLen = readCharacters(workBuffer, systemId, 0);
        _systemID = workBuffer;
        
        if (publicId != 0)
        {
            workBuffer = getWorkBuffer(xmlStringLen(publicId) + 1);
            strLen = readCharacters(workBuffer, publicId, 0);
            _publicID = workBuffer;
        }
        else
        {
            _publicID = L"";
        }
        
        XML_Status status = XML_StopParser(_parser, true);
        if (status != XML_STATUS_OK)
        {
            XML_Error errorCode = XML_GetErrorCode(_parser);
            if (errorCode != XML_ERROR_SUSPENDED)
            {
                throw OMException(getErrorString());
            }
        }
    
        registerEvent(UNPARSED_ENTITY_DECL);
    }
}
示例#9
0
int main(int argc, char **argv) {
    AppData *ad;
    XML_Parser p = XML_ParserCreateNS(NULL, '|');
    if (! p) {
        fprintf(stderr, "Couldn't allocate memory for parser\n");
        exit(-1);
    }

    ad = newAppData();

    XML_SetUserData(p, (void *) ad);
    XML_SetElementHandler(p, start, end);
    XML_SetNamespaceDeclHandler(p, ns_start, ns_end);

    for (;;) {
        char *buff;
        int len;

        buff = XML_GetBuffer(p, CHUNK_SIZE);
        if (! buff) {
            fprintf(stderr, "Ran out of memory for parse buffer\n");
            exit(-1);
        }

        len = read(0, buff, CHUNK_SIZE);
        if (len < 0) {
            perror("namespace - read error");
            exit(-1);
        }

        if (! XML_ParseBuffer(p, len, len == 0)) {
            fprintf(stderr, "Parse error at line %lu:\n%s\n",
                    XML_GetCurrentLineNumber(p),
                    XML_ErrorString(XML_GetErrorCode(p)));
            exit(-1);
        }

        if (len == 0)
            break;
    }

    return 0;
}  /* End main */
示例#10
0
//////////////////////////////////////////////////////////////////////////////////
/// Parse the fmu. The receiver must call freeElement(md) to release AST memory.
///
///\param xmlPath The xml file to be parsed
///\return the root node md of the AST if no error occurred. NULL to indicate failure
/////////////////////////////////////////////////////////////////////////////////
ModelDescription* parse(const char* xmlPath) {
  ModelDescription* md = NULL;
  FILE *file;
  int done = 0;

  stack = stackNew(100, 10); // Allocate stack memory	  
  if (checkPointer(stack)) return NULL;  // Check if the stack is creatted

  parser = XML_ParserCreate(NULL); // Create an parser
  if (checkPointer(parser)) return NULL;  // Check if the parser is created

  XML_SetElementHandler(parser, startElement, endElement); // Set handler for start and end tags
  XML_SetCharacterDataHandler(parser, handleData); // Set handler for text

	file = fopen(xmlPath, "rb");

	if (file == NULL) {
    printfError("Cannot open file '%s'\n", xmlPath);
    XML_ParserFree(parser); // Free the memory for parser
    return NULL; // Failure
  }

  while (!done) {
    int n = fread(text, sizeof(char), XMLBUFSIZE, file); // Read XMLBUFSIZE characters from file
    if (n != XMLBUFSIZE) done = 1; // Reach the end of file
    if (!XML_Parse(parser, text, n, done)){
      printf("Parse error in file %s at line %d:\n%s\n",
             xmlPath,
             (int)XML_GetCurrentLineNumber(parser),
              XML_ErrorString(XML_GetErrorCode(parser)));
      while (!stackIsEmpty(stack)) md = stackPop(stack);
      if (md) freeElement(md);
      cleanup(file);
      return NULL; // failure
    }
  }

  md = stackPop(stack);
  assert(stackIsEmpty(stack));
  cleanup(file);
  //printElement(1, md); // Print the element for debugging
  return md; // Success if all refs are valid    
}
示例#11
0
/* attempts to parse the buff onto this stream firing events to the handler, returns the last known status */
int xode_stream_eat(xode_stream xs, char *buff, int len)
{
    char *err;
    xode xerr;
    static char maxerr[] = "maximum node size reached";
    static char deeperr[] = "maximum node depth reached";

    if(xs == NULL)
    {
        fprintf(stderr,"Fatal Programming Error: xode_streameat() was improperly called with NULL.\n");
        return XODE_STREAM_ERROR;
    }

    if(len == 0 || buff == NULL)
        return xs->status;

    if(len == -1) /* easy for hand-fed eat calls */
        len = strlen(buff);

    if(!XML_Parse(xs->parser, buff, len, 0))
    {
        err = (char *)XML_ErrorString(XML_GetErrorCode(xs->parser));
        xs->status = XODE_STREAM_ERROR;
    }else if(xode_pool_size(xode_get_pool(xs->node)) > XODE_STREAM_MAXNODE || xs->cdata_len > XODE_STREAM_MAXNODE){
        err = maxerr;
        xs->status = XODE_STREAM_ERROR;
    }else if(xs->status == XODE_STREAM_ERROR){ /* set within expat handlers */
        err = deeperr;
    }else{
        err = deeperr;
    }

    /* fire parsing error event, make a node containing the error string */
    if(xs->status == XODE_STREAM_ERROR)
    {
        xerr = xode_new("error");
        xode_insert_cdata(xerr,err,-1);
        (xs->f)(XODE_STREAM_ERROR, xerr, xs->arg);
    }

    return xs->status;
}
示例#12
0
/// do actual parse, firing events a& returning true if all went well
/// need to create expat parser each time we dparse as its a one shot device
bool ParserImpl :: Parse( const string & s ) {

    if ( mExpat ) {
        XML_ParserFree( mExpat );
    }

    mExpat = XML_ParserCreate( 0 );
    XML_SetElementHandler( mExpat, StartElementHandler, EndElementHandler );
    XML_SetCharacterDataHandler( mExpat, CharDataHandler );
    XML_SetUserData( mExpat, this );

    unsigned int err = XML_Parse(  mExpat, s.c_str(), s.size(), 1 );
    if ( err == 0 ) {
        mErrorCode = XML_GetErrorCode( mExpat );
        mErrorMsg  = XML_ErrorString( XML_Error( err ) );
        mErrorLine = XML_GetCurrentLineNumber( mExpat );
    }

    return err != 0;
}
示例#13
0
文件: config.c 项目: koushik2506/exp
void parse_conf() {

	FILE *conf_file;
	char *buffer;
	XML_Parser p = XML_ParserCreate(NULL);

	if ( (conf_file = fopen(CONF_FILE,"r")) == NULL ) {
		perror("Error opening config file\n");
		exit(1);
	}

	buffer = (char *)malloc(sizeof(char) * 1024);

	XML_SetStartElementHandler(p,start_element);

	while(1) {
		int len,done;

		len = fread(buffer,1,1024,conf_file);

		if (ferror(conf_file)) {
			perror("Error reading config file\n");
			exit(1);
		}

		done = feof(conf_file);

		if ( !XML_Parse(p,buffer,len,done) ) {
			fprintf(stderr, "Parse error at line %d:\n%s\n", 
					XML_GetCurrentLineNumber(p),
					XML_ErrorString(XML_GetErrorCode(p)));
			exit(1);
		}

		if(done) break;
	}
	fclose(conf_file);
	XML_ParserFree(p);
	free(buffer);

}
示例#14
0
文件: xmlfile.cpp 项目: crazii/mameui
xml_data_node *xml_data_node::file_read(util::core_file &file, xml_parse_options const *opts)
{
	xml_parse_info info;
	int done;

	/* set up the parser */
	if (!expat_setup_parser(info, opts))
		return nullptr;

	/* loop through the file and parse it */
	do
	{
		char tempbuf[TEMP_BUFFER_SIZE];

		/* read as much as we can */
		int bytes = file.read(tempbuf, sizeof(tempbuf));
		done = file.eof();

		/* parse the data */
		if (XML_Parse(info.parser, tempbuf, bytes, done) == XML_STATUS_ERROR)
		{
			if (opts != nullptr && opts->error != nullptr)
			{
				opts->error->error_message = XML_ErrorString(XML_GetErrorCode(info.parser));
				opts->error->error_line = XML_GetCurrentLineNumber(info.parser);
				opts->error->error_column = XML_GetCurrentColumnNumber(info.parser);
			}

			info.rootnode->file_free();
			XML_ParserFree(info.parser);
			return nullptr;
		}
	}
	while (!done);

	/* free the parser */
	XML_ParserFree(info.parser);

	/* return the root node */
	return info.rootnode;
}
示例#15
0
xml_data_node *xml_file_read(mame_file *file, xml_parse_options *opts)
{
	xml_parse_info parse_info;
	int done;

	/* set up the parser */
	if (!setup_parser(&parse_info, opts))
		return NULL;

	/* loop through the file and parse it */
	do
	{
		char tempbuf[TEMP_BUFFER_SIZE];

		/* read as much as we can */
		int bytes = mame_fread(file, tempbuf, sizeof(tempbuf));
		done = mame_feof(file);

		/* parse the data */
		if (XML_Parse(parse_info.parser, tempbuf, bytes, done) == XML_STATUS_ERROR)
		{
			if (opts && opts->error)
		{
				opts->error->error_message = XML_ErrorString(XML_GetErrorCode(parse_info.parser));
				opts->error->error_line = XML_GetCurrentLineNumber(parse_info.parser);
				opts->error->error_column = XML_GetCurrentColumnNumber(parse_info.parser);
			}

			xml_file_free(parse_info.rootnode);
			XML_ParserFree(parse_info.parser);
			return NULL;
		}

	} while (!done);

	/* free the parser */
	XML_ParserFree(parse_info.parser);

	/* return the root node */
	return parse_info.rootnode;
}
示例#16
0
END_TEST

/* Regression test for SF bug #1515266: missing check of stopped
   parser in doContext() 'for' loop. */
START_TEST(test_suspend_parser_between_char_data_calls)
{
    /* The sample data must be big enough that there are two calls to
       the character data handler from within the inner "for" loop of
       the XML_TOK_DATA_CHARS case in doContent(), and the character
       handler must stop the parser and clear the character data
       handler.
    */
    char *text = long_character_data_text;

    XML_SetCharacterDataHandler(parser, clearing_aborting_character_handler);
    resumable = XML_TRUE;
    if (XML_Parse(parser, text, strlen(text), XML_TRUE) != XML_STATUS_SUSPENDED)
        xml_failure(parser);
    if (XML_GetErrorCode(parser) != XML_ERROR_NONE)
        xml_failure(parser);
}
示例#17
0
/**
 * Parse an XML string into a nested list.
 * The second parameter indicates if body text (text within XML tags)
 * should show up among the children of the tag or in its own
 * section.
 *
 * See documentation (ext-xml.README) for examples.
 */
static package 
parse_xml(const char *data, int bool_stream)
  {
  /*
   * FIXME: Feed expat smaller chunks of the string and 
   * check for task timeout between chunks
   *
   */
  int decoded_length;
  const char *decoded;
  package result; 
  XML_Parser parser = XML_ParserCreate(NULL);
  XMLdata *root = new_node(NULL, "");
  XMLdata *child = root;
  
  decoded_length = strlen(data);
  decoded = data;
  XML_SetUserData(parser, &child);
  XML_SetElementHandler(parser, xml_startElement, xml_endElement);
  if(bool_stream) {
    XML_SetCharacterDataHandler(parser, xml_streamCharacterDataHandler);
  } else {
    XML_SetCharacterDataHandler(parser, xml_characterDataHandler);
  }
  if (!XML_Parse(parser, decoded, decoded_length, 1)) {
    Var r;
    r.type = TYPE_INT;
    r.v.num = XML_GetCurrentByteIndex(parser);
    flush_nodes(child);
    result = make_raise_pack(E_INVARG, 
			     XML_ErrorString(XML_GetErrorCode(parser)),
			     r);
  } else {
    finish_node(root);
    result = make_var_pack(var_ref(root->element.v.list[4].v.list[1]));
    free_node(root);
  }
  XML_ParserFree(parser);
  return result; 
}
示例#18
0
bool XMLFileReader::Parse(XMLTagHandler *baseHandler,
                          const wxString &fname)
{
   wxFFile theXMLFile(fname, wxT("rb"));
   if (!theXMLFile.IsOpened()) {
      wxString errStr;
      mErrorStr.Printf(_("Could not open file: \"%s\""), fname.c_str());
      return false;
   }

   mBaseHandler = baseHandler;
   mHandler[0] = NULL;

   const size_t bufferSize = 16384;
   char buffer[16384];
   int done = 0;
   do {
      size_t len = fread(buffer, 1, bufferSize, theXMLFile.fp());
      done = (len < bufferSize);
      if (!XML_Parse(mParser, buffer, len, done)) {
         mErrorStr.Printf(_("Error: %hs at line %d"),
			  XML_ErrorString(XML_GetErrorCode(mParser)),
			  XML_GetCurrentLineNumber(mParser));
         theXMLFile.Close();
         return false;
      }
   } while (!done);

   theXMLFile.Close();

   // Even though there were no parse errors, we only succeed if
   // the first-level handler actually got called, and didn't
   // return false.
   if (mHandler[0])
      return true;
   else {
      mErrorStr.Printf(_("Unable to open project file."));
      return false;
   }
}
示例#19
0
static class s3_result *xml_extract_response(const class buffer *buf) 
{
    class s3_result *e = new s3_result();

    e->buf = buf;
    XML_Parser parser = XML_ParserCreate(NULL);
    XML_SetUserData(parser, e);
    XML_SetElementHandler(parser, startElement, endElement);
    XML_SetCharacterDataHandler(parser,characterDataHandler);

    if (!XML_Parse(parser, (const char *)buf->base, buf->len, 1)) {
	char buf2[2048];
	snprintf(buf2,sizeof(buf2),
		 "XML Error: %s at line %d",
		 XML_ErrorString(XML_GetErrorCode(parser)),(int)XML_GetCurrentLineNumber(parser));
	fprintf(stderr,"%s:\n",buf2);
	XML_ParserFree(parser);
	return 0;
    }
    XML_ParserFree(parser);
    return e;
}
示例#20
0
bool SkXMLParser::parse(SkStream& docStream)
{
    ParsingContext ctx(this);
    if (!ctx.fXMLParser) {
        SkDebugf("could not create XML parser\n");
        return false;
    }

    XML_SetUserData(ctx.fXMLParser, &ctx);
    XML_SetElementHandler(ctx.fXMLParser, start_element_handler, end_element_handler);
    XML_SetCharacterDataHandler(ctx.fXMLParser, text_handler);

    // Disable entity processing, to inhibit internal entity expansion. See expat CVE-2013-0340.
    XML_SetEntityDeclHandler(ctx.fXMLParser, entity_decl_handler);

    static const int kBufferSize = 512 SkDEBUGCODE( - 507);
    bool done = false;
    do {
        void* buffer = XML_GetBuffer(ctx.fXMLParser, kBufferSize);
        if (!buffer) {
            SkDebugf("could not buffer enough to continue\n");
            return false;
        }

        size_t len = docStream.read(buffer, kBufferSize);
        done = docStream.isAtEnd();
        XML_Status status = XML_ParseBuffer(ctx.fXMLParser, SkToS32(len), done);
        if (XML_STATUS_ERROR == status) {
            XML_Error error = XML_GetErrorCode(ctx.fXMLParser);
            int line = XML_GetCurrentLineNumber(ctx.fXMLParser);
            int column = XML_GetCurrentColumnNumber(ctx.fXMLParser);
            const XML_LChar* errorString = XML_ErrorString(error);
            SkDebugf("parse error @%d:%d: %d (%s).\n", line, column, error, errorString);
            return false;
        }
    } while (!done);

    return true;
}
示例#21
0
int main()
{	
  char filename[80];
  FILE* xmlFile;
  char buf[BUFSIZ];
  for (;;) {	  
	  XML_Parser parser;
	  int done;
	  int depth = 0;

	  puts("\n\nXML test: enter filename");
	  gets(filename);
	  if (strlen(filename)==0)
	  	break;
	  	
	  xmlFile = fopen(filename, "r");
	  if (!xmlFile)
	  	break;

	  parser = XML_ParserCreate(NULL);
	  XML_SetUserData(parser, &depth);
	  XML_SetElementHandler(parser, startElement, endElement);
	  XML_SetCharacterDataHandler(parser, charData);
	  do {
	    size_t len = fread(buf, 1, sizeof(buf), xmlFile /*stdin*/);
	    done = len < sizeof(buf);
	    if (!XML_Parse(parser, buf, len, done)) {
	      fprintf(stderr,
		      "%s at line %d\n",
		      XML_ErrorString(XML_GetErrorCode(parser)),
		      XML_GetCurrentLineNumber(parser));
	      return 1;
	    }
	  } while (!done);
	  XML_ParserFree(parser);
/*	  return 0;  */
  }
  puts("\nfinished!");
}
示例#22
0
int XMLParser::Parse(XMLParserCallback& rCallback, const char* chFileName) {
  int ret = 1;  // File not found

  FILE* fp = fopen(chFileName, "rb");
  if (fp) {
    XML_Parser parser = XML_ParserCreate(NULL);

    XML_SetUserData(parser, static_cast<void*>(&rCallback));

    // register Callbacks for start- and end-element events of the parser:
    XML_SetElementHandler(parser, startElement, endElement);

    int done;
    do {  // loop over whole file content
      char buf[BUFSIZ];
      size_t len = fread(buf, 1, sizeof(buf), fp);    // read chunk of data
      // end of file reached if buffer not completely filled
      done = len < sizeof(buf);
      if (!XML_Parse(parser, buf, static_cast<int>(len), done)) {
        // a parse error occurred:
          std::cerr <<
            XML_ErrorString(XML_GetErrorCode(parser))
            << " at line "
            << static_cast<int>(XML_GetCurrentLineNumber(parser));
        fclose(fp);
        ret = 2;    // quit, return = 2 indicating parsing error
        done = 1;
        return ret;
      }
    } while (!done);

    XML_ParserFree(parser);
    fclose(fp);
    ret = 0;
  } else {
      std::cerr <<  "Error opening " << chFileName << ":" << strerror(errno);
  }
  return ret;  // return = 0 indicating success
}
示例#23
0
文件: messdocs.c 项目: cdenix/psmame
static void ATTR_PRINTF(3,4) process_error(struct messdocs_state *state, const char *tag, const char *msgfmt, ...)
{
	/*va_list va;*/
	/*char buf[512];*/
	const char *msg;

	if (msgfmt)
	{
		//va_start(va, msgfmt);
		//vsprintf(buf, msgfmt, va);
		//va_end(va);
		//msg = buf;
		msg = "";
	}
	else
	{
		msg = XML_ErrorString(XML_GetErrorCode(state->m_parser));
	}

	fprintf(stderr, "%u:%s:%s\n", (unsigned) XML_GetCurrentLineNumber(state->m_parser), tag ? tag : "", msg);
	state->m_error = 1;
}
示例#24
0
int main()
{
  char buf[BUFSIZ];
  XML_Parser parser = XML_ParserCreate(NULL);
  int done;
  int depth = 0;
  XML_SetUserData(parser, &depth);
  XML_SetElementHandler(parser, startElement, endElement);
  do {
    size_t len = fread(buf, 1, sizeof(buf), stdin);
    done = len < sizeof(buf);
    if (!XML_Parse(parser, buf, len, done)) {
      fprintf(stderr,
	      "%s at line %d\n",
	      XML_ErrorString(XML_GetErrorCode(parser)),
	      XML_GetCurrentLineNumber(parser));
      return 1;
    }
  } while (!done);
  XML_ParserFree(parser);
  return 0;
}
示例#25
0
int
main(int argc, char *argv[])
{
  XML_Parser p = XML_ParserCreate(NULL);
  (void)argc;
  (void)argv;

  if (! p) {
    fprintf(stderr, "Couldn't allocate memory for parser\n");
    exit(-1);
  }

  XML_SetElementHandler(p, start, end);

  for (;;) {
    int done;
    int len;

    len = (int)fread(Buff, 1, BUFFSIZE, stdin);
    if (ferror(stdin)) {
      fprintf(stderr, "Read error\n");
      exit(-1);
    }
    done = feof(stdin);

    if (XML_Parse(p, Buff, len, done) == XML_STATUS_ERROR) {
      fprintf(stderr,
              "Parse error at line %" XML_FMT_INT_MOD "u:\n%" XML_FMT_STR "\n",
              XML_GetCurrentLineNumber(p),
              XML_ErrorString(XML_GetErrorCode(p)));
      exit(-1);
    }

    if (done)
      break;
  }
  XML_ParserFree(p);
  return 0;
}
示例#26
0
int RS_XML(parseWithParserData)(FILE *file, RS_XMLParserData *parserData)
{
  char buf[BUFSIZ];
  int done;
  XML_Parser parser = XML_ParserCreate(NULL);

  RS_XML(initParser)(parser, parserData);
  do {
    size_t len = fread(buf, 1, sizeof(buf), file);
    done = len < sizeof(buf);
    if (!XML_Parse(parser, buf, len, done)) {
      PROBLEM 
	      "%s at line %d\n",
	      XML_ErrorString(XML_GetErrorCode(parser)),
   	      XML_GetCurrentLineNumber(parser)
        WARN;
      return 1;
    }
  } while (!done);
  XML_ParserFree(parser);
  return 0;
}
int main(int argc, char **argv) {
  XML_Parser p = XML_ParserCreate(NULL);
  if (! p) {
    fprintf(stderr, "Couldn't allocate memory for parser\n");
    exit(-1);
  }

  XML_UseParserAsHandlerArg(p);
  XML_SetElementHandler(p, start_hndl, end_hndl);
  XML_SetCharacterDataHandler(p, char_hndl);
  XML_SetProcessingInstructionHandler(p, proc_hndl);

  /* Notice that the default handler is not set at this point */

  for (;;) {
    int done;
    int len;
    fgets(Buff, sizeof(Buff), stdin);
    len = strlen(Buff);
    if (ferror(stdin)) {
      fprintf(stderr, "Read error\n");
      exit(-1);
    }
    done = feof(stdin);
    if (! XML_Parse(p, Buff, len, done)) {
      fprintf(stderr, "Parse error at line %lu:\n%s\n",
	      XML_GetCurrentLineNumber(p),
	      XML_ErrorString(XML_GetErrorCode(p)));
      exit(-1);
    }

    if (done)
      break;
  }
  printf("\n");

  return 0;
}  /* End main */
示例#28
0
int
main(int argc, char *argv[])
{
  char buf[BUFSIZ];
  XML_Parser parser = XML_ParserCreate(NULL);
  int done;
  int depth = 0;
  XML_SetUserData(parser, &depth);
  XML_SetElementHandler(parser, startElement, endElement);
  do {
    int len = (int)fread(buf, 1, sizeof(buf), stdin);
    done = len < sizeof(buf);
    if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
      fprintf(stderr,
              "%s at line %" XML_FMT_INT_MOD "u\n",
              XML_ErrorString(XML_GetErrorCode(parser)),
              XML_GetCurrentLineNumber(parser));
      return 1;
    }
  } while (!done);
  XML_ParserFree(parser);
  return 0;
}
示例#29
0
int
expatElement(void)
{
  char buf[BUFSIZ];
  static char * text[] =
  {
        "<hello field=\"field1\">\n" ,
        "   <howdy something=\"something2\"/>\n" ,
        "</hello>\n" ,
        ""
  } ;
  const int numLines = sizeof( text ) / sizeof( text[ 0 ] ) ;
  XML_Parser parser = XML_ParserCreate(NULL);
  int done;
  int depth = 0;
  int line = 0 ;

  DebugPrint( "expatElement:\n" );

  XML_SetUserData(parser, &depth);
  XML_SetElementHandler(parser, startElement, endElement);
  do {
    done = ( line == numLines - 1 ) ;
    int len  = strlen( text[ line ] ) ;
    memcpy( buf, text[ line ], len + 1 ) ;
    ++ line ;
    if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
      DebugPrint(
              "%s at line %d\n",
              XML_ErrorString(XML_GetErrorCode(parser)),
              XML_GetCurrentLineNumber(parser));
      return 1;
    }
  } while (!done);
  XML_ParserFree(parser);
  return 0;
}
示例#30
0
		// ----------------------------------------------------------------------
        void
        	SAXReader::
            parse()
            throw(std::runtime_error)
        {
            char buf[16384];
            int len;

            //Open the file
            open_file();

            //Create the SAX parser and register the C-Style handlers which will call back on this object instace
			parser = XML_ParserCreate(NULL);
			XML_SetUserData(parser, (void*)this);
			XML_SetElementHandler(parser, saxreader_start, saxreader_end);
			XML_SetCharacterDataHandler(parser, saxreader_text);

            //Read the file until the end of file
            while( !is_->eof() && !stop_flag_ )
            {
            	is_->read( buf, sizeof(buf) );
				len = is_->gcount();

				if (XML_Parse(parser, buf, len, is_->eof()) == XML_STATUS_ERROR)
				{
					 ERROR(logger(), XML_ErrorString(XML_GetErrorCode(parser)) <<
					         "at line " << XML_GetCurrentLineNumber(parser));
				    reset();
				    throw std::runtime_error("Error in parsing XML input");
				}
            }

            //Done -> Close the file and free all associated memory
			parsing_done();
            reset();
			XML_ParserFree(parser);
        }