std::set<std::string> FileSniffer::getLastResult()
{
	std::set<std::string> lastresult;
	try{
		
		std::string* resultfile = new std::string();
		if(fexists(resultFilePath.c_str()))	//Check if result text file exists
		{
			resultfile = loadFile(resultFilePath);
			XmlReader rdr(*resultfile);
			while(rdr.next())		
			{							//Scan through the xml and search for filepath tag
				if(rdr.tag() == "listsize")
				{
					if(rdr.body() == "0")
						break;
				}
				if(rdr.tag() == "filepath")
					lastresult.insert(rdr.body());
			}
			delete resultfile;
		}
		
	}catch(std::exception& ex){
    std::cout << "\n\n    " << ex.what() << "\n\n"; }	
	return lastresult;
}
//////////////////////////////////////////////////////////////
///Checks if the specified path is the excluded paths
inline bool FileSniffer::isInExcluded(std::string path)
{
	try{
		std::string::reverse_iterator rit;
	rit=path.rbegin();
	if(!path.empty() && *rit=='.')	//remove . and .. dirctories from paths
		return true;
	if(excludeFileExists == false)	//return if excludefile does not exist
		return false;
	
	XmlReader rdr(*excludeFile);
	std::string dirpath;
	while(rdr.next())
	{
		if(rdr.tag() == "exclude")	//get exclude paths
		{
			dirpath = rdr.body();
			int found=path.find(dirpath);	//check if current path is in the exclude list
			if (found!=std::string::npos)	
				return true;
		}
	}
	}catch(std::exception& ex){
      std::cout << "\n\n    " << ex.what() << "\n\n"; }	
	return false;
}
Exemplo n.º 3
0
std::vector<grpprl> DocReader::GetCLXGrpprls()
{
	std::vector<grpprl> vecResults;

	WordFileReader rdr(m_sfr, GetTableStreamName(), GetStartComplexFilePart(), GetSizeComplexFilePart());

	while (rdr.GetSize())
	{
		CplxPartHeader hdr;
		WordFileReader rdr2 = rdr;
		rdr.Read(&hdr, 5);

		if (hdr.iType == 1) // a grpprl
		{
			rdr2 += 1;
			vecResults.push_back(grpprl(rdr2));

			rdr += hdr.iGrpplLen - 2;
		}
		else if (hdr.iType == 2) // piece table
		{
			rdr += hdr.iPctblLen;
		} 
		else  // we're in trouble - probably got the offsets wrong
		{
			_ASSERT(false);
		}
	}

	return vecResults;
}
Exemplo n.º 4
0
bool TGAImageDecoder::LoadRLE(DataStream* ds,ImageImpl* img) {
    Byte* data = img->GetRawData()->GetDataPtr();
    UInt32 pixels = img->GetWidth()*img->GetHeight();
    const UInt32 bpp = img->GetBpp();
    UInt32 c = 0;
    BufferedReader rdr(ds,2048);
    while (pixels && !rdr.Eof()) {
        /// @todo warning endianless
        rdr.Read(reinterpret_cast<Byte*> (&c),1);
        if (c < 128) {
            c++;
            if (c>pixels) c = pixels;
            data+=rdr.Read(data,c*bpp);
            pixels -= c;
        } else {
            c-=127;
            if (c>pixels) c = pixels;
            Byte* data_c = data;
            data+=rdr.Read(data,bpp);
            for(UInt32 counter = 1; counter < c; counter++)
            {
                data=copy_data(data_c,data,bpp);
            }
            pixels-= c;
        }
    }
    return pixels == 0;
}
Exemplo n.º 5
0
int dmtcp::CkptSerializer::openMtcpCheckpointFile(const dmtcp::string& path){
  int fd = openDmtcpCheckpointFile(path);
  jalib::JBinarySerializeReaderRaw rdr(path, fd);
  static ConnectionToFds cfd;
  static ProcessInfo pInfo;
  cfd.serialize(rdr);
  pInfo.serialize(rdr);
  return fd;
}
Exemplo n.º 6
0
int main(int argc, char** argv){
  CGE::LogOutputter* putty = new CGE::LogOutputter();
  CGE::TraceManager::instance()->setTraceOutputter(putty);
  if (argc <= 1){
    return -1;
  }
  PdfReader rdr(argv[1]);
  PdfDocument* doc = rdr.readDocument();
}
Exemplo n.º 7
0
		AnyValue JsonSerializer::deserialize(const std::string & str)
		{
			Json::Value root;
			Json::CharReaderBuilder rbuilder;
			rbuilder["collectComments"] = false;
			std::unique_ptr<Json::CharReader> rdr(rbuilder.newCharReader());
			if (!rdr->parse(str.data(), str.data() + str.size(), &root, nullptr))
				throw std::runtime_error("Invalid json string");
			return this->toAny(root);
		}
