Пример #1
0
void
WriterImplBase::_AddStringAttributeList(BHPKGAttributeID id,
	const BStringList& value, DoublyLinkedList<PackageAttribute>& list)
{
	for (int32 i = 0; i < value.CountStrings(); i++)
		AddStringAttribute(id, value.StringAt(i), list);
}
Пример #2
0
void
MidiSettingsView::_RetrieveSoftSynthList()
{
	BStringList paths;
	status_t status = BPathFinder::FindPaths(B_FIND_PATH_DATA_DIRECTORY,
			"synth", paths);
	if (status != B_OK)
		return;

	fListView->MakeEmpty();

	for (int32 i = 0; i < paths.CountStrings(); i++) {
		BDirectory directory(paths.StringAt(i).String());
		BEntry entry;
		if (directory.InitCheck() != B_OK)
			continue;
		while (directory.GetNextEntry(&entry) == B_OK) {
			BNode node(&entry);
			BNodeInfo nodeInfo(&node);
			char mimeType[B_MIME_TYPE_LENGTH];
			// TODO: For some reason this doesn't work
			if (nodeInfo.GetType(mimeType) == B_OK
					/*&& !strcmp(mimeType, "audio/x-soundfont")*/) {
				BPath fullPath = paths.StringAt(i).String();
				fullPath.Append(entry.Name());
				fListView->AddItem(new BStringItem(fullPath.Path()));
			}
		}
	}
}
Пример #3
0
void
LaunchDaemon::ReadyToRun()
{
	_RetrieveKernelOptions();
	_SetupEnvironment();

	fReadOnlyBootVolume = Utility::IsReadOnlyVolume("/boot");
	if (fReadOnlyBootVolume)
		Utility::BlockMedia("/boot", true);

	if (fUserMode) {
		BLaunchRoster roster;
		BLaunchRoster::Private(roster).RegisterSessionDaemon(this);
	} else
		_InitSystem();

	BStringList paths;
	BPathFinder::FindPaths(B_FIND_PATH_DATA_DIRECTORY, kLaunchDirectory,
		fUserMode ? B_FIND_PATHS_USER_ONLY : B_FIND_PATHS_SYSTEM_ONLY, paths);
	_ReadPaths(paths);

	BPathFinder::FindPaths(B_FIND_PATH_SETTINGS_DIRECTORY, kLaunchDirectory,
		fUserMode ? B_FIND_PATHS_USER_ONLY : B_FIND_PATHS_SYSTEM_ONLY, paths);
	_ReadPaths(paths);

	_InitJobs(NULL);
	_LaunchJobs(NULL);

	// Launch run targets (ignores events)
	for (int32 index = 0; index < fRunTargets.CountStrings(); index++) {
		Target* target = FindTarget(fRunTargets.StringAt(index));
		if (target != NULL)
			_LaunchJobs(target);
	}
}
Пример #4
0
static void
NotHere(BStringList& that, BStringList& otherList, BStringList* results)
{
	for (int32 i = 0; i < otherList.CountStrings(); i++) {
		if (!that.HasString(otherList.StringAt(i)))
			results->Add(otherList.StringAt(i));
	}
}
Пример #5
0
void
Job::_AddStringList(std::vector<const char*>& array, const BStringList& list)
{
	int32 count = list.CountStrings();
	for (int32 index = 0; index < count; index++) {
		array.push_back(list.StringAt(index).String());
	}
}
Пример #6
0
void
LaunchDaemon::ReadyToRun()
{
	_RetrieveKernelOptions();
	_SetupEnvironment();

	fReadOnlyBootVolume = Utility::IsReadOnlyVolume("/boot");
	if (fReadOnlyBootVolume)
		Utility::BlockMedia("/boot", true);

	if (fUserMode) {
		BLaunchRoster roster;
		BLaunchRoster::Private(roster).RegisterSessionDaemon(this);
	} else
		_InitSystem();

	BStringList paths;
	if (fUserMode) {
		// System-wide user specific jobs
		BPathFinder::FindPaths(B_FIND_PATH_DATA_DIRECTORY, kUserLaunchDirectory,
			B_FIND_PATHS_SYSTEM_ONLY, paths);
		_ReadPaths(paths);
	}

	BPathFinder::FindPaths(B_FIND_PATH_DATA_DIRECTORY, kLaunchDirectory,
		fUserMode ? B_FIND_PATHS_USER_ONLY : B_FIND_PATHS_SYSTEM_ONLY, paths);
	_ReadPaths(paths);

	if (fUserMode) {
		BPathFinder::FindPaths(B_FIND_PATH_SETTINGS_DIRECTORY,
			kUserLaunchDirectory, B_FIND_PATHS_SYSTEM_ONLY, paths);
		_ReadPaths(paths);
	}

	BPathFinder::FindPaths(B_FIND_PATH_SETTINGS_DIRECTORY, kLaunchDirectory,
		fUserMode ? B_FIND_PATHS_USER_ONLY : B_FIND_PATHS_SYSTEM_ONLY, paths);
	_ReadPaths(paths);

	BMessenger target(this);
	BMessenger::Private messengerPrivate(target);
	port_id port = messengerPrivate.Port();
	int32 token = messengerPrivate.Token();
	__start_watching_system(-1, B_WATCH_SYSTEM_TEAM_DELETION, port, token);

	_InitJobs(NULL);
	_LaunchJobs(NULL);

	// Launch run targets (ignores events)
	for (int32 index = 0; index < fRunTargets.CountStrings(); index++) {
		Target* target = FindTarget(fRunTargets.StringAt(index));
		if (target != NULL)
			_LaunchJobs(target);
	}

	if (fUserMode)
		be_roster->StartWatching(this, B_REQUEST_LAUNCHED);
}
Пример #7
0
static void add_replaces_list(Repo *repo, Offset &dependencies,
  const BStringList &packageNames)
{
  int32 count = packageNames.CountStrings();
  for (int32 i = 0; i < count; i++)
    {
      const BString &packageName = packageNames.StringAt(i);
      add_dependency(repo, dependencies, packageName, BPackageVersion(), 0);
    }
}
Пример #8
0
void
BPackageManager::Init(uint32 flags)
{
	if (fSolver != NULL)
		return;

	// create the solver
	status_t error = BSolver::Create(fSolver);
	if (error != B_OK)
		DIE(error, "failed to create solver");

	if (fSystemRepository == NULL || fHomeRepository == NULL
		|| fLocalRepository == NULL) {
		throw std::bad_alloc();
	}

	fSolver->SetDebugLevel(fDebugLevel);

	BRepositoryBuilder(*fLocalRepository).AddToSolver(fSolver, false);

	// add installation location repositories
	if ((flags & B_ADD_INSTALLED_REPOSITORIES) != 0) {
		// We add only the repository of our actual installation location as the
		// "installed" repository. The repositories for the more general
		// installation locations are added as regular repositories, but with
		// better priorities than the actual (remote) repositories. This
		// prevents the solver from showing conflicts when a package in a more
		// specific installation location overrides a package in a more general
		// one. Instead any requirement that is already installed in a more
		// general installation location will turn up as to be installed as
		// well. But we can easily filter those out.
		_AddInstalledRepository(fSystemRepository);

		if (!fSystemRepository->IsInstalled())
			_AddInstalledRepository(fHomeRepository);
	}

	// add other repositories
	if ((flags & B_ADD_REMOTE_REPOSITORIES) != 0) {
		BPackageRoster roster;
		BStringList repositoryNames;
		error = roster.GetRepositoryNames(repositoryNames);
		if (error != B_OK) {
			fUserInteractionHandler->Warn(error,
				"failed to get repository names");
		}

		int32 repositoryNameCount = repositoryNames.CountStrings();
		for (int32 i = 0; i < repositoryNameCount; i++) {
			_AddRemoteRepository(roster, repositoryNames.StringAt(i),
				(flags & B_REFRESH_REPOSITORIES) != 0);
		}
	}
}
Пример #9
0
void
LaunchDaemon::_ReadPaths(const BStringList& paths)
{
	for (int32 i = 0; i < paths.CountStrings(); i++) {
		BEntry entry(paths.StringAt(i));
		if (entry.InitCheck() != B_OK || !entry.Exists())
			continue;

		_ReadDirectory(NULL, entry);
	}
}
Пример #10
0
void
POP3Protocol::CheckForDeletedMessages()
{
	{
		// Delete things from the manifest no longer on the server
		BStringList list;
		NotHere(fUniqueIDs, fManifest, &list);
		fManifest.Remove(list);
	}

	if (!fSettings.FindBool("delete_remote_when_local")
		|| fManifest.CountStrings() == 0)
		return;

	BStringList toDelete;

	BStringList queryContents;
	BVolumeRoster volumes;
	BVolume volume;

	while (volumes.GetNextVolume(&volume) == B_OK) {
		BQuery fido;
		entry_ref entry;

		fido.SetVolume(&volume);
		fido.PushAttr(B_MAIL_ATTR_ACCOUNT_ID);
		fido.PushInt32(fAccountSettings.AccountID());
		fido.PushOp(B_EQ);

		fido.Fetch();

		BString uid;
		while (fido.GetNextRef(&entry) == B_OK) {
			BNode(&entry).ReadAttrString("MAIL:unique_id", &uid);
			queryContents.Add(uid);
		}
	}
	NotHere(queryContents, fManifest, &toDelete);

	for (int32 i = 0; i < toDelete.CountStrings(); i++) {
		printf("delete mail on server uid %s\n", toDelete.StringAt(i).String());
		Delete(fUniqueIDs.IndexOf(toDelete.StringAt(i)));
	}

	// Don't remove ids from fUniqueIDs, the indices have to stay the same when
	// retrieving new messages.
	fManifest.Remove(toDelete);

	// TODO: at some point the purged manifest should be written to disk
	// otherwise it will grow forever
}
Пример #11
0
		status_t operator()(const BEntry& entry)
		{
			char name[B_FILE_NAME_LENGTH];
			status_t result = entry.GetName(name);
			if (result != B_OK)
				return result;
			int32 count = names.CountStrings();
			for (int i = 0; i < count; ++i) {
				if (names.StringAt(i).Compare(name) == 0)
					return B_OK;
			}
			names.Add(name);
			return B_OK;
		}
