示例#1
0
文件: maze.cpp 项目: wenlongx/UCLA_CS
bool pathExists(std::string maze[], int nRows, int nCols, int sr, int sc, int er, int ec)
{
    // if start == end, maze is solved
    if (sr == er && sc == ec)
        return true;

    // marked as visited
    maze[sr][sc] = 'A';

    //NORTH
    if ((sr > 0) && (maze[sr-1][sc] == '.'))
        if (pathExists(maze, nRows, nCols, sr-1, sc, er, ec))
            return true;

    //EAST
    if ((sc < nCols-1) && (maze[sr][sc+1] == '.'))
        if (pathExists(maze, nRows, nCols, sr, sc+1, er, ec))
            return true;

    //SOUTH
    if ((sr < nRows-1) && (maze[sr+1][sc] == '.'))
        if (pathExists(maze, nRows, nCols, sr+1, sc, er, ec))
            return true;

    //WEST
    if ((sr < nCols-1) && (maze[sr][sc-1] == '.'))
        if (pathExists(maze, nRows, nCols, sr, sc-1, er, ec))
            return true;

    return false;
}
示例#2
0
void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
        bool isSystemPath) {
    bool pathAdded = false;

    // -syslibroot only used with to absolute framework search paths.
    if (fwPath.startswith("/")) {
        for (auto syslibRoot : _syslibRoots) {
            SmallString<256> path(syslibRoot);
            llvm::sys::path::append(path, fwPath);
            if (pathExists(path)) {
                _frameworkDirs.push_back(path.str().copy(_allocator));
                pathAdded = true;
            }
        }
    }
    // If fwPath found in any -syslibroot, then done.
    if (pathAdded)
        return;

    // If only one -syslibroot, system paths not in that SDK are suppressed.
    if (isSystemPath && (_syslibRoots.size() == 1))
        return;

    // Only use raw fwPath if that directory exists.
    if (pathExists(fwPath))
        _frameworkDirs.push_back(fwPath);
}
示例#3
0
ErrorOr<StringRef>
MachOLinkingContext::searchDirForLibrary(StringRef path,
                                         StringRef libName) const {
  SmallString<256> fullPath;
  if (libName.endswith(".o")) {
    // A request ending in .o is special: just search for the file directly.
    fullPath.assign(path);
    llvm::sys::path::append(fullPath, libName);
    if (pathExists(fullPath))
      return fullPath.str().copy(_allocator);
    return make_error_code(llvm::errc::no_such_file_or_directory);
  }

  // Search for dynamic library
  fullPath.assign(path);
  llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
  if (pathExists(fullPath))
    return fullPath.str().copy(_allocator);

  // If not, try for a static library
  fullPath.assign(path);
  llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
  if (pathExists(fullPath))
    return fullPath.str().copy(_allocator);

  return make_error_code(llvm::errc::no_such_file_or_directory);
}
示例#4
0
MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
    // See if already loaded.
    auto pos = _pathToDylibMap.find(path);
    if (pos != _pathToDylibMap.end())
        return pos->second;

    // Search -L paths if of the form "libXXX.dylib"
    std::pair<StringRef, StringRef> split = path.rsplit('/');
    StringRef leafName = split.second;
    if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
        // FIXME: Need to enhance searchLibrary() to only look for .dylib
        auto libPath = searchLibrary(leafName);
        if (!libPath.getError()) {
            return loadIndirectDylib(libPath.get());
        }
    }

    // Try full path with sysroot.
    for (StringRef sysPath : _syslibRoots) {
        SmallString<256> fullPath;
        fullPath.assign(sysPath);
        llvm::sys::path::append(fullPath, path);
        if (pathExists(fullPath))
            return loadIndirectDylib(fullPath);
    }

    // Try full path.
    if (pathExists(path)) {
        return loadIndirectDylib(path);
    }

    return nullptr;
}
示例#5
0
void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
        bool isSystemPath) {
    bool addedModifiedPath = false;

    // -syslibroot only applies to absolute paths.
    if (libPath.startswith("/")) {
        for (auto syslibRoot : _syslibRoots) {
            SmallString<256> path(syslibRoot);
            llvm::sys::path::append(path, libPath);
            if (pathExists(path)) {
                _searchDirs.push_back(path.str().copy(_allocator));
                addedModifiedPath = true;
            }
        }
    }

    if (addedModifiedPath)
        return;

    // Finally, if only one -syslibroot is given, system paths which aren't in it
    // get suppressed.
    if (_syslibRoots.size() != 1 || !isSystemPath) {
        if (pathExists(libPath)) {
            _searchDirs.push_back(libPath);
        }
    }
}
示例#6
0
    std::string ToolchainItem::colorStr(std::string const& _var) const
    {
      if (!library()) return std::string();

      if (!valid())
      {
        std::string _path(std::string("invalid_") + _var);
        if (!pathExists(_path))
        { 
          return (_var != "light") ? "#e74c3c" : "#6b2018"; 
        } else
        {
          return library()->config().get<std::string>(tbd::ConfigPath("colorset") / tbd::ConfigPath(_path));
        }
      }

      auto& _cfg = library()->config();
      tbd::ConfigPath _toolsetId(elementId().toolset().str());
      tbd::ConfigPath _typeId(elementId().typeId().str());
      tbd::ConfigPath _path = _toolsetId / _typeId / tbd::ConfigPath(_var);

      std::cout << _path.dump() << std::endl;
      if (pathExists(_path.dump()))
      {
        return _cfg.get<std::string>(ConfigPath("colorset") /_path);
      } 
      _path =  _toolsetId / tbd::ConfigPath(_var); 
      if (pathExists(_path.dump()))
      {
        return _cfg.get<std::string>(ConfigPath("colorset") /_path);
      }
      return (_var != "light") ? "#405959" : "#9ed8db"; 
    }
