Wait-Chain Traversal: Or, How We Can Use PowerShell to JIT C# to Load an Unmanaged Assembly (C++), InterOping With Windows APIs, Returning that Data Back to PowerShell

So, as the long-winded title infers, today I’ll be covering something that I wrote a long time ago and have recently re-written (albeit, probably badly) for you to use and/or learn from.

In this case, we’re using a PowerShell script, which JITs C# code, the C# code calls into an unmanaged DLL (C++), and that calls into an Windows API. Once the data has been obtained from the Windows API, we pass the data back from the unmanaged assembly to the managed code (via Marshal) and then return that back to the PowerShell instance to be displayed to the user.

Before we dive into the what we’re doing, we should cover some key concepts. The first is JIT’ing. JIT stands for “Just-In-Time” (Compilation) and the name is slightly a misnomer but we’ll cover that in a second. So, in JIT, what happens is that the run time precompiles the code before it’s ran. This is important because a key-concept in exception handling is the runtime’s seek operation to find a handler for an exception that is thrown. You’ll often see this as a FirstChanceException in a dump file. In PowerShell, we have the added ability to leverage the JIT compilation by passing source code as a type into the App’s Domain. It’s important to distinguish that once the App Domain has been disposed of, the type specified is lost and has to be re-instantiated again.

So, what – exactly – is this code going to be doing? Well, since Windows Vista, the Windows Operating System exposes the Wait Chain Traversal API. You can see a demonstration of this API in Task Manager: Go to the Details tab, right click on a process and click “Analyze Wait Chain”.

Since Windows Server 2016 Core doesn’t include a desktop or any GUI interfaces, a more robust way was needed to obtain the same information in production, to determine if the reason an application wasn’t responding or performing work was because the threads were blocked.

When you run the code, you can tell if this is the case or not by something like the following:

12972   [7464:12972:blocked]->[ThreadWait]->[7464:12968:blocked]->[End]

Where the first thread is blocked by a thread wait on the the second thread, which is also (itself) blocked.

So, first things first, the PowerShell code. Take a peek here to see that. Note that the Source code is contained with a specific character-delimited string @”<code>”@. After that we add a Type, pointing it to the source code we’ve defined and referencing the assemblies that we’ll need for this type to work. Worthy of noting is that when we add this type, it is exposed in PowerShell the same way any normal .NET type is, via the []:: convention.

Note that in the C# source we import the unmanaged DLL and reference the exposed method. In the body of the code, we also construct an IntPtr to reference for the return. So, now, we get to Marshalling.

An IntPtr is, quite literally, a pointer or handle to an object. A pointer is a reference to memory where an object exists and the object is typically delimited by characters to signify the termination of it (e.g.: the end of a string is null-terminated). A handle is roughly the same premise but the handle abstracts memory management from the caller. So, at 200 ticks, the handle could point to address 0x000001 and at 369 ticks, it could point to 0x34778.

Alright, so why this matters is because when we pass from unmanaged code back to managed code, there’s nothing that implicitly tells the managed code where to find the object in native memory; so, we have to pass a pointer to the object back to managed (I believe managed creates it’s own copy and creates an address for that object) and, using that, we can then try to convert the passed object from a native string into a managed string (via Marshalling).

What about this unmanaged code I keep hearing about? Oh, well… You can find that here. Don’t forget to add the headers referenced in stdafx.h, or your compiler will cry bloody murder.

So, how this works is: The script is called via PowerShell. After some magic to verify that we weren’t given junk data, then PowerShell JIT’s the C# code and performs the runtime operations. The compiler loads the unmanaged DLL into memory. The C# code then calls into the unmanaged DLL via the exposed method (declspec/dllexport/cdecl). The unmanaged code performs it’s work and returns the string back to the caller – unaware that the caller is managed code. The managed code creates an IntPtr to reference the return and then Marshal is called to convert the native string into a managed string. This is then returned back to the user. In the case of multiple instances of a process, the managed string is added to an array and that array is returned.

While it may not seem like much and seem like overglorified complication just to check for threads on wait chaings, it was code that was written to be used in production where we had no desktop environments and we had to determine if this was the case.

I hope that someone gets some kind of use out of it. 🙂

Until next time.

En promenad på Sondag

Was a late night, last night, and that makes for a late to rise and slow moving, lazy Sunday morning.

I haven’t a way to describe the why and to preserve the anonymity of those involved, I won’t go into great detail, but I face today with a sundry of emotions.

On the positive side of things, my bestie and my roommate (and fam) are all on the same flight back to Dublin from Seattle. They’re still in the air (it isn’t a short flight, considering it’s direct from Seattle to Dublin, to be sure) but I hope to hear from them, soon, that they’re all safe and sound back in the land of Ire.