Пример #12
0
void
RepositoriesSettings::SetRepositories(BStringList& nameList, BStringList& urlList)
{
	BMessage settings(_ReadFromFile());
	settings.RemoveName(key_name);
	settings.RemoveName(key_url);

	int32 index, count = nameList.CountStrings();
	for (index = 0; index < count; index++) {
		settings.AddString(key_name, nameList.StringAt(index));
		settings.AddString(key_url, urlList.StringAt(index));
	}
	_SaveToFile(settings);
}
status_t
VirtualDirectoryEntryList::_InitMergedDirectory(
	const BStringList& directoryPaths)
{
	status_t error = fMergedDirectory.Init();
	if (error != B_OK)
		return error;

	int32 count = directoryPaths.CountStrings();
	for (int32 i = 0; i < count; i++)
		fMergedDirectory.AddDirectory(directoryPaths.StringAt(i));

	return B_OK;
}
Пример #14
0
static void
list_targets(bool verbose)
{
	BLaunchRoster roster;
	BStringList targets;
	status_t status = roster.GetTargets(targets);
	if (status != B_OK) {
		fprintf(stderr, "%s: Could not get target listing: %s\n", kProgramName,
			strerror(status));
		exit(EXIT_FAILURE);
	}

	for (int32 i = 0; i < targets.CountStrings(); i++)
		puts(targets.StringAt(i).String());
}
Пример #15
0
void
MainWindow::_RefreshRepositories(bool force)
{
	if (fSinglePackageMode)
		return;

	BPackageRoster roster;
	BStringList repositoryNames;

	status_t result = roster.GetRepositoryNames(repositoryNames);
	if (result != B_OK)
		return;

	DecisionProvider decisionProvider;
	JobStateListener listener;
	BContext context(decisionProvider, listener);

	BRepositoryCache cache;
	for (int32 i = 0; i < repositoryNames.CountStrings(); ++i) {
		const BString& repoName = repositoryNames.StringAt(i);
		BRepositoryConfig repoConfig;
		result = roster.GetRepositoryConfig(repoName, &repoConfig);
		if (result != B_OK) {
			// TODO: notify user
			continue;
		}

		if (roster.GetRepositoryCache(repoName, &cache) != B_OK || force) {
			try {
				BRefreshRepositoryRequest refreshRequest(context, repoConfig);

				result = refreshRequest.Process();
			} catch (BFatalErrorException ex) {
				BString message(B_TRANSLATE("An error occurred while "
					"refreshing the repository: %error% (%details%)"));
 				message.ReplaceFirst("%error%", ex.Message());
				message.ReplaceFirst("%details%", ex.Details());
				_NotifyUser("Error", message.String());
			} catch (BException ex) {
				BString message(B_TRANSLATE("An error occurred while "
					"refreshing the repository: %error%"));
				message.ReplaceFirst("%error%", ex.Message());
				_NotifyUser("Error", message.String());
			}
		}
	}
}
Пример #16
0
	virtual status_t HandleRepositoryInfo(const BRepositoryInfo& repositoryInfo)
	{
		printf("repository-info:\n");
		printf("\tname: %s\n", repositoryInfo.Name().String());
		printf("\tsummary: %s\n", repositoryInfo.Summary().String());
		printf("\turl: %s\n", repositoryInfo.OriginalBaseURL().String());
		printf("\tvendor: %s\n", repositoryInfo.Vendor().String());
		printf("\tpriority: %u\n", repositoryInfo.Priority());
		printf("\tarchitecture: %s\n",
			BPackageInfo::kArchitectureNames[repositoryInfo.Architecture()]);
		const BStringList licenseNames = repositoryInfo.LicenseNames();
		if (!licenseNames.IsEmpty()) {
			printf("\tlicenses:\n");
			for (int i = 0; i < licenseNames.CountStrings(); ++i)
				printf("\t\t%s\n", licenseNames.StringAt(i).String());
		}

		return B_OK;
	}