示例#7
0
//============================================================================
// FUNCTION : SPELLutils::fileCopy
//============================================================================
void SPELLutils::copyFile( const std::string& sourcePath, const std::string& targetPath )
{
	if (!pathExists(sourcePath))
	{
		THROW_EXCEPTION("Cannot copy file", "File not found: " + sourcePath, SPELL_ERROR_FILESYSTEM);
	}
	if (!pathExists( basePath( targetPath )))
	{
		THROW_EXCEPTION("Cannot copy file", "Target directory not found: " + basePath(targetPath), SPELL_ERROR_FILESYSTEM);
	}
	std::ifstream infile( sourcePath.c_str() , std::ios_base::binary);
	std::ofstream outfile( targetPath.c_str(), std::ios_base::binary);
	outfile << infile.rdbuf();
	outfile.flush();
	outfile.close();
}
示例#8
0
/**
 * Depending on the operating system, kicks off the generation of the class
 * and library paths. Returns these as a pair.
 * 
 * @return The classpath and library path to use when starting the JVM
 */
pair<string,string> Runtime::generatePaths() throw( HLA::RTIinternalError )
{
	// Check for the presence of RTI_HOME
	// RTI_HOME *has* to be set. No two ways about it. Fail out if this isn't the case.
	// We make all inferences about path locations based off it, give it to us!
	char *rtihome = getenv( "RTI_HOME" );
	if( !rtihome )
	{
		logger->fatal( "RTI_HOME not set: this is *REQUIRED* to point to your Portico directory" );
		throw HLA::RTIinternalError( "RTI_HOME not set: this *must* point to your Portico directory" );
	}
	else
	{
		// check to make sure it is set to a valid location
		if( pathExists(string(rtihome)) == false )
		{
			logger->fatal( "RTI_HOME doesn't exist: this is *REQUIRED* to point to your Portico directory" );
			logger->fatal( "RTI_HOME set to [%s]", rtihome );
			throw HLA::RTIinternalError( "RTI_HOME set to directory that doesn't exist" );
		}
	}

	// Get the class and library paths depending on the platform in use
	#ifdef _WIN32
		return generateWinPath( string(rtihome) );
	#else
		return generateUnixPath( string(rtihome) );
	#endif
}
示例#9
0
Status readFile(const boost::filesystem::path& path, std::string& content) {
  auto path_exists = pathExists(path);
  if (!path_exists.ok()) {
    return path_exists;
  }

  int statusCode = 0;
  std::string statusMessage = "OK";
  std::stringstream buffer;

  fs::ifstream file_h(path);
  if (file_h.is_open()) {
    buffer << file_h.rdbuf();

    if (file_h.bad()) {
      statusCode = 1;
      statusMessage = "Could not read file";
    } else 
      content.assign(std::move(buffer.str()));
      
  } else {
    statusCode = 1;
    statusMessage = "Could not open file for reading";
  }
  return Status(statusCode, statusMessage);
}
示例#10
0
Status createPidFile() {
  // check if pidfile exists
  auto exists = pathExists(FLAGS_pidfile);
  if (exists.ok()) {
    // if it exists, check if that pid is running.
    std::string content;
    auto read_status = readFile(FLAGS_pidfile, content);
    if (!read_status.ok()) {
      return Status(1, "Could not read pidfile: " + read_status.toString());
    }

    auto stale_status = checkStalePid(content);
    if (!stale_status.ok()) {
      return stale_status;
    }
  }

  // Now the pidfile is either the wrong pid or the pid is not running.
  try {
    boost::filesystem::remove(FLAGS_pidfile);
  } catch (boost::filesystem::filesystem_error& e) {
    // Unable to remove old pidfile.
    LOG(WARNING) << "Unable to remove the osqueryd pidfile";
  }

  // If no pidfile exists or the existing pid was stale, write, log, and run.
  auto pid = boost::lexical_cast<std::string>(getpid());
  LOG(INFO) << "Writing osqueryd pid (" << pid << ") to " << FLAGS_pidfile;
  auto status = writeTextFile(FLAGS_pidfile, pid, 0644);
  return status;
}
示例#11
0
Status createPidFile() {
  // check if pidfile exists
  auto pidfile_path = fs::path(FLAGS_pidfile).make_preferred();

  if (pathExists(pidfile_path).ok()) {
    // if it exists, check if that pid is running.
    std::string content;
    auto read_status = readFile(pidfile_path, content, true);
    if (!read_status.ok()) {
      return Status(1, "Could not read pidfile: " + read_status.toString());
    }

    auto stale_status = checkStalePid(content);
    if (!stale_status.ok()) {
      return stale_status;
    }
  }

  // Now the pidfile is either the wrong pid or the pid is not running.
  try {
    boost::filesystem::remove(pidfile_path);
  } catch (const boost::filesystem::filesystem_error& /* e */) {
    // Unable to remove old pidfile.
    LOG(WARNING) << "Unable to remove the osqueryd pidfile";
  }

  // If no pidfile exists or the existing pid was stale, write, log, and run.
  auto pid = boost::lexical_cast<std::string>(
      PlatformProcess::getCurrentProcess()->pid());
  VLOG(1) << "Writing osqueryd pid (" << pid << ") to "
          << pidfile_path.string();
  auto status = writeTextFile(pidfile_path, pid, 0644);
  return status;
}
示例#12
0
 void SetUp() {
   socket_path = kTestManagerSocket + std::to_string(rand());
   remove(socket_path);
   if (pathExists(socket_path).ok()) {
     throw std::domain_error("Cannot test sockets: " + socket_path);
   }
 }