My roommate got a job working with my bestie; so, it’s funny how happenstances collide to conspire to make good things happen. Sadly, I didn’t impress one of the managers during my own interview gauntlet with said company, so I won’t be working there with them. As the French say, c’est la vie.

Luckily, the clouds stayed away today, so it’s a bright and sunny day.

So, having thoroughly explored Linköping and Norrköping, I hopped on the commuter train and went to Motala. It’s about the size of the largest city near where I grew up, so I figured it was worth a visit.

I’d been to Linghem, before, (which is also on the way) when I had the bout with abscess, and from what I saw, there wasn’t much to it.

So, Motala was the only one left.

Did I mention I like the Swedish countryside? It’s not as good as the English countryside, to be sure, but it has its own charms.

And then: A wild ladybug appeared.

No idea where it got off to, though.

My initial impression of Motala is that I like it. I’m not a fan of Sweden Mobile putting me on the Edge network, though, but what is one to do, yeah?

Everything was closed because it was Sunday. Sure, the Pressbyrån and the Subway restaurant were open but everything else was closed. It was kind of like how you’d imagine it being if some cataclysmic event happened. Remember the stand? Yeah, kind of like that.

So, hoped back on the train towards Norrköping and discovered I didn’t have enough to get back. Enter the Östgötatrafiken app to save the day. A 24-hour ticket? 125SEK (about €12.50).

Well, I think that will be it, for now. A lot on my mind and my heart, plus, I got this other thing I’m trying to get sorted by Monday. Le sigh.

Thanks for stopping by, dear reader.

As Jim Carey’s character says in Bruce Almighty, “And that’s the way the cookie crumbles.”

Rödadag

Today, in Sweden, it’s a Rödadag (pronounced: Road-ah-dawg), which means it’s a public holiday in which almost no one works. Public transit still operates but on holiday schedules.

Speaking of public transit, trains and buses contain the names of the drivers on the sides of them.

So, this time, I took the train to the Vidablick area. I didn’t know of anything that was already out there, I just figured that I may as well take the train to the end of the green line and check stuff out once I got there.

Of course, I only made it a few stops before I saw something that made me want to get off: Another church with a pretty hefty park surrounding it.

The area is called Folkparken (literal translation is “The Peoples Park”) but I was unable to figure out what the name of the church was.

However, the nearby graveyard tends to lend that the name of the church is Matteus Kyrka.

Then, it was time to see the actual park because parks.

Next was an area, still technically within the park I think, called Norra Kyrkogården.

This was another graveyard and recall that today was All Saints Day, so the graveyards were a bit busier than usual (I don’t think busier would be the most apropos adjective but whatever).

After that, it was time for more of the park, on the other side of this graveyard. Only… I was slightly wrong on my assumption: I had stumbled from there directly into Himmelstalunds Kapell.

After that then it was more of the actual park.

Somehow, I ended-up back at Matteus Kyrka, so it was time to hop back on the train and keep going.

Also, at about this time, my battery was at 13%; so I had to throw it on the battery pack to keep it charged, so I could keep writing this. (Yes, I write this as I go along because my memory is shit.)

Vidablick didn’t have much to it.

So, I walked to the red line and got off at Fridvalla. It was pretty much the same with Fridvalla but the clouds were starting to break-up and the sun was coming out, so there was that.

I kept seeing signs for Café Bråvalla in Företagspark (business park) and figured that maybe it might be a safe bet to snag some food. That is, until I came upon this sign about halfway there.

Admittedly, my assumption was wrong. Not all was lost, though. The sun finally came out.

So, I walked back to Fridvalla to take the red line back into town.

Which brings me to how the trains turn around here. Well, maybe it’s just specific to Norrköping, really. Anyway, they make a full loop to go back from whence they came.

So, empty transit photo? Empty transit photo.

The red line goes between Fridvalla and Kvarnberget; so, it was time to go to the other side and see what things were like there.

I only got as far as Södertull, though, because I needed both to eat something and to go to the store.

It look like Anonymous was doing a demonstration by Spiralen, judging from the masks, but I’m more inclined to think it was actually PETA because they were showing animal videos.

Got back on the red line, headed towards Kvarnberget but biology had different ideas about that. So, I got off at Ljura spårvägsbro and got back on the south-bound line. Will be nice to drop this stuff off at the hotel, anyways.

In other news, I can now fit in size 34 pants comfortably. The question becomes: Will they be size 34s after they’re washed? Only time will tell.

Did the needful and headed back towards the red line. This time, I got off at Hageby Centrum and a shopping centre greeted me.

It was a decent shopping centre and the layout a bit lacklustre but I finally found out what a Willy:S is.

Then, hopped on and got off at Ringsansens Centrum.

Creepy tunnel? Creepy tunnel.