Пример #17
0
int
get_lines(BString *message, BStringList& list, int *longestLine)
{
	BString copy(*message);
	// Convert tabs to 4 spaces
	copy.ReplaceAll("\t", "    ");
	if (copy.Split("\n", false, list)) {
		int maxLength = 0;
		int32 count = list.CountStrings();
		for (int32 i = 0; i < count; i++) {
			int32 length = list.StringAt(i).Length();
			if (length  > maxLength) {
				maxLength = length;
				*longestLine = i;
			}
		}
		return count;
	}
	return 0;
}
Пример #18
0
void
MainWindow::_ShowDocumentation()
{
	BPathFinder pathFinder;
	BStringList paths;
	BPath path;
	BEntry entry;

	status_t error = pathFinder.FindPaths(B_FIND_PATH_DOCUMENTATION_DIRECTORY,
		"packages/pecorename", paths);

	for (int i = 0; i < paths.CountStrings(); ++i) {
		if (error == B_OK && path.SetTo(paths.StringAt(i)) == B_OK
				&& path.Append(B_TRANSLATE_COMMENT("ReadMe.html",
				"Path to the help file. Only change if a translated file is "
				"provided.")) == B_OK) {
			entry = path.Path();
			entry_ref ref;
			entry.GetRef(&ref);
			be_roster->Launch(&ref);
		}
	}
}
Пример #19
0
bool
BActivationTransaction::SetPackagesToDeactivate(const BStringList& packages)
{
	fPackagesToDeactivate = packages;
	return fPackagesToDeactivate.CountStrings() == packages.CountStrings();
}
Пример #20
0
status_t
POP3Protocol::SyncMessages()
{
	bool leaveOnServer;
	if (fSettings.FindBool("leave_mail_on_server", &leaveOnServer) != B_OK)
		leaveOnServer = true;

	// create directory if not exist
	create_directory(fDestinationDir, 0777);

	printf("POP3Protocol::SyncMessages()\n");
	_ReadManifest();

	SetTotalItems(2);
	ReportProgress(1, 0, B_TRANSLATE("Connect to server" B_UTF8_ELLIPSIS));

	status_t error = Connect();
	if (error != B_OK) {
		printf("POP3 could not connect: %s\n", strerror(error));
		ResetProgress();
		return error;
	}

	ReportProgress(1, 0, B_TRANSLATE("Getting UniqueIDs" B_UTF8_ELLIPSIS));

	error = _RetrieveUniqueIDs();
	if (error < B_OK) {
		ResetProgress();
		Disconnect();
		return error;
	}

	BStringList toDownload;
	NotHere(fManifest, fUniqueIDs, &toDownload);

	int32 numMessages = toDownload.CountStrings();
	if (numMessages == 0) {
		CheckForDeletedMessages();
		ResetProgress();
		Disconnect();
		return B_OK;
	}

	ResetProgress();
	SetTotalItems(toDownload.CountStrings());
	SetTotalItemsSize(fTotalSize);

	printf("POP3: Messages to download: %i\n", (int)toDownload.CountStrings());
	for (int32 i = 0; i < toDownload.CountStrings(); i++) {
		const char* uid = toDownload.StringAt(i);
		int32 toRetrieve = fUniqueIDs.IndexOf(uid);

		if (toRetrieve < 0) {
			// should not happen!
			error = B_NAME_NOT_FOUND;
			printf("POP3: uid %s index %i not found in fUniqueIDs!\n", uid,
				(int)toRetrieve);
			continue;
		}

		BPath path(fDestinationDir);
		BString fileName = "Downloading file... uid: ";
		fileName += uid;
		fileName.ReplaceAll("/", "_SLASH_");
		path.Append(fileName);
		BEntry entry(path.Path());
		BFile file(&entry, B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE);
		error = file.InitCheck();
		if (error != B_OK) {
			printf("POP3: Can't create file %s\n ", path.Path());
			break;
		}
		BMailMessageIO mailIO(this, &file, toRetrieve);
		BMessage attributes;

		entry_ref ref;
		entry.GetRef(&ref);

		int32 size = MessageSize(toRetrieve);
		if (fFetchBodyLimit < 0 || size <= fFetchBodyLimit) {
			error = mailIO.Seek(0, SEEK_END);
			if (error < 0) {
				printf("POP3: Failed to download body %s\n ", uid);
				break;
			}
			ProcessMessageFetched(ref, file, attributes);

			if (!leaveOnServer)
				Delete(toRetrieve);
		} else {
			int32 dummy;
			error = mailIO.ReadAt(0, &dummy, 1);
			if (error < 0) {
				printf("POP3: Failed to download header %s\n ", uid);
				break;
			}
			ProcessHeaderFetched(ref, file, attributes);
		}
		ReportProgress(1, 0);

		if (file.WriteAttr("MAIL:unique_id", B_STRING_TYPE, 0, uid,
				strlen(uid)) < 0)
			error = B_ERROR;

		file.WriteAttr("MAIL:size", B_INT32_TYPE, 0, &size, sizeof(int32));
		write_read_attr(file, B_UNREAD);

		// save manifest in case we get disturbed
		fManifest.Add(uid);
		_WriteManifest();
	}

	ResetProgress();

	CheckForDeletedMessages();
	Disconnect();
	return error;
}
Пример #21
0
void
NetworkWindow::_ScanAddOns()
{
	BStringList paths;
	BPathFinder::FindPaths(B_FIND_PATH_ADD_ONS_DIRECTORY, "Network Settings",
		paths);

	// Collect add-on paths by name, so that each name will only be
	// loaded once.
	typedef std::map<BString, BPath> PathMap;
	PathMap addOnMap;

	for (int32 i = 0; i < paths.CountStrings(); i++) {
		BDirectory directory(paths.StringAt(i));
		BEntry entry;
		while (directory.GetNextEntry(&entry) == B_OK) {
			BPath path;
			if (entry.GetPath(&path) != B_OK)
				continue;

			if (addOnMap.find(path.Leaf()) == addOnMap.end())
				addOnMap.insert(std::pair<BString, BPath>(path.Leaf(), path));
		}
	}

	for (PathMap::const_iterator addOnIterator = addOnMap.begin();
			addOnIterator != addOnMap.end(); addOnIterator++) {
		const BPath& path = addOnIterator->second;

		image_id image = load_add_on(path.Path());
		if (image < 0) {
			printf("Failed to load %s addon: %s.\n", path.Path(),
				strerror(image));
			continue;
		}

		BNetworkSettingsAddOn* (*instantiateAddOn)(image_id image,
			BNetworkSettings& settings);

		status_t status = get_image_symbol(image,
			"instantiate_network_settings_add_on",
			B_SYMBOL_TYPE_TEXT, (void**)&instantiateAddOn);
		if (status != B_OK) {
			// No "addon instantiate function" symbol found in this addon
			printf("No symbol \"instantiate_network_settings_add_on\" found "
				"in %s addon: not a network setup addon!\n", path.Path());
			unload_add_on(image);
			continue;
		}

		BNetworkSettingsAddOn* addOn = instantiateAddOn(image, fSettings);
		if (addOn == NULL) {
			unload_add_on(image);
			continue;
		}

		fAddOns.AddItem(addOn);

		// Per interface items
		ItemMap::const_iterator iterator = fInterfaceItemMap.begin();
		for (; iterator != fInterfaceItemMap.end(); iterator++) {
			const BString& interface = iterator->first;
			BListItem* interfaceItem = iterator->second;

			uint32 cookie = 0;
			while (true) {
				BNetworkSettingsItem* item = addOn->CreateNextInterfaceItem(
					cookie, interface.String());
				if (item == NULL)
					break;

				fSettingsMap[item->ListItem()] = item;
				fListView->AddUnder(item->ListItem(), interfaceItem);
			}
			fListView->SortItemsUnder(interfaceItem, true,
				NetworkWindow::_CompareListItems);
		}

		// Generic items
		uint32 cookie = 0;
		while (true) {
			BNetworkSettingsItem* item = addOn->CreateNextItem(cookie);
			if (item == NULL)
				break;

			fSettingsMap[item->ListItem()] = item;
			fListView->AddUnder(item->ListItem(),
				_ListItemFor(item->Type()));
		}

		_SortItemsUnder(fServicesItem);
		_SortItemsUnder(fDialUpItem);
		_SortItemsUnder(fOtherItem);
	}

	fListView->SortItemsUnder(NULL, true,
		NetworkWindow::_CompareTopLevelListItems);
}
Пример #22
0
thread_id
TeamDebugHandler::_EnterDebugger(bool saveReport)
{
    TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): team %" B_PRId32
           "\n", fTeam));

    // prepare a debugger handover
    TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): preparing "
           "debugger handover for team %" B_PRId32 "...\n", fTeam));

    status_t error = send_debug_message(&fDebugContext,
                                        B_DEBUG_MESSAGE_PREPARE_HANDOVER, NULL, 0, NULL, 0);
    if (error != B_OK) {
        debug_printf("debug_server: Failed to prepare debugger handover: %s\n",
                     strerror(error));
        return error;
    }

    BStringList arguments;
    const char *argv[16];
    int argc = 0;

    bool debugInConsoled = _IsGUIServer() || !_AreGUIServersAlive();