Exemplo n.º 8
0
rust_crate_cache::rust_sym::rust_sym(rust_dom *dom,
                                     rust_crate const *curr_crate,
                                     c_sym *crate_sym,
                                     char const **path)
    : val(0),
      crate_sym(crate_sym),
      dom(dom)
{
    crate_sym->ref();
    typedef rust_crate_reader::die die;
    rust_crate const *crate = (rust_crate*)crate_sym->get_val();
    if (!crate) {
        dom->log(rust_log::CACHE,
                 "failed to resolve symbol, null crate symbol");
        return;
    }
    rust_crate_reader rdr(dom, crate);
    bool found_root = false;
    bool found_leaf = false;
    for (die d = rdr.dies.first_die();
         !(found_root || d.is_null());
         d = d.next_sibling()) {

        die t1 = d;
        die t2 = d;
        for (char const **c = crate_rel(curr_crate, path);
             (*c
              && !t1.is_null()
              && t1.find_child_by_name(crate_rel(curr_crate, *c), t2));
             ++c, t1=t2) {
            dom->log(rust_log::DWARF|rust_log::CACHE,
                    "matched die <0x%"  PRIxPTR
                    ">, child '%s' = die<0x%" PRIxPTR ">",
                    t1.off, crate_rel(curr_crate, *c), t2.off);
            found_root = found_root || true;
            if (!*(c+1) && t2.find_num_attr(DW_AT_low_pc, val)) {
                dom->log(rust_log::DWARF|rust_log::CACHE,
                         "found relative address: 0x%"  PRIxPTR, val);
                dom->log(rust_log::DWARF|rust_log::CACHE,
                         "plus image-base 0x%"  PRIxPTR,
                         crate->get_image_base());
                val += crate->get_image_base();
                found_leaf = true;
                break;
            }
        }
        if (found_root || found_leaf)
            break;
    }
    if (found_leaf) {
        dom->log(rust_log::CACHE, "resolved symbol to 0x%"  PRIxPTR, val);
    } else {
        dom->log(rust_log::CACHE, "failed to resolve symbol");
    }
}
//////////////////////////////////////////////////////////////
///Loads database from xml file to a set
void FileSniffer::loadDatabase()
{
	try{
	databaseFile = loadFile(databaseFilePath);
	XmlReader rdr(*databaseFile);
	while(rdr.next())					//Scan through the xml and search for filepath tag
		if(rdr.tag() == "filepath")
			fileset.insert(rdr.body());	//insert filepaths into set
	}catch(std::exception& ex){
    std::cout << "\n\n    " << ex.what() << "\n\n"; }	
}
Exemplo n.º 10
0
void MainWindow::diplayfile( const QString path ) const
{
    Reader rdr( path );
    ui->lbl_c_file->setText( fname );
    ui->txt_c_file->clear();
    for (int i = 0; i < rdr.getOutput().size(); i++ )
        ui->txt_c_file->append( rdr.getOutput()[i] );

    ui->btn_run->setEnabled( true );
    ui->btn_edit_params->setEnabled( true );
}
Exemplo n.º 11
0
int dmtcp::CkptSerializer::loadFromFile(const dmtcp::string& path,
                                        dmtcp::ConnectionToFds *conToFds,
                                        dmtcp::ProcessInfo *processInfo)
{
  int fd = openDmtcpCheckpointFile(path);
  JASSERT(fd != -1);
  jalib::JBinarySerializeReaderRaw rdr(path, fd);
  conToFds->serialize(rdr);
  processInfo->serialize(rdr);
  close_ckpt_to_read(fd);
  return rdr.bytes() + strlen(DMTCP_FILE_HEADER);
}
Exemplo n.º 12
0
bool TraceLineParser::SetFormat(const char * pszFormat, size_t cch, const std::vector<char>& separators)
{
	cch = (cch == 0) ? strlen(pszFormat) : cch;
	CStringReaderA rdr(pszFormat, cch);
	_Separators.assign(separators.begin(), separators.end());
	_Fields.resize(0);

	if (!SetFormat(rdr, separators))
	{
		_Fields.resize(0);
		return false;
	}

	return true;
}
Exemplo n.º 13
0
void TraceLineParser::SetLineInfoField(LineInfo& res, FieldId id, const char * pszStart, const char * pszEnd)
{
	switch(id)
	{
	case FieldId::Time: 
		res.Time.psz = pszStart;
		res.Time.cch = pszEnd - pszStart;
		break;
	case FieldId::ThreadId:
		{
			CStringReaderA rdr(pszStart, pszEnd-pszStart);
			int ibase = 10;
			if (rdr.Length() > 2 && strncmp(rdr.P(), "0x", 2) == 0)
			{
				rdr.ReadChar();
				rdr.ReadChar();
				ibase = 16;
			}
			rdr.ReadUInt32(&res.Tid, ibase);
		}
		break;
	case FieldId::User1:
		res.User[0].psz = pszStart;
		res.User[0].cch = pszEnd - pszStart;
		break;
	case FieldId::User2:
		res.User[1].psz = pszStart;
		res.User[1].cch = pszEnd - pszStart;
		break;
	case FieldId::User3:
		res.User[2].psz = pszStart;
		res.User[2].cch = pszEnd - pszStart;
		break;
	case FieldId::User4:
		res.User[3].psz = pszStart;
		res.User[3].cch = pszEnd - pszStart;
		break;
	case FieldId::Msg:
		res.Msg.psz = pszStart;
		res.Msg.cch = pszEnd - pszStart;
		break;
	case FieldId::None:
		break;
	default:
		assert(false);
		break;
	}
}
Exemplo n.º 14
0
int main()
{
	std::cout << "\nTesting AuthXml Library";
	std::cout << "\n=======================\n\n";
	std::cout << " Creating a couple new users\n\n";

	userList ulst;

	user u1("user1","pass1",1);
	user u2("user2","pass2",2);
	user u3("admin","password",0);

	ulst.addUser(u1);
	ulst.addUser(u2);
	ulst.addUser(u3);

	std::cout << "Finding user1's access level, should be 1: " << ulst.getUserByUsername("user1").getAccesslevel() << "\n";
	std::cout << "Finding user2's access level, should be 2: " << ulst.getUserByUsername("user2").getAccesslevel() << "\n";

	AuthXml::writeXml("test.xml",ulst);

	std::cout << "----------------------------------\n";
	std::string line;
	std::ifstream xmlFile ("test.xml");
	std::string infile;
	if (xmlFile.is_open())
	{
		while ( xmlFile.good() )
		{
			std::getline(xmlFile,line);
			infile += line;
		}
		xmlFile.close();
	}
	std::cout << infile << std::endl;

	XmlReader rdr(infile);
	userList ulst2 = AuthXml::readXml(rdr);
	std::cout << "\nPrinting user list\n";
	std::cout << "----------------------------------\n";

	ulst2.prettyPrintUserList();

	return 0;
}
Exemplo n.º 15
0
static inline
void
_os_debug_log_write(int level, char *str)
{
	int fd = os_debug_log_globals()->logfd;
	os_redirect_t rdr = os_debug_log_globals()->redirect;
	// true = redirect has fully handled, don't log
	if (os_slowpath(rdr) && os_fastpath(rdr(str))) {
		return;
	}
	if (os_slowpath(fd >= 0)) {
		if (os_fastpath(_os_debug_log_write_fd(level, str, fd))) {
			return;
		} else {
			_os_debug_log_write_error();
			os_debug_log_globals()->logfd = -1;
			// Don't return, fall out to syslog().
		}
	}
	_simple_asl_log(level, "com.apple.os_debug_log", str);
}
Exemplo n.º 16
0
/////////////////////////////////////////////////////////////////////////////
// This function loads the modifier.bin data into the three tier list ///////
/////////////////////////////////////////////////////////////////////////////
void ModifierBin::Load_Modifier(char* buff, long len)
{
	string st = buff; // Create retention string
	stringstream rdr(st,ios::in); // Create string stream using rentention string

	char buff2[255]; // Our data buffer
	MOD_LIST list;
	MOD_OBJ obj;
	ModProperty prop;

	// While ! END, get next line
	for(; GetString(&rdr,buff2) && TestEnd(buff2); NULL)
	{
		if( !buff2[0] ) // Ignore null lines
			continue;

		// While ! END, get next line
		for(strcpy(list.SectionTitle,buff2); GetString(&rdr,buff2) && TestEnd(buff2); NULL)
		{
			if( !buff2[0] )
				continue;

			for(strcpy(obj.ObjectName,buff2); GetString(&rdr,buff2) && TestEnd(buff2); NULL)
			{
				if( !buff2[0] )
					continue;

				prop.Load(buff2); // Load property into the object
				obj.Properties.push_back(prop);
						}
			list.ElementList.push_back(obj); // Load object into the header list
			obj.Properties.clear();
		}	
		ModifierList.push_back(list); // Load header list into the master list
		list.ElementList.clear();
	}
}
Exemplo n.º 17
0
extern "C" CDECL int
rust_start(uintptr_t main_fn, rust_crate const *crate, int argc, char **argv)
{
    int ret;
    {
        rust_srv srv;
        rust_dom dom(&srv, crate, "main");
        command_line_args args(dom, argc, argv);

        dom.log(rust_log::DOM, "startup: %d args", args.argc);
        for (int i = 0; i < args.argc; ++i)
            dom.log(rust_log::DOM,
                    "startup: arg[%d] = '%s'", i, args.argv[i]);

        if (dom._log.is_tracing(rust_log::DWARF)) {
            rust_crate_reader rdr(&dom, crate);
        }

        uintptr_t main_args[4] = { 0, 0, 0, (uintptr_t)args.args };

        dom.root_task->start(crate->get_exit_task_glue(),
                             main_fn,
                             (uintptr_t)&main_args,
                             sizeof(main_args));

        ret = dom.start_main_loop();
    }

#if !defined(__WIN32__)
    // Don't take down the process if the main thread exits without an
    // error.
    if (!ret)
        pthread_exit(NULL);
#endif
    return ret;
}
Exemplo n.º 18
0
HRESULT GetRibbonText(BSTR * RibbonXml)
{
	LPBYTE content = NULL;
	DWORD content_length = 0;

	ASSERT_RETURN_VALUE(LoadResourceFromModule(
		AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_RESOURCE_H), L"TEXT", &content, &content_length), S_FALSE);

	CMemFile mf(content, content_length);
	CTextFileRead rdr(&mf);

	CMapStringToString replacements;

	CString line;
	while (rdr.ReadLine(line))
	{
		CSimpleArray<CString> tokens;

		CString token;
		token.Preallocate(30);

		for (LPCWSTR pos = line; *pos; ++pos)
		{
			if (*pos == ' ' || *pos == '\t')
			{
				if (!token.IsEmpty())
				{
					tokens.Add(token);
					token = CString();
				}
			}
			else
			{
				token += *pos;
			}
		}

		if (!token.IsEmpty())
			tokens.Add(token);

		if (tokens.GetSize() != 3)
			continue;

		if (tokens[0] != "#define")
			continue;

		replacements[tokens[1]] = tokens[2];
	}

	CString ribbon = LoadTextFromModule(AfxGetInstanceHandle(), IDR_RIBBON);

	for (int pos = 0; pos < ribbon.GetLength(); ++pos)
	{
		if (ribbon[pos] != '{')
			continue;

		int endpos = ribbon.Find('}', pos);
		ASSERT_CONTINUE(endpos != -1);

		CString token = ribbon.Mid(pos+1, endpos-pos-1);
		CString token_found;

		ASSERT_CONTINUE(replacements.Lookup(token, token_found));	

		ribbon.Delete(pos, endpos-pos+1);
		ribbon.Insert(pos, token_found);

		pos += (token_found.GetLength()-1);
	}

	*RibbonXml = ribbon.AllocSysString();
	return S_OK;
}
Exemplo n.º 19
0
int CDBAPI_CacheTest::Run(void)
{
    cout << "Run CDBAPI_CacheTest test" << endl << endl;

    try {
        auto_ptr<ICache> blob_cache( MakeICache() );
        
        if ( blob_cache.get() == NULL ) {
            return 1;
        }

        int top = blob_cache->GetTimeStampPolicy();
        blob_cache->SetTimeStampPolicy(top, 30);

        blob_cache->Purge("", "", 30);

        const char* szTest = "01234567890";

        blob_cache->Store("key_1",
                         1,
                         "",
                         szTest,
                         strlen(szTest));


        size_t blob_size = blob_cache->GetSize("key_1",
                                               1,
                                               "");

        int s = strlen(szTest);
        assert(blob_size == size_t(s));

        char blob_buf[1024] = {0,};
        blob_cache->Read("key_1",
                        1,
                        "", 
                        blob_buf,
                        1024);

        int cmp = strcmp(blob_buf, szTest);
        assert(cmp == 0);

        {
        auto_ptr<IWriter> wrt(blob_cache->GetWriteStream("key_3", 1, "sk1"));
        size_t bytes_written;
        int s = strlen(szTest);
        wrt->Write(szTest, s, &bytes_written);
        wrt->Flush();
        }

        {
        char str[1024] = {0,};
        char* sp = str;
        auto_ptr<IReader> rdr(blob_cache->GetReadStream("key_3", 1, "sk1"));
        char buf[1024];
        ERW_Result r;
        size_t rd;
        do {
            r = rdr->Read(buf, 1, &rd);
            if (r != eRW_Success)
                break;
            *sp++ = buf[0];
        } while (rd > 0);
        int c = strcmp(szTest, str);
        assert(c == 0);

        }

        // dump huge BLOB
        {
            unsigned bsize = 10 * 1024 * 1024;
            int* big_blob = new int[bsize];

            for (unsigned i = 0; i < bsize; ++i) {
                big_blob[i] = i;
            }

            {
            auto_ptr<IWriter> wrt(blob_cache->GetWriteStream("key_big", 1, ""));
            unsigned written = 0;
            int* p = big_blob;
            while (written < bsize) {
                size_t bytes_written;
                unsigned elements_to_write = 10;
                unsigned chunk_size = elements_to_write * sizeof(int);
                wrt->Write(p, chunk_size, &bytes_written);
                p += elements_to_write;
                written += elements_to_write;
                assert(bytes_written == chunk_size);
            } // while
            wrt->Flush();
            }
    
            auto_ptr<IReader> rdr(blob_cache->GetReadStream("key_big", 1, ""));
            
            ERW_Result r;
            size_t rd;
            unsigned int cnt = 0;
            do {
                int buf[1];
                r = rdr->Read(buf, sizeof(int), &rd);
                if (r != eRW_Success)
                    break;
                if (cnt != (unsigned int)buf[0]) {
                    cerr << "BLOB comparison error element idx = " << cnt <<
                            " value=" << buf[0] << endl;
                    assert(cnt == (unsigned int)buf[0]);
                }
                cnt++;
            } while (rd > 0);
        }
        
        blob_cache->Remove("key_big", 1, "");
    } catch( CDB_Exception& dbe ) {
        NcbiCerr  << dbe.what() << " " << dbe.Message() 
                  << NcbiEndl;
        return 1;
    }

    cout << endl;
    cout << "TEST execution completed successfully!" << endl << endl;
    return 0;
}
int main()
{
  std::cout << "\n  Testing XmlReader";
  std::cout << "\n ===================\n";

  std::string Prologue = "<?xml version=\"1.0\"?><!-- top level comment -->";
  std::string test1 = Prologue; 
  test1 += "<parent att1='val1' att2='val2'><child1 /><child2>child2 body<child1 /></child2></parent>";
  std::string test2 = Prologue;
  test2 += "<Dir><path>/TestFile/Dir1</path><File><name>text1.txt</name><date>02/11/2012</date></File></Dir>";
  XmlReader rdr(test1);

  std::cout << "\n  source = " << test1.c_str() << std::endl;

  // testing helper function

  std::cout << "\n  Testing extractIdentifier";
  std::cout << "\n ---------------------------";
  std::string ident;
  size_t position = 1;
  do
  {
    ident = rdr.extractIdentifier(position);
    std::cout << "\n  " << ident.c_str();
  } while(ident.size() > 0);

  // testing typical use, step through each element extracting tags, attributes,
  // bodies, and or entire element strings

  std::cout << "\n  testing next(), tag(), element(), body(), and attributes()";
  std::cout << "\n -----------------------------------------------------------";
  rdr.reset();
  while(rdr.next())
  {
    std::cout << "\n  tag:     " << rdr.tag().c_str();
    std::cout << "\n  element: " << rdr.element().c_str();
    std::cout << "\n  body:    " << rdr.body().c_str();
    XmlReader::attribElems attribs = rdr.attributes();
    for(size_t i=0; i<attribs.size(); ++i)
      std::cout << "\n  attributes: " << attribs[i].first.c_str() << ", " << attribs[i].second.c_str();
  }
  std::cout << "\n\n";

  // testing typical use, step through each element extracting tags, attributes,
  // bodies, and or entire element strings

  rdr.xml() = test2;
  std::cout << "\n  source = " << rdr.xml().c_str() << std::endl;

  std::cout << "\n  testing next(), tag(), element(), body(), and attributes()";
  std::cout << "\n -----------------------------------------------------------";

  rdr.reset();
  while(rdr.next())
  {
    std::cout << "\n  tag:     " << rdr.tag().c_str();
    std::cout << "\n  element: " << rdr.element().c_str();
    std::cout << "\n  body:    " << rdr.body().c_str();
    XmlReader::attribElems attribs = rdr.attributes();
    for(size_t i=0; i<attribs.size(); ++i)
      std::cout << "\n  attributes: " << attribs[i].first.c_str() << ", " << attribs[i].second.c_str();
  }
  std::cout << "\n\n";
  return 0;
}
Exemplo n.º 21
0
/*
 * program entry point
 */
