Skip to content

Commit

Permalink
Ensure linenoise can be safely used from multiple threads (#16388)
Browse files Browse the repository at this point in the history
This addresses a data race for `linenoise::lnstate` and
`StdInOutConsole::_isPromptShowing` which could result in openrct2
crashing and misreporting values when inspected in debugger.
  • Loading branch information
janisozaur committed Jan 7, 2022
1 parent 2e9e549 commit f68411b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/openrct2/interface/InteractiveConsole.h
Expand Up @@ -12,6 +12,7 @@
#include "../common.h"
#include "../localisation/FormatCodes.h"

#include <atomic>
#include <future>
#include <queue>
#include <string>
Expand Down Expand Up @@ -53,7 +54,7 @@ class StdInOutConsole final : public InteractiveConsole
{
private:
std::queue<std::tuple<std::promise<void>, std::string>> _evalQueue;
bool _isPromptShowing{};
std::atomic<bool> _isPromptShowing{};

public:
void Start();
Expand Down
4 changes: 4 additions & 0 deletions src/thirdparty/linenoise.hpp
Expand Up @@ -157,6 +157,7 @@
#include <functional>
#include <vector>
#include <iostream>
#include <mutex>

namespace linenoise {

Expand Down Expand Up @@ -1094,6 +1095,7 @@ struct linenoiseState {
int history_index; /* The history index we are currently editing. */
};

static std::mutex lnstate_mutex;
static struct linenoiseState lnstate;

enum KEY_ACTION {
Expand Down Expand Up @@ -2092,6 +2094,7 @@ inline void linenoiseEditDeletePrevWord(struct linenoiseState *l) {

inline void linenoiseEditRefreshLine()
{
std::lock_guard lock(lnstate_mutex);
refreshLine(&lnstate);
}

Expand All @@ -2105,6 +2108,7 @@ inline void linenoiseEditRefreshLine()
* The function returns the length of the current buffer. */
inline int linenoiseEdit(int stdin_fd, int stdout_fd, char *buf, int buflen, const char *prompt)
{
std::lock_guard lock(lnstate_mutex);
auto& l = lnstate;

/* Populate the linenoise state that we pass to functions implementing
Expand Down

0 comments on commit f68411b

Please sign in to comment.