#ifdef HANDOVER_USE_GDB

    error = _SetupGDBArguments(arguments, debugInConsoled);
    if (error != B_OK) {
        debug_printf("debug_server: Failed to set up gdb arguments: %s\n",
                     strerror(error));
        return error;
    }

    // start the terminal
    TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): starting  "
           "terminal (debugger) for team %" B_PRId32 "...\n", fTeam));

#elif defined(HANDOVER_USE_DEBUGGER)
    if (!debugInConsoled && !saveReport
            && be_roster->IsRunning(kDebuggerSignature)) {

        // for graphical handovers, check if Debugger is already running,
        // and if it is, simply send it a message to attach to the requested
        // team.
        BMessenger messenger(kDebuggerSignature);
        BMessage message(MSG_DEBUG_THIS_TEAM);
        if (message.AddInt32("team", fTeam) == B_OK
                && messenger.SendMessage(&message) == B_OK) {
            return 0;
        }
    }

    // prepare the argument vector
    BPath debuggerPath;
    if (debugInConsoled) {
        error = find_directory(B_SYSTEM_BIN_DIRECTORY, &debuggerPath);
        if (error != B_OK) {
            debug_printf("debug_server: can't find system-bin directory: %s\n",
                         strerror(error));
            return error;
        }
        error = debuggerPath.Append("consoled");
        if (error != B_OK) {
            debug_printf("debug_server: can't append to system-bin path: %s\n",
                         strerror(error));
            return error;
        }

        if (!arguments.Add(debuggerPath.Path()))
            return B_NO_MEMORY;
    }

    error = find_directory(B_SYSTEM_APPS_DIRECTORY, &debuggerPath);
    if (error != B_OK) {
        debug_printf("debug_server: can't find system-apps directory: %s\n",
                     strerror(error));
        return error;
    }
    error = debuggerPath.Append("Debugger");
    if (error != B_OK) {
        debug_printf("debug_server: can't append to system-apps path: %s\n",
                     strerror(error));
        return error;
    }
    if (!arguments.Add(debuggerPath.Path()))
        return B_NO_MEMORY;

    if (debugInConsoled && !arguments.Add("--cli"))
        return B_NO_MEMORY;

    BString debuggerParam;
    debuggerParam.SetToFormat("%" B_PRId32, fTeam);
    if (saveReport) {
        if (!arguments.Add("--save-report"))
            return B_NO_MEMORY;
    }
    if (!arguments.Add("--team") || !arguments.Add(debuggerParam))
        return B_NO_MEMORY;

    // start the debugger
    TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): starting  "
           "%s debugger for team %" B_PRId32 "...\n",
           debugInConsoled ? "command line" : "graphical", fTeam));