int main( int argc, char** argv )
{
   try
   {
      // execution options
      ::XmlUnion::Config::Settings config;

      char* InputFileName1 = 0;
      char* InputFileName2 = 0;
      char* OutputFileName = 0;

      // <editor-fold defaultstate="collapsed" desc="command line argument parsing">

      // could be a bitmap file name or a configuration option
      for ( int i = 1; i < argc; ++i )
      {
         ::std::string arg( argv[i] );

         // if '-c'...
         if ( arg == "-c" )
         {
            // if there's a file name following...
            if ( ++i < argc )
            {
               // try to parse the configuration file
               try
               {
                  ::XmlUnion::Config::Reader rdr( argv[i] );
                  config = rdr.Parse();
               }
               catch ( ::std::runtime_error& e )
               {
                  ::std::cerr << e.what() << "\n";
                  return 2;
               }
               catch ( ... )
               {
                  ::std::cerr << "Error reading configuration file\n"; 
                  return 2;
               }
               continue;
            }
         }

         // input file name first
         if ( ! arg.empty() && ! InputFileName1 )
         {
            InputFileName1 = argv[i];
            continue;
         }

         // output file name next
         if ( ! arg.empty() && ! InputFileName2 )
         {
            InputFileName2 = argv[i];
            continue;
         }

         // output file name next
         if ( ! arg.empty() && ! OutputFileName )
         {
            OutputFileName = argv[i];
            continue;
         }

         // something unrecognized
         throw ::std::runtime_error( ::std::string( "Invalid command line parameter: " ) + arg );
      }

      if ( ! InputFileName1 || ! InputFileName2 )
         throw ::std::runtime_error( "Invalid command line parameters: two different files must be specified" );
      // </editor-fold>

      // Reader for the first input document
      ::File::Reader rdr1;
      rdr1.open( InputFileName1 );

      // Reader for the second input document
      ::File::Reader rdr2;
      rdr2.open( InputFileName2 );

      ::XmlUnion::App app( rdr1, rdr2 );
      app.Process( config );
      
      ::File::Writer wrt;
      if ( OutputFileName )
         wrt.open( OutputFileName );
      else
         if ( config.OutputFile.empty() )
            wrt.open( stdout );
         else
            wrt.open( config.OutputFile.c_str() );
      app.OutputXmlDoc.Write( wrt );
   }
   catch ( ::std::runtime_error& ex )
   {
      ::std::cerr << ex.what() << "\n";
      return 2;
   }
   catch (...)
   {
      ::std::cerr << "Unexpected error with no explanation thrown\n";
      return 3;
   }
   
   // equal. return success
   return 0;
}
Exemplo n.º 22
0
void Serial::configDma(Dma::Stream *write, Dma::Stream *read)
{
    Device::configDma(write, read);
    if (Device::mDmaWrite != nullptr)
    {
        mDmaWrite->config(Dma::Stream::Direction::MemoryToPeripheral, false, true, Dma::Stream::DataSize::Byte, Dma::Stream::DataSize::Byte, Dma::Stream::BurstLength::Single, Dma::Stream::BurstLength::Single);
        mDmaWrite->setAddress(Dma::Stream::End::Peripheral, reinterpret_cast<System::BaseAddress>(tdr()));
        mDmaWrite->configFifo(Dma::Stream::FifoThreshold::ThreeQuater);
        mBase->CR3.DMAT = 1;
    }
    else
    {
        mBase->CR3.DMAT = 0;
    }
    if (Device::mDmaRead != nullptr)
    {
        mDmaRead->config(Dma::Stream::Direction::PeripheralToMemory, false, true, Dma::Stream::DataSize::Byte, Dma::Stream::DataSize::Byte, Dma::Stream::BurstLength::Single, Dma::Stream::BurstLength::Single);
        mDmaRead->setAddress(Dma::Stream::End::Peripheral, reinterpret_cast<System::BaseAddress>(rdr()));
        mDmaRead->configFifo(Dma::Stream::FifoThreshold::Disable);
        mBase->CR3.DMAR = 1;
    }
    else
    {
        mBase->CR3.DMAR = 0;
    }
}
Exemplo n.º 23
0
		AnyValue BsonSerializer::deserialize(const std::string & str)
		{
			Bundle res;
			std::vector<uint8_t> data(str.begin(), str.end());
			BufferReader rdr(data);
			if (rdr.getSize() < 4)
				throw std::invalid_argument("Document must be at least 4 byte long");

			rdr.readInt32();
			while (true)
			{
				uint8_t field_type = rdr.readUInt8();
				if (field_type == 0x00)
					break;

				std::string name = rdr.readCString();

				if (field_type == 0x01)
				{
					res.set(name, rdr.readDouble());
				}
				else if (field_type == 0x02)
				{
					int32_t len = rdr.readInt32();
					res.set(name, rdr.readString(len - 1));
					rdr.readUInt8(); // skip trailing 0
				}
				else if (field_type == 0x03)
				{
					// Document
					int32_t len = rdr.peekInt32();
					const uint8_t* ptr = rdr.readBytes(len);
					std::string document(ptr, ptr + len);
					res.set(name, this->deserialize(document));
				}
				else if (field_type == 0x04)
				{
					// Array
					int32_t len = rdr.peekInt32();
					const uint8_t* ptr = rdr.readBytes(len);
					std::string document(ptr, ptr + len);
					std::vector<AnyValue> bdocres;
					for (auto& elem : this->deserialize(document).as<Bundle>()) bdocres.push_back(elem.second);

					res.set(name, bdocres);
				}
				else if (field_type == 0x05)
				{
					// Binary Data
					int32_t len = rdr.readInt32();
					rdr.readUInt8(); // Subtype
									 // TODO: What to do with subtype ?
					auto ptr = rdr.readBytes(len);
					res.set(name, std::vector<uint8_t>(ptr, ptr + len));
				}
				else if (field_type == 0x06)
				{
					// Deprecated
				}
				else if (field_type == 0x07)
				{
					// ObjectID
					// We don't know what to do with it in standard implementations.
					rdr.readBytes(12);
				}
				else if (field_type == 0x08)
				{
					// Boolean
					res.set(name, (rdr.readUInt8() == 1));
				}
				else if (field_type == 0x09)
				{
					// UTC Date int64
					res.set(name, rdr.readInt64());
				}
				else if (field_type == 0x0A)
				{
					res.set(name, nullptr);
				}
				else if (field_type == 0x0B)
				{
					rdr.readCString();
					rdr.readCString();
				}
				else if (field_type == 0x0C)
				{
					// DB Pointer
					// Deprecated
					int32_t len = rdr.readInt32();
					rdr.readBytes(len + 12);
				}
				else if (field_type == 0x0D)
				{
					// Javascript code
					// Is this a good idea ?
					Bundle js;
					int32_t len = rdr.readInt32();
					js.set("js", rdr.readString(len));
					rdr.readUInt8(); // skip trailing 0
					js.set("scope", Bundle());
					res.set(name, js);
				}
				else if (field_type == 0x0E)
				{
					// Deprecated
					int32_t len = rdr.readInt32();
					rdr.readBytes(len);
				}
				else if (field_type == 0x0F)
				{
					// Javascript code with scope
					// Is this a good idea ?
					Bundle js;
					rdr.readInt32(); // code length
					int32_t jslen = rdr.readInt32();
					js.set("js", rdr.readString(jslen));
					rdr.readUInt8(); // skip trailing 0
					int32_t doclen = rdr.peekInt32();
					auto docptr = rdr.readBytes(doclen);
					js.set("scope", this->deserialize(std::string(docptr, docptr + doclen)));
					res.set(name, js);
				}
				else if (field_type == 0x10)
				{
					// INT32
					res.set(name, rdr.readInt32());
				}
				else if (field_type == 0x11)
				{
					// Timestamp
					res.set(name, rdr.readInt64());
				}
				else if (field_type == 0x12)
				{
					// Int64
					res.set(name, rdr.readInt64());
				}
				else if (field_type == 0xFF)
				{
					// Min key
				}
				else if (field_type == 0x7F)
				{
					// Max key
				}
			}

			return res;
		}
