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.”


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.


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.”

Windows PowerShell: Discovering and Resolving Neighbours in Your Network

Have you ever wanted to find out which computers are on your local network, what their IP addresses are (if you’re using DHCP), and what their hostnames are? Well, I’ve written a PowerShell script to do just that!

You can find it on GitHub, here.

Essentially, the script does one of two things.

If the Prefix parameter is supplied, it attempts to find all hosts in the last octet range (0-255) that are up (e.g.: that respond to pings) and then uses DNS to attempt to resolve the IP address to a known hostname. This can be especially useful for things like trying to find your Plex server, if your router has restarted and you don’t have a static IP address assigned for it.

If the Prefix parameter is not supplied, we attempt to obtain the first IP address available to the system (indexing by zero from the array) and use that range (e.g.: 192.168.0.x) to find the local hosts that are up (e.g.: responding to pings) and attempt to resolve their names in DNS.

The script takes some time to process the entire range and that’s because I didn’t want to deal with trying to add to a collection in a thread-safe manner due to parallelisation in PowerShell. It would be easy enough to do in C# and, if there’s a lot of interest in that, I could devote some time to writing this to be a dynamic-link library, instead.

For now, I hope it does someone some good, at the very least. 🙂

Onsdag den 31 Oktober 2018

So, there’s not a whole lot to write about today. I did some walking (surprise, surprise).

During my walk, I found that Hedvigs Kyrka (also called Tyska [pronounced: tee-skah] Kyrka because it’s in Tyska Torget) was open, so I popped in for a quick bit.

After that, it was a bit more walking around but there’s only so much walking one can do aimlessly, yeah?

So, instead, it was off to the Stadsbibliotek of Norrköping. Stadsbibliotek is a compound (much like words are compounded in German) of city stad [pronounced: stah’d] and library bibliotek [pronounced: bib-lee-oh-tek].

The library has all of the amenities you can think of and even has what my roommate would probably appreciate being available for check-out: audio books.

After that, it was a stop over at the movie theatre to see what was on.

This is the poster for the last movie I saw (multiple times) when I was in Sweden, Den Blomstertid Nu Kommer (the literal translation from Swedish would be “The Time for Blooming Comes Now” or “The Blooming Time is Now Coming”, depending on context). The movie’s no longer in the theatres but this particular cinema is under renovations. (I think I’ll ask them tomorrow if I can have the poster.)

What did I see? Well, I saw the latest (film) instalment of the Millennium Series, The Girl in the Spider’s Web. It was decent and stayed true to the book, somewhat, but I kind of wish they had stuck with the original cast. The movie wasn’t bad, just different. Maybe I’m just too old and contankerous to appreciate change, anymore.

That being said, I imagine that – depending on how well the movie does in the theatres – they’ll be working on making the latest book into a movie and I will be seeing it. So, there is that.

Sorry that this is a bit lacklustre, dear reader. In the words of Walter Cronkite, “That’s the way it is.”

Tillbaka i Östergötland

Flew back into Sverige (pronounced: sv-air-ee-yay), yesterday. I never thought that I would say this but I think I’m getting tired of travelling/flying. On the realsies. As my friend, HomeSlice (only code names from here-on out), used to say, “For real, real, not play, play.

Something you’ll eventually figure out, if you ever go to Stockholm, but I’ll ruin the surprise for you: They have GSM repeaters under-ground, so you can all of that roaming goodness without the need of that pesky thing called the Earth getting in the way. (Pretty sure this is a GSM-band antenna, at least. Can confirm: Your cellphone will work underground.)

Arlanda Express. Do it. From Arlanda airport to Stockholm Central Station in like 20 minutes. Seriously. Do it. It does all the kph’s.

After a few hours’ wait (during which, I hit-up Forex bank to pay the fee for my ID-Kort, ate some Burger King and felt disgusted with myself, and smoked copious amounts of cigarettes), it was off to Norrköping via the train.

I was the only one in train car for the majority of the ride. Yes, you read that correctly: I had the train car to myself. It was simultaneously great and a bit disheartening. It was great because people suck, in general and en masse. It was disheartening because it was like a three hour train ride and I get bored super-easily. I read some of my book, programmed in C#, and surfed the internet to try to fill those hours.

I toss the lack of other people up to it being 21:00 (local time), it was a 1st class coach (which was like €10 more), and it was an older type train, with older type train cars (read:we were in no WiFi country).

Yes, there’s even video. Let’s see if we can get WordPress to play well with it.


If you get a chance to grab a train via SJ in Sweden, I highly recommend the double-decker. Yes. They have one. Yes. It’s just as awesome as you’d think it’d be.

Today, I got up and did the needful, and then went to my appointment for my ID-Kort (Swedish ID Card).

Afterwards, I had to have meatballs for lunch (because Sweden and köttbullar), so I headed over to Tropikhuset and had some lunch.

Afterwards, it was a lot of walking but given how rainy and generally just miserable it’s been, I haven’t been snapping that many photos.

I do have to mention that during my walk I did swing by an old school book store and I think I have officially found heaven – especially at those prices.

So, that’s it for now. Maybe I’ll be more in the photo-taking mood as the week progresses. We’ll see.

Until then, dear reader, as Smokey the Bear says, “Only you can prevent forest fires…”

En Dag i Stockholm Del Två

So, today started off with breakfast in the hotel, which is where the Kalles Caviar photo that finished the last post originated from.

After breakfast, it was a quick shower, realising that I had left almost all of my toiletries at the hotel in Linköping (womp-womp).