#endif

    for (int32 i = 0; i < arguments.CountStrings(); i++)
        argv[argc++] = arguments.StringAt(i).String();
    argv[argc] = NULL;

    thread_id thread = load_image(argc, argv, (const char**)environ);
    if (thread < 0) {
        debug_printf("debug_server: Failed to start debugger: %s\n",
                     strerror(thread));
        return thread;
    }
    resume_thread(thread);

    TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): debugger started "
           "for team %" B_PRId32 ": thread: %" B_PRId32 "\n", fTeam, thread));

    return thread;
}
Пример #23
0
void
BGopherRequest::_ParseInput(bool last)
{
    BString line;

    while (_GetLine(line) == B_OK) {
        char type = GOPHER_TYPE_NONE;
        BStringList fields;

        line.MoveInto(&type, 0, 1);

        line.Split("\t", false, fields);

        if (type != GOPHER_TYPE_ENDOFPAGE
                && fields.CountStrings() < FIELD_GPFLAG)
            _EmitDebug(B_URL_PROTOCOL_DEBUG_TEXT,
                       "Unterminated gopher item (type '%c')", type);

        BString pageTitle;
        BString item;
        BString title = fields.StringAt(FIELD_NAME);
        BString link("gopher://");
        BString user;
        if (fields.CountStrings() > 3) {
            link << fields.StringAt(FIELD_HOST);
            if (fields.StringAt(FIELD_PORT).Length())
                link << ":" << fields.StringAt(FIELD_PORT);
            link << "/" << type;
            //if (fields.StringAt(FIELD_SELECTOR).ByteAt(0) != '/')
            //	link << "/";
            link << fields.StringAt(FIELD_SELECTOR);
        }
        _HTMLEscapeString(title);
        _HTMLEscapeString(link);

        switch (type) {
        case GOPHER_TYPE_ENDOFPAGE:
            /* end of the page */
            break;
        case GOPHER_TYPE_TEXTPLAIN:
            item << "<a href=\"" << link << "\">"
                 "<span class=\"text\">" << title << "</span></a>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_BINARY:
        case GOPHER_TYPE_BINHEX:
        case GOPHER_TYPE_BINARCHIVE:
        case GOPHER_TYPE_UUENCODED:
            item << "<a href=\"" << link << "\">"
                 "<span class=\"binary\">" << title << "</span></a>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_DIRECTORY:
            /*
             * directory link
             */
            item << "<a href=\"" << link << "\">"
                 "<span class=\"dir\">" << title << "</span></a>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_ERROR:
            item << "<span class=\"error\">" << title << "</span>"
                 "<br/>\n";
            if (fPosition == 0 && pageTitle.Length() == 0)
                pageTitle << "Error: " << title;
            break;
        case GOPHER_TYPE_QUERY:
            /* TODO: handle search better.
             * For now we use an unnamed input field and accept sending ?=foo
             * as it seems at least Veronica-2 ignores the = but it's unclean.
             */
            item << "<form method=\"get\" action=\"" << link << "\" "
                 "onsubmit=\"window.location = this.action + '?' + "
                 "this.elements['q'].value; return false;\">"
                 "<span class=\"query\">"
                 "<label>" << title << " "
                 "<input id=\"q\" name=\"\" type=\"text\" align=\"right\" />"
                 "</label>"
                 "</span></form>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_TELNET:
            /* telnet: links
             * cf. gopher://78.80.30.202/1/ps3
             * -> gopher://78.80.30.202:23/8/ps3/new -> [email protected]
             */
            link = "telnet://";
            user = fields.StringAt(FIELD_SELECTOR);
            if (user.FindLast('/') > -1) {
                user.Remove(0, user.FindLast('/'));
                link << user << "@";
            }
            link << fields.StringAt(FIELD_HOST);
            if (fields.StringAt(FIELD_PORT) != "23")
                link << ":" << fields.StringAt(FIELD_PORT);

            item << "<a href=\"" << link << "\">"
                 "<span class=\"telnet\">" << title << "</span></a>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_TN3270:
            /* tn3270: URI scheme, cf. http://tools.ietf.org/html/rfc6270 */
            link = "tn3270://";
            user = fields.StringAt(FIELD_SELECTOR);
            if (user.FindLast('/') > -1) {
                user.Remove(0, user.FindLast('/'));
                link << user << "@";
            }
            link << fields.StringAt(FIELD_HOST);
            if (fields.StringAt(FIELD_PORT) != "23")
                link << ":" << fields.StringAt(FIELD_PORT);

            item << "<a href=\"" << link << "\">"
                 "<span class=\"telnet\">" << title << "</span></a>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_CSO_SEARCH:
            /* CSO search.
             * At least Lynx supports a cso:// URI scheme:
             * http://lynx.isc.org/lynx2.8.5/lynx2-8-5/lynx_help/lynx_url_support.html
             */
            link = "cso://";
            user = fields.StringAt(FIELD_SELECTOR);
            if (user.FindLast('/') > -1) {
                user.Remove(0, user.FindLast('/'));
                link << user << "@";
            }
            link << fields.StringAt(FIELD_HOST);
            if (fields.StringAt(FIELD_PORT) != "105")
                link << ":" << fields.StringAt(FIELD_PORT);

            item << "<a href=\"" << link << "\">"
                 "<span class=\"cso\">" << title << "</span></a>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_GIF:
        case GOPHER_TYPE_IMAGE:
        case GOPHER_TYPE_PNG:
        case GOPHER_TYPE_BITMAP:
            /* quite dangerous, cf. gopher://namcub.accela-labs.com/1/pics */
            if (kInlineImages) {
                item << "<a href=\"" << link << "\">"
                     "<span class=\"img\">" << title << " "
                     "<img src=\"" << link << "\" "
                     "alt=\"" << title << "\"/>"
                     "</span></a>"
                     "<br/>\n";
                break;
            }
            /* fallback to default, link them */
            item << "<a href=\"" << link << "\">"
                 "<span class=\"img\">" << title << "</span></a>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_HTML:
            /* cf. gopher://pineapple.vg/1 */
            if (fields.StringAt(FIELD_SELECTOR).StartsWith("URL:")) {
                link = fields.StringAt(FIELD_SELECTOR);
                link.Remove(0, 4);
            }
            /* cf. gopher://sdf.org/1/sdf/classes/ */

            item << "<a href=\"" << link << "\">"
                 "<span class=\"html\">" << title << "</span></a>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_INFO:
            // TITLE resource, cf.
            // gopher://gophernicus.org/0/doc/gopher/gopher-title-resource.txt
            if (fPosition == 0 && pageTitle.Length() == 0
                    && fields.StringAt(FIELD_SELECTOR) == "TITLE") {
                pageTitle = title;
                break;
            }
            item << "<span class=\"info\">" << title << "</span>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_AUDIO:
        case GOPHER_TYPE_SOUND:
            item << "<a href=\"" << link << "\">"
                 "<span class=\"audio\">" << title << "</span></a>"
                 "<audio src=\"" << link << "\" "
                 //TODO:Fix crash in WebPositive with these
                 //"controls=\"controls\" "
                 //"width=\"300\" height=\"50\" "
                 "alt=\"" << title << "\"/>"
                 "<span>[player]</span></audio>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_PDF:
        case GOPHER_TYPE_DOC:
            /* generic case for known-to-work items */
            item << "<a href=\"" << link << "\">"
                 "<span class=\"document\">" << title << "</span></a>"
                 "<br/>\n";
            break;
        case GOPHER_TYPE_MOVIE:
            item << "<a href=\"" << link << "\">"
                 "<span class=\"video\">" << title << "</span></a>"
                 "<video src=\"" << link << "\" "
                 //TODO:Fix crash in WebPositive with these
                 //"controls=\"controls\" "
                 //"width=\"300\" height=\"300\" "
                 "alt=\"" << title << "\"/>"
                 "<span>[player]</span></audio>"
                 "<br/>\n";
            break;
        default:
            _EmitDebug(B_URL_PROTOCOL_DEBUG_TEXT,
                       "Unknown gopher item (type 0x%02x '%c')", type, type);
            item << "<a href=\"" << link << "\">"
                 "<span class=\"unknown\">" << title << "</span></a>"
                 "<br/>\n";
            break;
        }

        if (fPosition == 0) {
            if (pageTitle.Length() == 0)
                pageTitle << "Index of " << Url();

            const char *uplink = ".";
            if (fPath.EndsWith("/"))
                uplink = "..";

            // emit header
            BString header;
            header <<
                   "<html>\n"
                   "<head>\n"
                   "<meta http-equiv=\"Content-Type\""
                   " content=\"text/html; charset=UTF-8\" />\n"
                   //FIXME: fix links
                   //"<link rel=\"icon\" type=\"image/png\""
                   //	" href=\"resource:icons/directory.png\">\n"
                   "<style type=\"text/css\">\n" << kStyleSheet << "</style>\n"
                   "<title>" << pageTitle << "</title>\n"
                   "</head>\n"
                   "<body id=\"gopher\">\n"
                   "<div class=\"uplink dontprint\">\n"
                   "<a href=" << uplink << ">[up]</a>\n"
                   "<a href=\"/\">[top]</a>\n"
                   "</div>\n"
                   "<h1>" << pageTitle << "</h1>\n";

            fListener->DataReceived(this, header.String(), fPosition,
                                    header.Length());

            fPosition += header.Length();
        }

        if (item.Length()) {
            fListener->DataReceived(this, item.String(), fPosition,
                                    item.Length());

            fPosition += item.Length();
        }
    }

    if (last) {
        // emit footer
        BString footer =
            "</div>\n"
            "</body>\n"
            "</html>\n";

        fListener->DataReceived(this, footer.String(), fPosition,
                                footer.Length());

        fPosition += footer.Length();
    }
}
status_t
AccelerantHWInterface::_OpenAccelerant(int device)
{
	char signature[1024];
	if (ioctl(device, B_GET_ACCELERANT_SIGNATURE,
			&signature, sizeof(signature)) != B_OK) {
		return B_ERROR;
	}

	ATRACE(("accelerant signature is: %s\n", signature));

	fAccelerantImage = -1;

	BString leafPath("/accelerants/");
	leafPath << signature;
	BStringList addOnPaths;
	BPathFinder::FindPaths(B_FIND_PATH_ADD_ONS_DIRECTORY, leafPath.String(),
		addOnPaths);
	int32 count = addOnPaths.CountStrings();
	for (int32 i = 0; i < count; i++) {
		const char* path = addOnPaths.StringAt(i).String();
		struct stat accelerantStat;
		if (stat(path, &accelerantStat) != 0)
			continue;

		ATRACE(("accelerant path is: %s\n", path));

		fAccelerantImage = load_add_on(path);
		if (fAccelerantImage >= 0) {
			if (get_image_symbol(fAccelerantImage, B_ACCELERANT_ENTRY_POINT,
					B_SYMBOL_TYPE_ANY, (void**)(&fAccelerantHook)) != B_OK) {
				ATRACE(("unable to get B_ACCELERANT_ENTRY_POINT\n"));
				unload_add_on(fAccelerantImage);
				fAccelerantImage = -1;
				return B_ERROR;
			}

			init_accelerant initAccelerant;
			initAccelerant = (init_accelerant)fAccelerantHook(
				B_INIT_ACCELERANT, NULL);
			if (!initAccelerant || initAccelerant(device) != B_OK) {
				ATRACE(("InitAccelerant unsuccessful\n"));
				unload_add_on(fAccelerantImage);
				fAccelerantImage = -1;
				return B_ERROR;
			}

			break;
		}
	}

	if (fAccelerantImage < B_OK)
		return B_ERROR;

	if (_SetupDefaultHooks() != B_OK) {
		syslog(LOG_ERR, "Accelerant %s does not export the required hooks.\n",
			signature);

		uninit_accelerant uninitAccelerant = (uninit_accelerant)
			fAccelerantHook(B_UNINIT_ACCELERANT, NULL);
		if (uninitAccelerant != NULL)
			uninitAccelerant();

		unload_add_on(fAccelerantImage);
		return B_ERROR;
	}

	return B_OK;
}
Пример #25
0
/*
iterate over add-on-folders and collect information about each
catalog-add-ons (types of catalogs) into fCatalogAddOnInfos.
*/
status_t
LocaleRosterData::_InitializeCatalogAddOns()
{
	BAutolock lock(fLock);
	if (!lock.IsLocked())
		return B_ERROR;

	// add info about embedded default catalog:
	CatalogAddOnInfo* defaultCatalogAddOnInfo
		= new(std::nothrow) CatalogAddOnInfo("Default", "",
			DefaultCatalog::kDefaultCatalogAddOnPriority);
	if (!defaultCatalogAddOnInfo)
		return B_NO_MEMORY;

	defaultCatalogAddOnInfo->fInstantiateFunc = DefaultCatalog::Instantiate;
	defaultCatalogAddOnInfo->fCreateFunc = DefaultCatalog::Create;
	fCatalogAddOnInfos.AddItem((void*)defaultCatalogAddOnInfo);

	BStringList folders;
	BPathFinder::FindPaths(B_FIND_PATH_ADD_ONS_DIRECTORY, "locale/catalogs/",
		B_FIND_PATH_EXISTING_ONLY, folders);

	BPath addOnPath;
	BDirectory addOnFolder;
	char buf[4096];
	status_t err;
	for (int32 f = 0; f < folders.CountStrings(); f++) {
		BString addOnFolderName = folders.StringAt(f);
		err = addOnFolder.SetTo(addOnFolderName.String());
		if (err != B_OK)
			continue;

		// scan through all the folder's entries for catalog add-ons:
		int32 count;
		int8 priority;
		entry_ref eref;
		BNode node;
		BEntry entry;
		dirent* dent;
		while ((count = addOnFolder.GetNextDirents((dirent*)buf, sizeof(buf)))
				> 0) {
			dent = (dirent*)buf;
			while (count-- > 0) {
				if (strcmp(dent->d_name, ".") != 0
						&& strcmp(dent->d_name, "..") != 0
						&& strcmp(dent->d_name, "x86") != 0
						&& strcmp(dent->d_name, "x86_gcc2") != 0) {
					// we have found (what should be) a catalog-add-on:
					eref.device = dent->d_pdev;
					eref.directory = dent->d_pino;
					eref.set_name(dent->d_name);
					entry.SetTo(&eref, true);
						// traverse through any links to get to the real thang!
					node.SetTo(&entry);
					priority = -1;
					if (node.ReadAttr(kPriorityAttr, B_INT8_TYPE, 0,
						&priority, sizeof(int8)) <= 0) {
						// add-on has no priority-attribute yet, so we load it
						// to fetch the priority from the corresponding
						// symbol...
						BString fullAddOnPath(addOnFolderName);
						fullAddOnPath << "/" << dent->d_name;
						image_id image = load_add_on(fullAddOnPath.String());
						if (image >= B_OK) {
							uint8* prioPtr;
							if (get_image_symbol(image, "gCatalogAddOnPriority",
								B_SYMBOL_TYPE_DATA,
								(void**)&prioPtr) == B_OK) {
								priority = *prioPtr;
								node.WriteAttr(kPriorityAttr, B_INT8_TYPE, 0,
									&priority, sizeof(int8));
							}
							unload_add_on(image);
						}
					}

					if (priority >= 0) {
						// add-ons with priority < 0 will be ignored
						CatalogAddOnInfo* addOnInfo
							= new(std::nothrow) CatalogAddOnInfo(dent->d_name,
								addOnFolderName, priority);
						if (addOnInfo)
							fCatalogAddOnInfos.AddItem((void*)addOnInfo);
					}
				}
				// Bump the dirent-pointer by length of the dirent just handled:
				dent = (dirent*)((char*)dent + dent->d_reclen);
			}
		}
	}
	fCatalogAddOnInfos.SortItems(CompareInfos);

	return B_OK;
}
Пример #26
0
void
MainWindow::_RefreshPackageList()
{
	BPackageRoster roster;
	BStringList repositoryNames;

	status_t result = roster.GetRepositoryNames(repositoryNames);
	if (result != B_OK)
		return;

	DepotInfoMap depots;
	for (int32 i = 0; i < repositoryNames.CountStrings(); i++) {
		const BString& repoName = repositoryNames.StringAt(i);
		depots[repoName] = DepotInfo(repoName);
	}

	PackageManager manager(B_PACKAGE_INSTALLATION_LOCATION_HOME);
	try {
		manager.Init(PackageManager::B_ADD_INSTALLED_REPOSITORIES
			| PackageManager::B_ADD_REMOTE_REPOSITORIES);
	} catch (BException ex) {
		BString message(B_TRANSLATE("An error occurred while "
			"initializing the package manager: %message%"));
		message.ReplaceFirst("%message%", ex.Message());
		_NotifyUser("Error", message.String());
		return;
	}

	BObjectList<BSolverPackage> packages;
	result = manager.Solver()->FindPackages("",
		BSolver::B_FIND_CASE_INSENSITIVE | BSolver::B_FIND_IN_NAME
			| BSolver::B_FIND_IN_SUMMARY | BSolver::B_FIND_IN_DESCRIPTION
			| BSolver::B_FIND_IN_PROVIDES,
		packages);
	if (result != B_OK) {
		// TODO: notify user
		return;
	}

	if (packages.IsEmpty())
		return;

	PackageInfoMap foundPackages;
		// if a given package is installed locally, we will potentially
		// get back multiple entries, one for each local installation
		// location, and one for each remote repository the package
		// is available in. The above map is used to ensure that in such
		// cases we consolidate the information, rather than displaying
		// duplicates
	PackageInfoMap remotePackages;
		// any package that we find in a remote repository goes in this map.
		// this is later used to discern which packages came from a local
		// installation only, as those must be handled a bit differently
		// upon uninstallation, since we'd no longer be able to pull them
		// down remotely.
	BStringList systemFlaggedPackages;
		// any packages flagged as a system package are added to this list.
		// such packages cannot be uninstalled, nor can any of their deps.
	PackageInfoMap systemInstalledPackages;
		// any packages installed in system are added to this list.
		// This is later used for dependency resolution of the actual
		// system packages in order to compute the list of protected
		// dependencies indicated above.

	BitmapRef defaultIcon(new(std::nothrow) SharedBitmap(
		"application/x-vnd.haiku-package"), true);

	for (int32 i = 0; i < packages.CountItems(); i++) {
		BSolverPackage* package = packages.ItemAt(i);
		const BPackageInfo& repoPackageInfo = package->Info();
		PackageInfoRef modelInfo;
		PackageInfoMap::iterator it = foundPackages.find(
			repoPackageInfo.Name());
		if (it != foundPackages.end())
			modelInfo.SetTo(it->second);
		else {
			// Add new package info
			BString publisherURL;
			if (repoPackageInfo.URLList().CountStrings() > 0)
				publisherURL = repoPackageInfo.URLList().StringAt(0);

			BString publisherName = repoPackageInfo.Vendor();
			const BStringList& rightsList = repoPackageInfo.CopyrightList();
			if (rightsList.CountStrings() > 0)
				publisherName = rightsList.StringAt(0);

			modelInfo.SetTo(new(std::nothrow) PackageInfo(
					repoPackageInfo.Name(),
					repoPackageInfo.Version().ToString(),
					PublisherInfo(BitmapRef(), publisherName,
					"", publisherURL), repoPackageInfo.Summary(),
					repoPackageInfo.Description(),
					repoPackageInfo.Flags()),
				true);

			if (modelInfo.Get() == NULL)
				return;

			foundPackages[repoPackageInfo.Name()] = modelInfo;
		}

		modelInfo->SetIcon(defaultIcon);
		modelInfo->AddListener(this);

		BSolverRepository* repository = package->Repository();
		if (dynamic_cast<BPackageManager::RemoteRepository*>(repository)
				!= NULL) {
			depots[repository->Name()].AddPackage(modelInfo);
			remotePackages[modelInfo->Title()] = modelInfo;
		} else {
			if (repository == static_cast<const BSolverRepository*>(
					manager.SystemRepository())) {
				modelInfo->AddInstallationLocation(
					B_PACKAGE_INSTALLATION_LOCATION_SYSTEM);
				if (!modelInfo->IsSystemPackage()) {
					systemInstalledPackages[repoPackageInfo.FileName()]
						= modelInfo;
				}
			} else if (repository == static_cast<const BSolverRepository*>(
					manager.HomeRepository())) {
				modelInfo->AddInstallationLocation(
					B_PACKAGE_INSTALLATION_LOCATION_HOME);
			}
		}

		if (modelInfo->IsSystemPackage())
			systemFlaggedPackages.Add(repoPackageInfo.FileName());
	}

	BAutolock lock(fModel.Lock());

	fModel.Clear();

	// filter remote packages from the found list
	// any packages remaining will be locally installed packages
	// that weren't acquired from a repository
	for (PackageInfoMap::iterator it = remotePackages.begin();
			it != remotePackages.end(); it++) {
		foundPackages.erase(it->first);
	}

	if (!foundPackages.empty()) {
		BString repoName = B_TRANSLATE("Local");
		depots[repoName] = DepotInfo(repoName);
		DepotInfoMap::iterator depot = depots.find(repoName);
		for (PackageInfoMap::iterator it = foundPackages.begin();
				it != foundPackages.end(); ++it) {
			depot->second.AddPackage(it->second);
		}
	}

	for (DepotInfoMap::iterator it = depots.begin(); it != depots.end(); it++) {
		fModel.AddDepot(it->second);
	}

	// start retrieving package icons and average ratings
	fModel.PopulateAllPackages();

	// compute the OS package dependencies
	try {
		// create the solver
		BSolver* solver;
		status_t error = BSolver::Create(solver);
		if (error != B_OK)
			throw BFatalErrorException(error, "Failed to create solver.");

		ObjectDeleter<BSolver> solverDeleter(solver);
		BPath systemPath;
		error = find_directory(B_SYSTEM_PACKAGES_DIRECTORY, &systemPath);
		if (error != B_OK) {
			throw BFatalErrorException(error,
				"Unable to retrieve system packages directory.");
		}

		// add the "installed" repository with the given packages
		BSolverRepository installedRepository;
		{
			BRepositoryBuilder installedRepositoryBuilder(installedRepository,
				"installed");
			for (int32 i = 0; i < systemFlaggedPackages.CountStrings(); i++) {
				BPath packagePath(systemPath);
				packagePath.Append(systemFlaggedPackages.StringAt(i));
				installedRepositoryBuilder.AddPackage(packagePath.Path());
			}
			installedRepositoryBuilder.AddToSolver(solver, true);
		}

		// add system repository
		BSolverRepository systemRepository;
		{
			BRepositoryBuilder systemRepositoryBuilder(systemRepository,
				"system");
			for (PackageInfoMap::iterator it = systemInstalledPackages.begin();
					it != systemInstalledPackages.end(); it++) {
				BPath packagePath(systemPath);
				packagePath.Append(it->first);
				systemRepositoryBuilder.AddPackage(packagePath.Path());
			}
			systemRepositoryBuilder.AddToSolver(solver, false);
		}

		// solve
		error = solver->VerifyInstallation();
		if (error != B_OK) {
			throw BFatalErrorException(error, "Failed to compute packages to "
				"install.");
		}

		BSolverResult solverResult;
		error = solver->GetResult(solverResult);
		if (error != B_OK) {
			throw BFatalErrorException(error, "Failed to retrieve system "
				"package dependency list.");
		}

		for (int32 i = 0; const BSolverResultElement* element
				= solverResult.ElementAt(i); i++) {
			BSolverPackage* package = element->Package();
			if (element->Type() == BSolverResultElement::B_TYPE_INSTALL) {
				PackageInfoMap::iterator it = systemInstalledPackages.find(
					package->Info().FileName());
				if (it != systemInstalledPackages.end())
					it->second->SetSystemDependency(true);
			}
		}
	} catch (BFatalErrorException ex) {
		printf("Fatal exception occurred while resolving system dependencies: "
			"%s, details: %s\n", strerror(ex.Error()), ex.Details().String());
	} catch (BNothingToDoException) {
		// do nothing
	} catch (BException ex) {
		printf("Exception occurred while resolving system dependencies: %s\n",
			ex.Message().String());
	} catch (...) {
		printf("Unknown exception occurred while resolving system "
			"dependencies.\n");
	}
}
Пример #27
0
thread_id
TeamDebugHandler::_EnterDebugger(bool saveReport)
{
	TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): team %" B_PRId32
		"\n", fTeam));

	// prepare a debugger handover
	TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): preparing "
		"debugger handover for team %" B_PRId32 "...\n", fTeam));

	status_t error = send_debug_message(&fDebugContext,
		B_DEBUG_MESSAGE_PREPARE_HANDOVER, NULL, 0, NULL, 0);
	if (error != B_OK) {
		debug_printf("debug_server: Failed to prepare debugger handover: %s\n",
			strerror(error));
		return error;
	}

	BStringList arguments;
	const char *argv[16];
	int argc = 0;

	bool debugInConsoled = _IsGUIServer() || !_AreGUIServersAlive();