The other side of the creepy tunnel led to an unlit path that pretty much dead-ended at the Syrianksa Ortodoxa Kyrka St:Kyriakos church. So, that was pretty much a bust.

Blurry picture is bluryingly blurry, I’m aware.

Without the clouds acting as a thermal blanket, it started to get chilli (about 5C or 6C). So, I figured, “Why not walk to the last stop and ride back into town?” You know, as one does. So, that’s precisely what I did.

Along the way, I found an oddly lit pole with a parking sign on it but because I’m dressed like the black power ranger and walking around at night, I figured it best to just take a photo of it and be on my way, rather than get all kinds of investigative about it.

Then, it was time to hop back on the train, again. Public transiting intensifies.

Got off at Södertull and walked over to CNEMA. Had bought a ticket for Bohemian Rhapsody, so couldn’t pass it up. Sadly, the theatre doesn’t do popcorn, so will probably be my first and last time seeing a movie here.

That’s it for today. Thanks for visiting, dear reader.

As they used to say on the old Batman TV show, “Tune in next week. Same bat time, same bat channel.”

Annan dag i Norrköping

Start the day with breakfast at the hotel and it was off to walking, again. This time I walked from the Söderstaden area to the Ljura area, in search of Ljuraparken.

First things, first, the Swedes are sticklers (mostly) for following rules and for safety. Even in a small city, they’ll caution on the side of safety (which isn’t inherently a bad thing, whatsoever).

Check out the fishermen and fisherwomen in this photo. See any glaring colours that pop-out at you?

It was a bit of a walk to get to Ljuraparken, as I took the long way ’round but it gave ample opportunity to snap some more photos and videos. For science.

http://www.iseelondoniseefrance.se/wp-content/uploads/2018/11/img_0549.mov

When I got to Ljuraparken, I felt entirely bamboozled. You see, this was the visage that greeted me.

And Apple Maps had it all as one big, green park. Sneaky, sneaky Apple Maps…

However, I’m not one to give up that easily. After all, I had walked all of this way and it wasn’t going to be for naught. I walked passed the buildings, to the inner square, and found the park that I was looking for (queue U2 song here).

On the other side of the park is S:t Johannes Kyrka. Sadly, there were funeral services going on, so I didn’t want to get all camera-happy. I think in any culture that’s generally considered a dick move.

I saw that people were leaving these coniferous looking wreathes at graves and I wondered what that was about. I found a shop selling them and figured I’d stop in to ask.

It turns out that Allhelgonadagen (also known as Alla Helgons Dag) is on 3 Nov 2018. We call this day All Saints Day in English.

The reason why they use the branches and cones from coniferous trees is because it harkens back to the days of old, when there were no such things as flowers during the fall/winter time.

After that, I took the train back towards resecentrum. It costs about €2.50 to ride the train but that’s the base fee. That’s it. Even if you ride from one end to the other.

After that, I realised I want to do a little bit of shopping (failure to plan, means failure to perform) and got back on the train towards Stora torget.

A little bit of lunch was in order, around now, so I popped into Kafé Kuriosa for a spot of food. Sadly their card machine was broken and this was the first time, in about three or four months, that I had to find an ATM to withdraw kronor from.

Kontantfri (cash free) is the the future of Sweden and, as such, one hardly ever has need of physical money, anymore. They’ve even come up with their own official mobile payment system, called Swish.

Anyways, that was quite a long and arduous journey to just get to me saying that I had to walk a few blocks to even find an ATM (bankomat), so I could get the money (pengar) to pay for my sandwich (smörgås) and coffee (kaffe).

After lunch, it was a bit more walking and a little bit of shopping at Dressman.

The thing about winter in the higher latitudes is that it gets dark a lot earlier than one would think. So, for example, above the 58th parallel, here, the sun set at 17:04 today.

One thing that I definitively like about the Nordics is that people are generally nice to the animals here and, at worst, they act like animals are pretty pedestrian.

Now that I’ve written an entirely unnecessary diatribe, I suppose that I should mention that I found quite a substantial congregation of ducks whilst on my way back to the hotel.

The ducks seem pretty content/happy in the river area but I’m not sure if they’re so content that they don’t migrate for the winter. Only time will tell.

So, popped by the hotel to drop the stuff off and use the restroom. Then, it was off to walking again.

Then, I popped over to the Rose Garden (buffet restaurant) for a bit of a lacklustre dinner. Buffets: You go for volume (and subsequent regret), not for quality.

So, you’ll never guess what happened next. Survey says… More walking.

It’s only around, local time, so I’m going to haul my bloated carcass to bed, try to watch some comedies, and hopefully be in a much better disposition tomorrow.

As Beat says in the Truman show, “…In case I don’t see you: Good morning, good afternoon, good evening, and good night.”