Exemplo n.º 24
0
MetadataFromBlr::MetadataFromBlr(unsigned aBlrLength, const unsigned char* aBlr, unsigned aLength)
{
	if (aBlrLength == 0)
		return;

	BlrReader rdr(aBlr, aBlrLength);

	const UCHAR byte = rdr.getByte();
	if (byte != blr_version4 && byte != blr_version5)
	{
		(Arg::Gds(isc_dsql_error) <<
		 Arg::Gds(isc_sqlerr) << Arg::Num(-804) <<
		 Arg::Gds(isc_wroblrver2) << Arg::Num(blr_version4) << Arg::Num(blr_version5) << Arg::Num(byte)
		).raise();
	}

	if (rdr.getByte() != blr_begin || rdr.getByte() != blr_message)
	{
		(Arg::Gds(isc_sqlerr) << Arg::Num(-804) <<
		 Arg::Gds(isc_dsql_sqlda_err)
#ifdef DEV_BUILD
		 << Arg::Gds(isc_random) << "Missing blr_begin / blr_message"
#endif
		).raise();
	}

	rdr.getByte();						// skip the message number
	unsigned count = rdr.getWord();
	fb_assert(!(count & 1));
	count /= 2;

	unsigned offset = 0;
	items.grow(count);

	for (unsigned index = 0; index < count; index++)
	{
		Item* item = &items[index];
		item->scale = 0;
		item->subType = 0;

		switch (rdr.getByte())
		{
		case blr_text:
			item->type = SQL_TEXT;
			item->charSet = CS_dynamic;
			item->length = rdr.getWord();
			break;

		case blr_varying:
			item->type = SQL_VARYING;
			item->charSet = CS_dynamic;
			item->length = rdr.getWord();
			break;

		case blr_text2:
			item->type = SQL_TEXT;
			item->charSet = rdr.getWord();
			item->length = rdr.getWord();
			break;

		case blr_varying2:
			item->type = SQL_VARYING;
			item->charSet = rdr.getWord();
			item->length = rdr.getWord();
			break;

		case blr_short:
			item->type = SQL_SHORT;
			item->length = sizeof(SSHORT);
			item->scale = rdr.getByte();
			break;

		case blr_long:
			item->type = SQL_LONG;
			item->length = sizeof(SLONG);
			item->scale = rdr.getByte();
			break;

		case blr_int64:
			item->type = SQL_INT64;
			item->length = sizeof(SINT64);
			item->scale = rdr.getByte();
			break;

		case blr_quad:
			item->type = SQL_QUAD;
			item->length = sizeof(SLONG) * 2;
			item->scale = rdr.getByte();
			break;

		case blr_float:
			item->type = SQL_FLOAT;
			item->length = sizeof(float);
			break;

		case blr_double:
		case blr_d_float:
			item->type = SQL_DOUBLE;
			item->length = sizeof(double);
			break;

		case blr_timestamp:
			item->type = SQL_TIMESTAMP;
			item->length = sizeof(SLONG) * 2;
			break;

		case blr_sql_date:
			item->type = SQL_TYPE_DATE;
			item->length = sizeof(SLONG);
			break;

		case blr_sql_time:
			item->type = SQL_TYPE_TIME;
			item->length = sizeof(SLONG);
			break;

		case blr_blob2:
			item->type = SQL_BLOB;
			item->length = sizeof(ISC_QUAD);
			item->subType = rdr.getWord();
			item->charSet = rdr.getWord();
			break;

		case blr_bool:
			item->type = SQL_BOOLEAN;
			item->length = sizeof(UCHAR);
			break;

		default:
			(Arg::Gds(isc_sqlerr) << Arg::Num(-804) <<
			 Arg::Gds(isc_dsql_sqlda_err)
#ifdef DEV_BUILD
			 << Arg::Gds(isc_random) << "Wrong BLR type"
#endif
			).raise();
		}

		if (rdr.getByte() != blr_short || rdr.getByte() != 0)
		{
			(Arg::Gds(isc_sqlerr) << Arg::Num(-804) <<
			 Arg::Gds(isc_dsql_sqlda_err)
#ifdef DEV_BUILD
			 << Arg::Gds(isc_random) << "Wrong BLR type for NULL indicator"
#endif
			).raise();
		}

		item->finished = true;
	}

	makeOffsets();

	if (rdr.getByte() != (UCHAR) blr_end || length != aLength)
	{
		(Arg::Gds(isc_sqlerr) << Arg::Num(-804) <<
		 Arg::Gds(isc_dsql_sqlda_err)
#ifdef DEV_BUILD
		 << Arg::Gds(isc_random) << (length != aLength ? "Invalid message length" : "Missing blr_end")
#endif
		).raise();
	}
}
Exemplo n.º 25
0
int CTestTransmission::Run(void)
{
    LOG_POST("Test IReader/IWriter transmission");

    const int test_buf_size = 1024;
    unsigned char buf[test_buf_size  * 10];
    unsigned char buf2[test_buf_size * 10];

    // ---------------------------------------
    // write the test sequence

    ERW_Result res;
    size_t     sz;

    {{
    CTestMemWriter wrt(buf, sizeof(buf));
    s_SaveTestData(&wrt, test_buf_size/2);
    sz = wrt.SizeWritten();
    assert(sz == test_buf_size/2);
    }}


    // ---------------------------------------
    // read the whole test sequence

    {{
#if defined(NCBI_XCODE_BUILD)  &&  defined(__OPTIMIZE__)  &&  NCBI_COMPILER_VERSION == 421
    // Our Xcode builds use gcc-4.2 -Os, which passes in a
    // CTestMemWriter(!) object without this workaround. :-/
    unique_ptr<CTestMemReader> rdr(new CTestMemReader(buf, sz));
    s_ReadCheck1(rdr.get(), buf, buf2, sz * 2, sz);
#else
    CTestMemReader rdr(buf, sz);
    s_ReadCheck1(&rdr, buf, buf2, sz * 2, sz);
#endif
    }}

    // ---------------------------------------
    // read the test sequence char by char

    {{
    CTestMemReader rdr(buf, sz);
    for (size_t i = 0; i < sz * 2; ++i) {
        buf2[i] = 0;
        size_t read;
        res = rdr.Read(buf2 + i, 1, &read);
        if (res == eRW_Eof) {
            assert(i == sz);
            assert(read == 0);
            break;
        }
        assert(read == 1);
        assert(res == eRW_Success);
        assert (buf2[i] == buf[i]);
    }
    }}

    // ---------------------------------------
    // read the test sequence by 7 char

    {{
    CTestMemReader rdr(buf, sz);
    size_t read = 0;
    for (size_t i = 0; i < sz * 2; i+=read) {
        unsigned char buf3[10] = {0,};
        res = rdr.Read(buf3, 7, &read);
        if (res == eRW_Eof) {
            assert(read == 0);
            break;
        }
        assert(read <= 7);
        assert(res == eRW_Success);
        for (size_t j = 0; j < read; ++j) {
            assert(buf3[j] == (unsigned char)(i + j));
        }
    }
    }}


    // Transmission test

    memset(buf, 0, sizeof(buf));
    memset(buf2, 0, sizeof(buf2));

    {{
    CTestMemWriter wrt(buf, sizeof(buf));
    CTransmissionWriter twrt(&wrt);

    char b = 35;
    twrt.Write(&b, 1);

    CTestMemReader rdr(buf, sz);
    CTransmissionReader trdr(&rdr);

    char c = 0;
    trdr.Read(&c, 1);

    assert(b==c);
    }}

    size_t tsize = 3;
    size_t byte_size;

    {{
    CTestMemWriter wrt(buf, sizeof(buf));
    CTransmissionWriter twrt(&wrt);
    s_SaveTestData(&twrt, tsize);//test_buf_size/2);
    byte_size = wrt.SizeWritten();
    }}


    // ---------------------------------------
    // read the whole test sequence

    {{
    CTestMemReader rdr(buf, byte_size);
    CTransmissionReader trdr(&rdr);

    s_ReadCheck1(&trdr, buf, buf2, sz * 2, tsize);//test_buf_size/2);
    }}

    memset(buf, 0, sizeof(buf));
    memset(buf2, 0, sizeof(buf2));

    tsize = test_buf_size/2;
    {{
    CTestMemWriter wrt(buf, sizeof(buf));
    CTransmissionWriter twrt(&wrt);
    s_SaveTestData(&twrt, tsize);
    byte_size = wrt.SizeWritten();
    }}


    // ---------------------------------------
    // read the whole test sequence

    {{
    CTestMemReader rdr(buf, byte_size);
    CTransmissionReader trdr(&rdr);

    s_ReadCheck1(&trdr, buf, buf2, tsize * 2, tsize);
    }}

    // ---------------------------------------
    // read the test sequence char by char

    {{
    CTestMemReader rdr(buf, byte_size);
    CTransmissionReader trdr(&rdr);
    size_t i;
    for (i = 0; i < tsize * 2; ++i) {
        buf2[i] = 0;
        size_t read;
        res = trdr.Read(buf2 + i, 1, &read);
        if (res == eRW_Eof) {
            assert(i == sz);
            assert(read == 0);
            break;
        }
        assert(read == 1);
        assert(res == eRW_Success);
        unsigned char ch = (unsigned char) i;
        assert (buf2[i] == ch);
    }
    assert(i == tsize);
    }}


    // ---------------------------------------
    // read the test sequence by 7 char

    {{
    CTestMemReader rdr(buf, byte_size);
    CTransmissionReader trdr(&rdr);
    size_t read = 0;
    size_t total_read = 0;
    for (size_t i = 0; i < tsize * 2; i+=read) {
        unsigned char buf3[10] = {0,};
        res = trdr.Read(buf3, 7, &read);
        if (res == eRW_Eof) {
            assert(read == 0);
            break;
        }
        total_read += read;
        assert(read <= 7);
        assert(res == eRW_Success);
        for (size_t j = 0; j < read; ++j) {
            assert(buf3[j] == (unsigned char)(i + j));
        }
    }
    assert(total_read = tsize);
    }}

    // ---------------------------
    // test eof packet
    {{
    CTestMemWriter wrt(buf, sizeof(buf));
    char b = 35;
    {
    CTransmissionWriter twrt(&wrt, eNoOwnership, CTransmissionWriter::eSendEofPacket);

    twrt.Write(&b, 1);
    }
    CTestMemReader rdr(buf, sz);
    CTransmissionReader trdr(&rdr);

    char c = 0;
    trdr.Read(&c, 1);

    assert(b==c);
    res = trdr.Read(&c,1);
    assert(res==eRW_Eof);
    }}

    LOG_POST("OK");

    return 0;
}
Exemplo n.º 26
0
STDMETHODIMP CAdRotator::get_GetAdvertisement(BSTR bstrVirtualPath, BSTR * pVal)
{
	SCODE rc = E_FAIL;
    
	try
	{
		USES_CONVERSION;

		CContext cxt;
		rc = cxt.Init( CContext::get_Server );
		if ( !FAILED(rc) )
		{
			CComBSTR bstrPhysicalPath;
			// determine the physical path
			if ( ( rc = cxt.Server()->MapPath( bstrVirtualPath, &bstrPhysicalPath ) ) == S_OK )
			{
				_TCHAR* szPath = OLE2T( bstrPhysicalPath );

				CAdFilePtr pAdFile = AdFile( szPath );
				
				if ( pAdFile.IsValid() )
				{
					// refresh the ad file (make sure it's up to date)
					pAdFile->Refresh();

					// block all writers
					CReader rdr( *pAdFile );

					// if the border hasn't been set, use the default from the ad file
					short nBorder;
					if ( m_nBorder < 0 )
					{
						nBorder = pAdFile->Border();
					}
					else
					{
						nBorder = m_nBorder;
					}

					CAdDescPtr pAd = pAdFile->RandomAd();
					if ( pAd.IsValid() )
					{
						// write out the HTML line for this ad
						StringOutStream ss;

						if ( m_bClickable && ( pAd->m_strLink.size() > 1 ) )
						{
							// use the href format
							ss	<< _T("<A HREF=\"") << pAdFile->Redirector()
								<< _T("?url=") << pAd->m_strLink
								<< _T("&image=") << pAd->m_strGif
								<< _T("\" ") << m_strTargetFrame << _T(">");
						}
						
						// now fill in the rest
						ss	<< _T("<IMG SRC=\"") << pAd->m_strGif
							<< _T("\" ALT=\"") << pAd->m_strAlt
							<< _T("\" WIDTH=") << pAdFile->Width()
							<< _T(" HEIGHT=") << pAdFile->Height();

						if ( pAdFile->HSpace() != CAdFile::defaultHSpace )
						{
							ss << _T(" HSPACE=") << pAdFile->HSpace();
						}
						if ( pAdFile->VSpace() != CAdFile::defaultVSpace )
						{
							ss << _T(" VSPACE=") << pAdFile->VSpace();
						}

						ss << _T(" BORDER=") << nBorder << _T(">");

						if ( m_bClickable && ( pAd->m_strLink.size() > 1 ) )
						{
							// put the trailing tag on
							ss << _T("</A>");
						}

						String str = ss.toString();
						
						if ( pVal )
						{
							if ( *pVal )
							{
								::SysFreeString( *pVal );
							}
							*pVal = T2BSTR( str.c_str() );
							THROW_IF_NULL( *pVal );
							rc = S_OK;
						}
						else
						{
							rc = E_POINTER;
						}
					}
				}
			}
		}
		else
		{
			_ASSERT(0);
			RaiseException( IDS_ERROR_NOSVR );
		}   // end if got server
	}
	catch ( alloc_err& )
	{
		rc = E_OUTOFMEMORY;
	}
	catch ( ... )
	{
		rc = E_FAIL;
	}
	return rc;
}