#ifdef HANDOVER_USE_GDB

	error = _SetupGDBArguments(arguments, debugInConsoled);
	if (error != B_OK) {
		debug_printf("debug_server: Failed to set up gdb arguments: %s\n",
			strerror(error));
		return error;
	}

	// start the terminal
	TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): starting  "
		"terminal (debugger) for team %" B_PRId32 "...\n", fTeam));

#elif defined(HANDOVER_USE_DEBUGGER)
	if (debugInConsoled) {
		error = _SetupGDBArguments(arguments, debugInConsoled);
		if (error != B_OK) {
			debug_printf("debug_server: Failed to set up gdb arguments: %s\n",
				strerror(error));
			return error;
		}
	} else {
		// prepare the argument vector
		BPath debuggerPath;
		error = find_directory(B_SYSTEM_APPS_DIRECTORY, &debuggerPath);
		if (error != B_OK) {
			debug_printf("debug_server: can't find system-apps directory: %s\n",
				strerror(error));
			return error;
		}
		error = debuggerPath.Append("Debugger");
		if (error != B_OK) {
			debug_printf("debug_server: can't append to system-apps path: %s\n",
				strerror(error));
			return error;
		}
		if (!arguments.Add(debuggerPath.Path()))
			return B_NO_MEMORY;

		BString debuggerParam;
		debuggerParam.SetToFormat("%" B_PRId32, fTeam);
		if (saveReport) {
			if (!arguments.Add("--save-report"))
				return B_NO_MEMORY;
		}
		if (!arguments.Add("--team") || !arguments.Add(debuggerParam))
			return B_NO_MEMORY;

		// start the debugger
		TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): starting  "
			"graphical debugger for team %" B_PRId32 "...\n", fTeam));
	}
