#!/Users/scouten/Adobe/lightroom/7.0/imported/adobe/wichitafoundation/tools/cocoa/coverage/lua

-- A Q&D hack script to identify which message processor are getting left behind.
-- Lots of hard-coded paths here. You'll have to tweak the script for your machine.

-- How to use:

	-- 1. In WFMessaging.c, circa line 74, change #define DEBUG_MESSAGING_PROCESSOR_LEAKS
	--	  to 1. DO NOT CHECK THIS IN TO MASTER!

	-- 2. Push the updated code to a branch and submit a PR marked [DO NOT MERGE].

	-- 3. Go have lunch. It'll take an hour or more for the build to run.

	-- 4. When the build completes, save the full build log to mp-leak.txt.

	-- 5. Update this script to point to mp-leak. (See "local file = io.open"... below.)

	-- 6. There will be a boatload of debug output which you can mostly ignore.
	--	  Near the bottom, you'll see something like:

--[[
	    4    leftover MPs


Leaked MP   00007F809495F5D0     with name  WFRxHttpClientImp.lua
Leaked MP   00007F809453B1E0     with name  WFLuaTestLoader.lua :: WFWorkerThreadTest
Leaked MP   00007F809493B650     with name  WFLuaTestLoader.lua :: WFTestFileUtilsTest
Leaked MP   00007F808ACF0910     with name  WFDiagnosticLogImp.lua
]]--

	-- 7. Those message processors contain leaks or references that are keeping them
	--	  alive. As of this writing, we're still finding instances where WFRxNativeObservable
	--	  instances are improperly ref-counted, causing the host MP to remain alive.
	--	  See https://git.corp.adobe.com/lightroom/lightroom/pull/515 for examples of
	--	  how to fix.

	-- 8. Ping me (scouten@adobe.com) if you have more questions.

local file = io.open( "/Users/scouten/Desktop/mp-leak.txt", "r" )

local openMPs = {}

while true do

	local line = file:read()
	if not line then break end

	local _, _, mpId, name = line:find( "Creating message processor ([0-9A-F]+), name = (.*)" )
	if mpId and name then
		print( "Creating MP ", mpId, " with name ", name )
		openMPs[ mpId ] = name
	end

	local _, _, deadMpId = line:find( "Closing message processor ([0-9A-F]+)" )
	if deadMpId then
		print( "Closing MP ", deadMpId )
		openMPs[ deadMpId ] = nil
	end

end

local count = 0
for id in pairs( openMPs ) do
	count = count + 1
end

print( "\n\n", count, " leftover MPs\n\n" )

for id, name in pairs( openMPs ) do
	print( "Leaked MP ", id, " with name ", name )
end