First was to go to the Riksdag area, again. The Riksdag, itself, takes up almost half of the island called Helgeandsholmen and the area of the city is called Gamla Stan (literally, the old town).

This is also where the Stockholms Medeltidsmuseum (literally, Stockholm’s Mideival Times Museum) is located.

It’s a museum and it’s free, so of course I went through it! 😊

After that, it was time to get up close and personal with the Riksdag. Apparently, you need to have pre-booked tours; so, guess what I want to do the next go around?

Then, some more walking because why not?

Then, I stumbled upon another church, S:t Jacobs Kyrka. I think that the church is in the Norrmalm area of the city. Yes, it was a bit of a walk.

Just behind S:t Jacobs Kyrka is Kungsträdgården (literally, king’s tree garden), a fairly large park that also hosts an fairly large ice skating arena in winter.

After that, it was time to grab a bite to eat and I figured that it was time to see what all of the fuss about Max was.

Turns out that they’re pretty environmentally conscious and friendly, so I can see what all of the fuss was about.

The fries were worth passing on but the grilled halloumi nacho burger and the cloud berry shake were worth it.

After that, it was to the hotel to pick up my bag and head to Arlanda via the Arlanda Express. A train that goes 180km/h? Yes, please.

Hopped on the plane back to Dublin.

Back in Dublin, the passport control line was brutal. To give you an idea, the plane landed around 19:00. I didn’t get out of passport control until around 20:00.

Fun-filled facts: You have to have your GNIB card and cannot use your phone when talking to GARDAÍ. Either could be a €3000 fine. Not that I forgot my card or used my phone but I overheard the threats (?), so just trying to help you out. The More You Know™️

Now, I’m back in Dublin and I have to go right back to Sweden, soon, so expect a new post before the month is through. 😊

Until then, dear reader, as Mork used say, “Nanu nanu!”

En Dag i Stockholm.

So, a day in Stockholm was between yesterday and today. Well, if you want to hyper literal with it, it was less than a full day but who’s counting ticks, yeah?

Anyway, I got a room with a view at Radisson Blu Waterfront (in the Norrmalm area of Stockholm …or is it really Kungsholmen?). When they say, “with a view”, they aren’t lying.

That church-like tower off to the right is the Stadshuset (literally, house of the city), also known to us in English as city hall. You can tour the Stadshuset and I highly suggest you do so, if you ever get the chance. I, myself, have been twice and it’s a rather lovely building.

Any visit to Stockholm isn’t complete without a visit to Riksdagen.

The Riksdag is where the magic of the Swedish government happens (not to be outdone by knugen, to be sure) and, currently, they’re trying to form a coalition to form a complete government. There’s rumours that Annie Lööf will become the new stasminister, which I hope turn out to be true.

Next up was S:ta Clara kyrka. Unlike the many castles of Europe, I cannot seem to get tired of going into churches. Perhaps, there’s something to them or the fact the overall exposure time to churches is far less because their footprint is much smaller. Who knows…

S:ta Clara kyrka was nice but it was being used at the time that I had popped-in, so I snapped a photo or two and ducked out of there.

I then headed over to Drottninggatan (literally, Queen Street), hoping to go to Dressman before it got too late in the day.

I had duplicitous reasons for going to Dressman. The first was that I was looking for the cashier that had flirted with me in Swedish years before (I know, I know…) and the second was that I was running out of muscle shirts (always layer in cold environments).

After navigating the whole affair, mostly in Swedish, I was off to snag something to eat.

Drottninghof. I can not recommend it enough. Almost every time that I’ve been in Stockholm and had the time to afford a visit to this restaurant, I’ve always gone without fail.

This time, my meal consisted of toast skagen (literally, shrimp toast), regnbågsfilé (literally, rainbow fillet), and the dessert of the day.

After that, it was a bit more walking around before going back to the hotel to sleep and catching my flight today.

Did I mention the view of the hotel room? I’m not trying to show off, more like I’m trying to convince you to treat yourself, if ever you should go.

Finally, if you’ve ever been to Sweden, you’re all too familiar with the Kalles phenomenon. If you haven’t, let me explain: Kalles is a brand of caviar and the caviar, itself, is packaged and sold in tubes. When people talk about it, it’s almost always followed by the word caviar, Kalles Caviar. It’s a thing here, kind of like snus, but the only difference is that I’ve seen people use snus.

So, that’s all there is from a very brief time in Stockholm. I’ll probably tour the city a bit more before my flight today but won’t get a chance to update the blog until late tonight or tomorrow. Better to just assume this is the end of it, at the moment.

Until next time, dear reader, as the Vulcans say, “Live long and prosper.”

En Promenad runt Linköping

So, for Saturday and Sunday, I stuck mainly around the Linköping (pronounced: len-show-ping) area. It’s a decent walk about in autumn (yes, I’m trying to drop “fall” from my vocabulary for any seasonal references) and walking is good for you, or so I hear.

First up was the Trädgårdsföringen park (not to be confused with the park of the same name in Göteborg). I’ve taken plenty of photos of the park in the past. So, to save you from that mundane banality of seeing a panel of photos of it, again, here’s only a few. 🙂

After that, it was necessary to visit Linköpings Domkyrka (pronounced: dum-sheeyir-kah, said very quickly). It’s a beauty of a church and the acoustics of it are astounding, to the say the least.

After the domkyrka, it was a bit more of walking around town, killing time before bed.

The reason why it needed to be an early night for me is because I was off to Stockholm on the morrow. There won’t be anything on Stockholm in the next post.

Until then, dear reader, have a good one and – in the immortal words of Bill S. Preston, Esq. and Ted Theodore Logan, “Be excellent to each other!”