#endif

	for (int32 i = 0; i < arguments.CountStrings(); i++)
		argv[argc++] = arguments.StringAt(i).String();
	argv[argc] = NULL;

	thread_id thread = load_image(argc, argv, (const char**)environ);
	if (thread < 0) {
		debug_printf("debug_server: Failed to start debugger: %s\n",
			strerror(thread));
		return thread;
	}
	resume_thread(thread);

	TRACE(("debug_server: TeamDebugHandler::_EnterDebugger(): debugger started "
		"for team %" B_PRId32 ": thread: %" B_PRId32 "\n", fTeam, thread));

	return thread;
}
Пример #28
0
int
main(int argc, const char* const* argv)
{
	const char* architecture = NULL;
	const char* dependency = NULL;
	const char* referencePath = NULL;
	bool existingOnly = false;
	const char* separator = NULL;

	while (true) {
		static struct option sLongOptions[] = {
			{ "architecture", required_argument, 0, 'a' },
			{ "dependency", required_argument, 0, 'd' },
			{ "help", no_argument, 0, 'h' },
			{ "path", required_argument, 0, 'p' },
			{ 0, 0, 0, 0 }
		};

		opterr = 0; // don't print errors
		int c = getopt_long(argc, (char**)argv, "+a:c:d:ehlp:",
			sLongOptions, NULL);
		if (c == -1)
			break;

		switch (c) {
			case 'a':
				architecture = optarg;
				break;

			case 'c':
				separator = optarg;
				break;

			case 'd':
				dependency = optarg;
				break;

			case 'e':
				existingOnly = true;
				break;

			case 'h':
				print_usage_and_exit(false);
				break;

			case 'l':
				for (size_t i = 0; i < kDirectoryConstantCount; i++) {
					const DirectoryConstantEntry& entry
						= kDirectoryConstants[i];
					printf("%s\n    - %s\n", entry.string, entry.description);
				}
				exit(0);

			case 'p':
				referencePath = optarg;
				break;

			default:
				print_usage_and_exit(true);
				break;
		}
	}

	// The remaining arguments are the kind constant and optionally the subpath.
	if (optind >= argc || optind + 2 < argc)
		print_usage_and_exit(true);

	const char* kindConstant = argv[optind++];

	const char* subPath = NULL;
	if (optind >= argc)
		subPath = argv[optind++];

	// resolve the directory constant
	path_base_directory baseDirectory = B_FIND_PATH_IMAGE_PATH;
	bool found = false;
	for (size_t i = 0; i < kDirectoryConstantCount; i++) {
		const DirectoryConstantEntry& entry = kDirectoryConstants[i];
		if (strcmp(kindConstant, entry.string) == 0) {
			found = true;
			baseDirectory = entry.constant;
			break;
		}
	}

	if (!found) {
		fprintf(stderr, "Error: Unsupported directory constant \"%s\".\n",
			kindConstant);
		exit(1);
	}

	if (referencePath != NULL) {
		BPath path;
		status_t error = BPathFinder(referencePath, dependency).FindPath(
			architecture, baseDirectory, subPath,
			existingOnly ? B_FIND_PATH_EXISTING_ONLY : 0, path);
		if (error != B_OK) {
			fprintf(stderr, "Error: Failed to find path: %s\n",
				strerror(error));
			exit(1);
		}

		printf("%s\n", path.Path());
	} else {
		BStringList paths;
		status_t error = BPathFinder::FindPaths(architecture, baseDirectory,
			subPath, existingOnly ? B_FIND_PATH_EXISTING_ONLY : 0, paths);
		if (error != B_OK) {
			fprintf(stderr, "Error: Failed to find paths: %s\n",
				strerror(error));
			exit(1);
		}

		if (separator != NULL) {
			BString result = paths.Join(separator);
			if (result.IsEmpty()) {
				fprintf(stderr, "Error: Out of memory!\n");
				exit(1);
			}
			printf("%s\n", result.String());
		} else {
			int32 count = paths.CountStrings();
			for (int32 i = 0; i < count; i++)
				printf("%s\n", paths.StringAt(i).String());
		}
	}

	return 0;
}