示例#13
0
void genBrowserPlugin(const std::string& uid,
                      const std::string& path,
                      QueryData& results,
                      bool is_disabled = false) {
  Row r;
  pt::ptree tree;

  r["uid"] = uid;
  auto info_path = path + "/Contents/Info.plist";
  // Ensure that what we're processing is actually a plug-in.
  if (!pathExists(info_path)) {
    return;
  }
  if (osquery::parsePlist(info_path, tree).ok()) {
    // Plugin did not include an Info.plist, or it was invalid
    for (const auto& it : kBrowserPluginKeys) {
      r[it.second] = tree.get(it.first, "");

      // Convert bool-types to an integer.
      jsonBoolAsInt(r[it.second]);
    }
  }

  if (r.count("native") == 0 || r.at("native").size() == 0) {
    // The default case for native execution is false.
    r["native"] = "0";
  }
  r["path"] = path;
  r["disabled"] = (is_disabled) ? "1" : "0";
  results.push_back(std::move(r));
}
示例#14
0
QueryData genSafariExtensions(QueryContext& context) {
  QueryData results;

  // Iterate over each user
  auto users = usersFromContext(context);
  for (const auto& row : users) {
    if (row.count("uid") > 0 && row.count("directory") > 0) {
      auto dir = fs::path(row.at("directory")) / kSafariExtensionsPath;
      // Check that an extensions directory exists.
      if (!pathExists(dir).ok()) {
        continue;
      }

      // Glob the extension files.
      std::vector<std::string> paths;
      if (!resolveFilePattern(dir / kSafariExtensionsPattern, paths).ok()) {
        continue;
      }

      for (const auto& extension_path : paths) {
        genSafariExtension(row.at("uid"), extension_path, results);
      }
    }
  }

  return results;
}
示例#15
0
void genSuidBinsFromPath(const std::string& path, QueryData& results) {
  if (!pathExists(path).ok()) {
    // Creating an iterator on a missing path will except.
    return;
  }

  auto it = fs::recursive_directory_iterator(fs::path(path));
  fs::recursive_directory_iterator end;
  while (it != end) {
    fs::path path = *it;
    try {
      // Do not traverse symlinked directories.
      if (fs::is_directory(path) && fs::is_symlink(path)) {
        it.no_push();
      }

      int perms = it.status().permissions();
      if (isSuidBin(path, perms)) {
        // Only emit suid bins.
        genBin(path, perms, results);
      }

      ++it;
    } catch (fs::filesystem_error& e) {
      VLOG(1) << "Cannot read binary from " << path;
      it.no_push();
      // Try to recover, otherwise break.
      try { ++it; } catch(fs::filesystem_error& e) { break; }
    }
  }
}
示例#16
0
int getBluetoothSharingStatus() {
  auto users = SQL::selectAllFrom("users");
  for (const auto& row : users) {
    if (row.count("uid") > 0 && row.count("directory") > 0) {
      auto dir = fs::path(row.at("directory")) / kRemoteBluetoothSharingPath;
      if (!pathExists(dir).ok()) {
        continue;
      }
      std::vector<std::string> paths;
      if (!resolveFilePattern(dir / kRemoteBluetoothSharingPattern, paths)
               .ok()) {
        continue;
      }

      for (const auto& bluetoothSharing_path : paths) {
        auto bluetoothSharingStatus =
            SQL::selectAllFrom("plist", "path", EQUALS, bluetoothSharing_path);
        if (bluetoothSharingStatus.empty()) {
          continue;
        }
        for (const auto& r : bluetoothSharingStatus) {
          if (r.find("key") == row.end() || row.find("value") == r.end()) {
            continue;
          }
          if (r.at("key") == "PrefKeyServicesEnabled" &&
              r.at("value") == INTEGER(1)) {
            return 1;
          }
        }
      }
    }
  }
  return 0;
}
示例#17
0
//============================================================================
// FUNCTION:    SPELLutils::deleteFile
//============================================================================
void SPELLutils::deleteFile( const std::string& file )
{
	if (pathExists(file) && isFile(file))
	{
		::remove( file.c_str() );
	}
}
示例#18
0
void makeInputDefFileIfNotExist( void )
{
	char *path = INPUTDEF_PATH;
	if ( ! pathExists( path ) ) {
		FILE *fp = fopen( path, "w" );
		if ( fp ) {	
			fputs( "\
# MV input definitions.\n\
# http://mv.dinglisch.net/userguide.html#id\n\
#\n\
TPS(FR) e l f  0 otv-fr 8 epg .dat otid:2e18h-1:0:1:5dd:2e18:b0:820000:0:0:0:\n\
EnigmaCache c u f 0 - 0 - - -\n\
SavedCache s u f 7200 ec-save 5 epg .dat -\n\
NordicTEAM e l r -7200 nordicteam 7 tv- .dat http://mv.nordicteam.com/\n\
Dinglisch(EU) e l r 0 dinglisch-eu 3 tv- .dat http://mv.dinglisch.net/data/e\n\
KULICHIKI e u r -18000 kul-rus 2 kul_ .dat http://www.twinline.net/tv/\n\
Wolf(NL) x u r 0 wolf-nl 4 tv- .xmltv http://wolf.xs4all.nl/xmltv/\n\
MyXMLTV x u f 0 myxmltv 4 tv .xmltv -\n", fp );

// WARNING: if you change MyXMLTV name, need to change
// the warning text in inputdefreader.cpp too

			fclose( fp );
		}
		else {
示例#19
0
 void SetUp() {
   socket_path = kTestWorkingDirectory + "test.em" + std::to_string(rand());
   remove(socket_path);
   if (pathExists(socket_path).ok()) {
     throw std::domain_error("Cannot test sockets: " + socket_path);
   }
 }
示例#20
0
std::string DiskArbitrationEventPublisher::extractUdifChecksum(
    const std::string& path_str) {
  fs::path path = path_str;
  if (!pathExists(path).ok() || !isReadable(path).ok()) {
    return "";
  }

  boost::system::error_code ec;
  if (!fs::is_regular_file(path, ec) || ec.value() != errc::success) {
    return "";
  }

  // The koly trailer (footer) is 512 bytes
  // http://newosxbook.com/DMG.html
  if (fs::file_size(path) < 512) {
    return "";
  }

  std::ifstream dmg_file(path_str, std::ios::binary);
  if (dmg_file.is_open()) {
    dmg_file.seekg(-512L, std::ios::end);

    char* buffer = new char[4];
    dmg_file.read(buffer, 4);
    std::string koly_signature;
    koly_signature.assign(buffer, 4);
    delete[] buffer;

    // check for valid signature
    if (koly_signature != "koly") {
      dmg_file.close();
      return "";
    }

    uint32_t checksum_size;
    dmg_file.seekg(-156L, std::ios::end);
    dmg_file.read((char*)&checksum_size, sizeof(checksum_size));
    // checksum_size is in big endian and we need to byte swap
    checksum_size = CFSwapInt32(checksum_size);

    dmg_file.seekg(-152L, std::ios::end); // checksum offset
    unsigned char* u_buffer = new unsigned char[checksum_size];
    dmg_file.read((char*)u_buffer, checksum_size);
    // we don't want to byte swap checksum as disk utility/hdiutil doesn't
    std::stringstream checksum;
    for (size_t i = 0; i < checksum_size; i++) {
      if (u_buffer[i] != 0) {
        checksum << std::setw(2) << std::hex << std::uppercase
                 << (unsigned int)u_buffer[i];
      }
    }
    delete[] u_buffer;
    dmg_file.close();
    return checksum.str();
  }
  return "";
}
示例#21
0
文件: maze.cpp 项目: Srikanth8/CS32
bool pathExists(string maze[], int nRows, int nCols, int sr, int sc, int er, int ec)
{
	if (sr == er && sc == ec)
		return true;

	maze[sr][sc] = 'o';

	if (maze[sr - 1][sc] == '.') //North
		if (pathExists(maze, nRows, nCols, sr - 1, sc, er, ec) == true) return true;
	if (maze[sr][sc + 1] == '.') //East
		if (pathExists(maze, nRows, nCols, sr, sc + 1, er, ec) == true) return true;
	if (maze[sr + 1][sc] == '.') //South
		if (pathExists(maze, nRows, nCols, sr + 1, sc, er, ec) == true) return true;
	if (maze[sr][sc - 1] == '.') //West
		if (pathExists(maze, nRows, nCols, sr, sc - 1, er, ec) == true) return true;
	
	return false;
}
示例#22
0
TEST_F(RocksDBDatabasePluginTests, test_rocksdb_loglevel) {
  // Make sure a log file was created.
  EXPECT_FALSE(pathExists(path_ + "/LOG"));

  // Make sure no log file is created.
  // RocksDB logs are intercepted and forwarded to the GLog sink.
  auto details = SQL::selectAllFrom("file", "path", EQUALS, path_ + "/LOG");
  ASSERT_EQ(details.size(), 0U);
}
示例#23
0
文件: maze.cpp 项目: kkodani/cs32
bool pathExists(char maze[][10], int sr, int sc, int er, int ec)
{
	if(sr==er && sc==ec)
	{	
		return true;
	}
		
	maze[sr][sc]='o';

	if(maze[sr-1][sc]=='.')
	{
		if(pathExists(maze, sr-1, sc, er, ec))
		{
			return true;
		}
	}
	
	if(maze[sr+1][sc]=='.')
	{
		if(pathExists(maze, sr+1, sc, er, ec))
		{
			return true;
		}
	}
	
	if(maze[sr][sc-1]=='.')
	{
		if(pathExists(maze, sr, sc-1, er, ec))
		{
			return true;
		}
	}
	
	if(maze[sr][sc+1]=='.')
	{
		if(pathExists(maze, sr, sc+1, er, ec))
		{
			return true;
		}
	}
		
	return false;
}
示例#24
0
TEST_F(RocksDBDatabasePluginTests, test_corruption) {
  ASSERT_TRUE(pathExists(path_));
  ASSERT_FALSE(pathExists(path_ + ".backup"));

  // Mark the database as corrupted
  RocksDBDatabasePlugin::setCorrupted();
  printf("set corrupt\n");
  resetDatabase();
  printf("did reset\n");

  EXPECT_TRUE(pathExists(path_ + ".backup"));

  // Remove the backup and expect another reload to not create one.
  removePath(path_ + ".backup");
  ASSERT_FALSE(pathExists(path_ + ".backup"));

  resetDatabase();
  EXPECT_FALSE(pathExists(path_ + ".backup"));
}
示例#25
0
void openAndLockFile(FILE** dst, const char* path) {

    if (pathExists(path) != 0) {
        auto file = fopenWrapper(path, "wb");
        fclose(file);
    }

    *dst = fopenWrapper(path, "rb+");
    flockWrapper(*dst, LOCK_EX | LOCK_NB);
}
示例#26
0
ErrorOr<StringRef> MachOLinkingContext::findPathForFramework(StringRef fwName) const{
  SmallString<256> fullPath;
  for (StringRef dir : frameworkDirs()) {
    fullPath.assign(dir);
    llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
    if (pathExists(fullPath))
      return fullPath.str().copy(_allocator);
  }

  return make_error_code(llvm::errc::no_such_file_or_directory);
}
示例#27
0
Status isReadable(const boost::filesystem::path& path) {
  auto path_exists = pathExists(path);
  if (!path_exists.ok()) {
    return path_exists;
  }

  if (access(path.c_str(), R_OK) == 0) {
    return Status(0, "OK");
  }
  return Status(1, "Path is not readable.");
}
示例#28
0
Status isReadable(const fs::path& path) {
  auto path_exists = pathExists(path);
  if (!path_exists.ok()) {
    return path_exists;
  }

  if (access(path.c_str(), R_OK) == 0) {
    return Status(0, "OK");
  }
  return Status(1, "Path is not readable: " + path.string());
}
示例#29
0
 bool socketExists(const std::string& socket_path) {
   // Wait until the runnable/thread created the socket.
   int delay = 0;
   while (delay < kTimeoutUS) {
     if (pathExists(socket_path).ok() && isReadable(socket_path).ok()) {
       return true;
     }
     sleepFor(kDelayUS / 1000);
     delay += kDelayUS;
   }
   return false;
 }
示例#30
0
bool MachOLinkingContext::fileExists(StringRef path) const {
    bool found = pathExists(path);
    // Log search misses.
    if (!found)
        addInputFileNotFound(path);

    // When testing, file is never opened, so logging is done here.
    if (_testingFileUsage && found)
        addInputFileDependency(path);

    return found;
}