Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hs.ipc: Avoid reentrance when in printReplacement #3718

Merged
merged 2 commits into from
Nov 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 39 additions & 4 deletions extensions/ipc/ipc.lua
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,54 @@ local MSG_ID = {
CONSOLE = 3, -- cloned console output
}

-- stop printReplacement from being reentrant
-- otherwise errors might cascade into lots of recursive prints
-- hammerspoon is single threaded, thus this does not need a semaphore
-- otherwise we'll have to deal with a potential race condition
module.insidePrintInstances = {}

module.print_enter = function(instance)
val = module.insidePrintInstances[instance] or 0
module.insidePrintInstances[instance] = val + 1
end

module.print_exit = function(instance)
-- make sure instance exists
if module.insidePrintInstances[instance] then
module.insidePrintInstances[instance] = module.insidePrintInstances[instance] - 1
-- make sure to delete the entry from the table to avoid
-- growing forever
if module.insidePrintInstances[instance] == 0 then
module.insidePrintInstances[instance] = nil
end
end
end

module.print_inside = function(instance)
-- return true if we are already inside printReplacement
val = module.insidePrintInstances[instance]
return val and val > 0
end

local originalPrint = print
local printReplacement = function(...)
originalPrint(...)
for _,v in pairs(module.__registeredCLIInstances) do
for id,v in pairs(module.__registeredCLIInstances) do
if v._cli.console and v.print and not v._cli.quietMode then
-- v.print(...)
-- make it more obvious what is console output versus the command line's
if module.print_inside(id) then
log.w(string.format("Instance of [%s] already recursing, refusing request.", id))
else
module.print_enter(id)
-- v.print(...)
-- make it more obvious what is console output versus the command line's
local things = table.pack(...)
local stdout = (things.n > 0) and tostring(things[1]) or ""
for i = 2, things.n do
stdout = stdout .. "\t" .. tostring(things[i])
stdout = stdout .. "\t" .. tostring(things[i])
end
v._cli.remote:sendMessage(stdout .. "\n", MSG_ID.CONSOLE)
module.print_exit(id)
end
end
end
end
Expand Down
Loading