Logo




Subscribe:
RSS 2.0 | Atom 1.0
Categories:

Sign In


[Giagnocavo]Michael::Write()

 Friday, January 28, 2005
Inline x86 ASM in C#

One thing I had done before and decided to try again was inline (embedded? inline isn't the right term exactly) ASM with C#. Remember, the CLR JITs your IL code down to native code when it runs. There's no interpreter or likewise going on -- your C# code is x86 when it runs (on an x86 platform). However, when writing in C#, it's rather hard to get out to x86 directly. Probably the easiest way would be to use Managed C++ and an inline asm section there. But, if you want to keep it all in C# (say, you want something extra hard to decompile), you can achieve that.

[I must note, the more I learn of internals, the more I learn I need to learn more. Thus hopefully, some true expert will read this and give me more insight.]

The most straightforward way that occurred to me was to use a delegate. As far as I know, C# won't issue calli and ldftn IL opcodes for us in any way we can neatly control. There will be ldftn when a delegate is created, but we can't set that value directly. So instead, we'll create a delegate and modify it. Delegates have a private field named “_methodPtr”. This, as far as I can tell, points to the code to be executed by the delegate. It's important that our delegate is accurate regarding the number of parameters, and the return value.

We will store our x86 in a byte array. Then, we'll pin the array, and stick the address of the first element inside the delegate. When we call the delegate, everything will be set.

As far as I can tell, methods in the CLR use the fastcall convention, so the first two parameters will be in EDX and ECX. The return value is expected in EAX. My demo is going to be simple, performing a ROR (ROtate Right) by 1 on the parameter and returning that. 3 lines of ASM.

Compile with /unsafe obviously, else I'd be writing to secure@microsoft.com. I'm not sure how terribly useful this is, but it seemed cool to me. At the very minimum, it serves to tell people to STFU when they claim that C# / .NET can't do pointers, or raw code, or whatever.

using System;
using System.Reflection;

class Program
{
    public delegate uint Ret1ArgDelegate(uint arg1);
    static uint PlaceHolder1(uint arg1) { return 0; }
    
    public static byte[] asmBytes = new byte[]
        {        
0x89,0xD0, // MOV EAX,EDX
0xD1,0xC8, // ROR EAX,1
0xC3       // RET
        };
        
    unsafe static void Main(string[] args)
    {
        fixed(byte* startAddress = &asmBytes[0]) // Take the address of our x86 code
        {
            // Get the FieldInfo for "_methodPtr"
            Type delType = typeof(Delegate);
            FieldInfo _methodPtr = delType.GetField("_methodPtr", BindingFlags.NonPublic | BindingFlags.Instance);

            // Set our delegate to our x86 code
            Ret1ArgDelegate del = new Ret1ArgDelegate(PlaceHolder1);
            _methodPtr.SetValue(del, (IntPtr)startAddress);

            // Enjoy
            uint n = (uint)0xFFFFFFFC;
            n = del(n);
            Console.WriteLine("{0:x}", n);
        }
    }
}

Code | IL
Friday, January 28, 2005 7:15:12 PM UTC  #    Comments [10]  |  Trackback

 Monday, January 24, 2005
Easy Gnome/X desktop integration with Windows

When I started working with Linux for my current projects, it was on a severly underpowered box (a Celeron 400MHz, 128MB RAM, 3GB HDD). Thus, running Gnome and so on, in addition to my development projects, wasn't a really good idea.

After a bit, I got tired of waiting forever to compile, so I got a 2.something GHz Pentium 4, 512MB of RAM, nice disks, etc. Since I was going to do a bit more than I had done before, I decided to install and use Gnome, as well as RedHat's cute little GUI tools to configure stuff.

Soon, I was using X/Gnome a good portion of my time (X-Chat seems to be the best free IRC client on any platform, and I use IRC for work on Asterisk a lot). Also, it can be nicer to use Gnome than have a bunch of SSH sessions open at once. So, at first, I tried out VNC. I didn't like it. I wanted to get a logon screen, and I was having trouble getting VNC to do that. Also, the RealVNC client I had for Windows seemed pretty crappy.

Then I discovered GDM and XDMCP. Now I have integration like this:



Here are the steps to get XDMCP/GDM working rather nicely with Windows (at least on RedHat systems):

1. Edit /etc/X11/gdm/gdm.conf. In the [xdmcp] section, set Enable=true. That'll allow you to connect remotely using xwin or other XDMCP clients. Next, in the [daemon] section, set KillInitClients=false. This allows xwin's clipboard integration to work correctly.

2. Next, install cygwin, ensuring to install XWin. This has the tools we need to make the connection.

3. Create a shell file inside cygwin to start xwin. I called mine “startsungx“ (sung is my Linux machine's name). Here's my file:
    xwin -query sung -notrayicon -clipboard -rootless -nowinkill -keyhook -xkbmodel microsoft

Do xwin -? to find out about those options. The interesting ones are -rootless, which prevents a “root“ window from appearing (which will manifest itself as an ugly background).
-nowinkill stops the Windows Alt-F4 from killing xwin.
-keyhook allows you to use Alt-Tab and the Menu key inside the session.
-xkbmodel microsoft allows you to use a nice big Microsoft keyboard with all the keys. You can also specify pc101 and similar.

With that, everything should work. But, the downside is that you now have a Cygwin window sitting on your taskbar. Hardly elegant.

4. Create a batch file to start cygwin, and run xwin, while hiding itself. I have a SungX.cmd file:
D:
cd \Linux\cygwin\bin\
cygstart.exe --hide -- bash --login  -i -c /startsungx


That'll start up cygwin, hidden, and run your xwin script. Enjoy!

Now, what I'd REALLY be interested in having is a way to have each application that registers for the Gnome application list panel appear on the Windows taskbar. Or maybe not, as it'd add to the clutter. Either way, I'd like to try it for a bit. If anyone knows, drop me a line.

This post is because of Micah, who had the most classic expression when he saw the Gnome Fedora Core 2 splash screen load up right in the middle of Windows XP. (Yea, I've since moved to RHEL, err, TaoLinux.)

Misc. Technology
Monday, January 24, 2005 7:09:24 PM UTC  #    Comments [1]  |  Trackback

 Sunday, January 16, 2005
My first open source contribution

I ran into an issue with Asterisk, mainly that you can't dynamically control which codec gets accepted. You have to make your choice “up front”, when you define a user/peer. This means, for example, if you want to say “for this call, use the GSM codec”, you can't. You've got to let Asterisk's code work things out, and even it works out on your side, the callee might decide to use a different codec anyways. This means that I end up declaring various peers: peerX-g729, peerX-ulaw, etc., and then have to swap them out when I call Dial.

Even worse, there's no easy way of completely avoiding transcoding when you want to. For instance, I have several phones connected to my server. Some use GSM, some use ULAW, some use G.729. They all use the same dialplan, and ulaw is usually negotiated for the termination. That means my little server gets nailed doing all this transcoding. This is even sillier when you realise that my termination provider has big hardware and will handle transcoding for me. So, without making a seriously complex dialplan, I'm stuck.

Well, IMO, that sucks.

So, I actually dove into the code, and patched it: http://bugs.digium.com/bug_view_page.php?bug_id=0003346 I've yet to see if this will get into the actual codebase. I sure hope so, since I *hate* forking. Indeed, that's one major criticism I have of the “you can just modify it to suit your needs“ claims of OSS. But, the ones in power seem quite rational, so there's some hope... maybe :).

Asterisk is a large project, but thanks to Visual C++ 2005, I could navigate it (New Project From Existing Code is very useful!). Unfortunately, I think there's a bug, as VS takes up 1.4GB of memory when editing this project. However, it's still quite responsive -- except for the Virtual Memory Warning from Windows, and the initial slowness, I'd never notice it was eating all that memory.

Code | Asterisk
Sunday, January 16, 2005 4:03:31 AM UTC  #    Comments [1]  |  Trackback

 Thursday, January 13, 2005
Primer on Encryption in Spanish

MVP Patrick MacKay down in Chile has finally gotten his Spanish primer on encryption up on the MSDN site. Check it out here: Desmitificando la Encriptación (Parte I). Not to boast or to brag, but I drew the little face that's used to show off the cipher modes :).

Security
Thursday, January 13, 2005 5:53:55 PM UTC  #    Comments [0]  |  Trackback

 Wednesday, January 12, 2005
New Horizons Engrish: Bistalk and comerse Server
A while back, we were looking for some training courses on BizTalk and Commerce Server. We emailed the local New Horizons training centre, asking for info. They offered us:

“Bistalk Server, y otra en comerse Server 2000.“

Bistalk? comerse Server? Oh joy. We responded asking for prices, and explaining the correct spelling. Their response:

Dear Mr. XXX
delay of its news, If has left it is possible that it can send its data to me of I telephone to be able to communicate with its person and power to me to have a direct contact but. until soon.

To this day, I'm not quite sure exactly what he meant.
Guatemala | Humour
Wednesday, January 12, 2005 8:20:24 PM UTC  #    Comments [2]  |  Trackback

Convergence Communications: 8% Packet loss is great!

I was configuring my router (my all-purpose Linux machine) to use both of my Internet connections, specifically to route my data and voice over separate connections, so I don't have to deal with QoS issues.

I tested both lines, and noticed the Convergence line seemed to have a bit less latency, so decided to go with that. But, I also noticed that there seemed to be some packet loss, moving around between 3% and 8%. So I phoned Convergence and explained I have a problem. I was asked how fast my downloads were, but told the tech that the issue was there was a lot of packet loss: 5% I said. “And the problem is?” He insisted that 5% is very acceptable and good.

After pushing him for a bit, he says that they have up to 8%, and they consider that to be fine. He went on to explain that cable is just like that. I don't know what these guys are smoking, but this is the stupidest thing I've ever heard. When Convergence bought Cybernet, I think they didn't realise what a horrible infraestructure they had. But it's been years now, plenty of time to fix things.

I'm going to play with the modem and see if I can increase it's power or something that will reduce loss. It's an old 1997 Zenith modem -- anyone know anything else about these kinds of issues?

Guatemala
Wednesday, January 12, 2005 8:14:31 PM UTC  #    Comments [4]  |  Trackback

 Saturday, January 08, 2005
Warning on a phone

You know you're gonna have a fun time trying to figure out configuration settings when the user manual for your phone start off with this:

Congratulations on your purchase of the product. Please read the manual carefully to ensure your phone work in best status.

 Security and Notes:

     Don’t use it in chemical plantgas station or near the exploder place.

I have to say, I was really disheartened when I read that. I was really looking forward to using my phone near the exploder place! I guess I'll have to find some equipment that IS safe to use in the exploder place.

Humour
Saturday, January 08, 2005 1:21:15 AM UTC  #    Comments [4]  |  Trackback

 Thursday, December 30, 2004
Newest spyware and popups brought to you by Windows Media

It appears as if Microsoft's Windows Media DRM protection sucks in yet another way. Some evil people are using Windows Media files to open popups, which then try to confuse users into installing spyware and so on. I can imagine that perhaps this is even by design (when you try play protected media, it wants to send you to a website so you can purchase a license).

Some companies are now trying to trick users into downloading these files, and then take advantage of the extra confusion since the Windows open from WMP (”What the... I have to click this? Huh? Must be related to this new Windows Media Player...”).

While this “hole“ isn't *that bad*, since, AFAIK, all it does is fire up a browser (ok, that can be pretty risky, depending on the circumstance, and perhaps it can easily be used to escalate?), why is this even happening in the first place?

  1: Microsoft builds DRM into it's media system, even though no users are asking for it.
  2: Microsoft then turns ON these features by default -- features that connect to arbitrary sites without the user doing any action remotely related to Internet access.
  3: User gets burned, and some crafty devil-developers are happy.

How is this good? If MS would just wake the hell up and do what's right, instead of continuing to cater to media executives, we'd all be a lot better off.

Security
Thursday, December 30, 2004 10:55:54 PM UTC  #    Comments [0]  |  Trackback

Fedora Core 2 Input Methods - What a joke

I use a Fedora Core 2 machine for a lot of my development work (well, mainly compiling and running, since I develop, when possible, with VS 2005). I've found the desktop to be generally usable, if perhaps a bit unstable (I'd say Gnome on FC2 hangs just as much as IE does on XP, which is pretty often).

Sometimes I use IRC. I've realised that mIRC *really sucks*. Especially when I try to get it working with Korean input. Pretty much everything makes it hang (full CPU usage). Apart from that, it's just not that nice. However, mIRC combined with AppLocale is the only IRC client I've been able to work with Hangeul input and display.

At any rate, I've been using X-Chat for a while on my FC2 machine. It seems far better. Today I wanted to go into a Korean chat room. Hmm, shouldn't be hard right? Somewhere I should be able to click something and get a Korean IME... right?

So I searched. And asked. And read lists. And downloaded and installed a lot of RPMs. And I'm still no closer to getting any CJK support at all. Apparently whoever develops this stuff didn't think that 'foreign' language input should be that easy. The closest I came to getting any decent info was some Japanese guy basically saying that the Gnome/FC2 people are dumbasses for not getting this working right and easy.

Maybe it's just me. Maybe I just really don't know how to use computers and figure things out. At any rate, it's just nice to see such solid reminders of why MS shouldn't give a damn about “Linux on the desktop” coming to steal their users away.

For what it's worth, getting pretty much ANY input method installed on Windows XP is this simple: Start -> Control Panel -> Regional and Language Options -> Details -> Add. That's it. Maybe you'll have to insert the CD and reboot. After this, you'll get the Language Bar, and can flip between IMEs till your heart's content. Considering this isn't anything so revolutionary or new, but a simple, “boring“ core functionality item, you'd think that the desktop linux people would have it down solid by now eh?

Korean | Misc. Technology
Thursday, December 30, 2004 12:09:02 PM UTC  #    Comments [0]  |  Trackback

Grinding halt: VS 2005 + Mono + ASP.NET

Well, I guess my cross-platform development bliss had to come to an end sooner or later, right? I started work on a new app for Asterisk, and found that ASP.NET would come in handy.

Visual Studio 2003 requires IIS to work with web projects. Maybe I can trick it into using XSP, but I'm really, very, happy with VS 2005, and I don't want to go back. So, what are the problems with 2005? ASP.NET's new drug-induced compilation model.

Before, I could build my app with codebehind, compile, and go on my merry way. The DLLs are loaded at runtime, things are good, and most importantly, they work with Mono/XSP. Now, I've got several problems. First, it doesn't seem like the ASP.NET 2 support is in Mono. That's fine, I'll stay away from master pages (even though it hurts), and other new stuff. My biggest goal is to use VS 2005.

Then comes the real problems: There is no more “compile“ option in VS 2005 for web projects. Nope. Seems like the ASP/VBS and PHP whiners got their way and wanted things more like a scripting language. Some huge advancements were made (no more stupid IIS screwups). But I can no longer work as before. Which means I can't deploy as before. There's a precompilation system, but it's not what I want.

I can't even do it with runtime compilation either, because of this partial class and “compiles with“ nonsense. So it appears as if I'm screwed. Anyone have any suggestions?

Code
Thursday, December 30, 2004 12:30:26 AM UTC  #    Comments [2]  |  Trackback

 Saturday, December 25, 2004
Merry Christmas from Guatemala

Well, I'm heading off to my parents' place, and my in-laws. And of course, what better way to celebrate than with kilos of powder! This year has surpassed every other in terms of aerial payloads. For less than $8, one can buy rockets with about 1kg of gunpowder. Some people have been launching these every day for the past week or so. They set off car alarms blocks away, and the diameter of the burst is probably about 20 metres? I suck at estimating sizes and weights, so maybe it's 50m. Or perhaps 5 cm. At any rate, it's big.

Last year we set someone's roof on fire in our fire-induced bliss. But to be fair, it was their fault since they never clean their roof, and it had lots of dry, dry, pine needles on it.

I bought a “Christmas Basket” for our security guards here. I'm not sure what gift baskets in other countries have, but here it contained this:

 - 1 litre of rum
 - 1 can of “Vienna” hot dogs
 - 1 bag of large marshmellows
 - 1 box of crackers
 - 1 box of brie cheese
 - 1 can of SPAM

I'm not sure what the continuity is here, but they seem to sell quite well.

Anyways, happy times to all, and if I don't blog for a few weeks, it'll be because my brother wasn't joking when he said he wanted to launch a shell horizontally. That, or I was attacked by a drunk with a can of SPAM.

Guatemala | Personal
Saturday, December 25, 2004 2:07:06 AM UTC  #    Comments [1]  |  Trackback

 Wednesday, December 22, 2004
What have I done? Patrick gets cracking

Patrick Mac Kay, a Chilean MVP, gets into IL cracking fun, en español. He says he wasn't sure how to do it before, but after my quick tutorial, had “enhanced” a program to handle more data. What have I done? :)

Security
Wednesday, December 22, 2004 4:22:46 AM UTC  #    Comments [3]  |  Trackback

 Monday, December 13, 2004
First look at MSN Desktop Search (MSN Toolbar Suite)

Microsoft finally has a decent desktop search: http://toolbar.msn.com/desktop/results.aspx?FORM=PCHP

First impression: Why MSN? Why oh why? I really dislike MSN. They insist on sticking their damn butterfly all over the place, and feel the need to add tons of links to useless content I don't want to see (while still no equivalent of Google Groups, as far as I can tell). I don't wanna see a damn butterfly and links to dating inside of Outlook! I hope this just a temporary fix until Windows/Office get their search fixed up. And, the place you'd really expect and hope for integration is not there: Searching IM history. Duh.

Microsoft's using the usual tactic to promote their lame offerings by forcing them along with something you actually want. I won't say it's wrong. It's probably good for business. But I sure as hell hate it. But, I guess that's the price you pay when another division cleans up for someone else.

Oh yea, they ignore guidelines, and put a bloody shortcut on your desktop without permission. I guess they thought that even with having it automatically added everywhere else, you might *still* have problems starting it. Sigh. Even MS can't listen to MS guidelines. Oh wait, this is MSN, nevermind.

The deskbar is a nice idea, but unfortunately, having another band on my desktop really sucks (since it takes the full verticle space, wasting lots of precious taskbar space). And, unfortunately, the hotkey to start search doesn't work if the band is closed. Sucky. 

A workaround is to simply disable the MSN Toolbar (lameness incorporated), Outlook integration, and deskbar. Then, go into your start menu, right click the MSN Desktop Search, and assign a shortcut. Enjoy searching without cluttering up your apps.

Apart from MSN's spam-like tendencies, it's a good solid offering. MSN shows some of it's MS-ness here:

   - Awesome UI. The deskbar is really cool. Not worth the space loss, but almost. The search results go right the program -- no browser nonsense.

  - Network indexing!!! YEA. Now I can search the source on my Linux development machine easily. 

  - Outlook-integrated search (right where I need it).

I'm really happy with it. What I really want is Office and Windows to integrate this into their products, rather than having it be a big MSN orgy.

At any rate, I've already said goodbye to Google Desktop. Yey!

Misc. Technology
Monday, December 13, 2004 6:27:43 PM UTC  #    Comments [3]  |  Trackback

Christmas in Guatemala

Christmas is quite a bit of fun down here. Contrary to what some believe, it does get somewhat cold here, since we're at an elevation of around 2000 metres. However, what makes it *cold* is that the idea of insulation is a foreign concept to most houses. Thus, even though it's only “rather cold“ out, you can feel the coldness right through the house. I've got a little electric heater in my computer room (2 Pentium IVs and four routers aren't enough) to keep my hands from freezing.

Apparently there is a legal issue with selling real trees (”Pinabete” -- Fir or Spruce I'm guessing), some kind of ban. But that doesn't stop people from selling them. Instead, to get around the law, they cut up the tree, and then staple the branches to a piece of wood to get around the law (since they're no longer selling a “tree”). It's done quite well, and besides the fact that they get a bit dry after a while (even so, we had ours up for 4+ months last year), you'd never notice.

Some people are surprised to find that fireworks are used (almost exclusively) during the Christmas season. Christmas Eve, at exactly midnight (well, then it's be Christmas Day) everyone lights off tons of firecrackers and fireworks of all sizes. Then the do the same thing 12 hours later. The amount of firepower you can buy for pennies is quite impressive. Seriously, with a few cents, you can buy something big enough to blow a hole in a block wall. For about a dollar, you can get a pack of whistlers: small (8cm?) hollow plastic tubes filled with gunpowder that scream off as mini-rockets -- or blow up in your hand. Fun for the whole family.

This year, it seems as if a lot more people are buying aerial shells, the kinds you'd expect to see at a “serious” firework display. I've bought them every year I've been here. Playing with that kinda firepower is so much fun, since getting ahold of that stuff in u.s. or Canada is a bit of a challenge (well, if you come from any decent state :P). At any rate, pretty much every night we've been treated to some fantastic aerial display by some neighbours. Some of them are really quite huge, and I've heard more than a few car alarms go off because of the explosions.

With all this commotion, some people might think that Christmas would be quite a bit different, and surely it is. It's certainly a much more festive affair than in other places. However, the fireworks aren't as distracting as they might sound like at first. Indeed, hearing the deep sounds of the shells going off, the whistlers and firecrackers in the streets just reminds you that there's a lot more people around you, celebrating too.

Guatemala
Monday, December 13, 2004 1:33:17 AM UTC  #    Comments [2]  |  Trackback

 Saturday, December 11, 2004
Diversity is not intrinsically a benefit

Sometimes people talk of diversity as if striving for the utmost diversity is somehow going to bring a huge benefit. Somehow, the “higher” the diversity, the “better” things get. Sure, there's obviously some value into having different points of view, different methods, etc. And perhaps, more times than not, valuable information is not discovered because of too closed a point of view. OTOH, extreme diversity is not a boon. It's incompatibility.

Every now and then, I'll read about how Guatemala is so culturally rich because there's 20+ dialects of the Mayan language. I've seen a lot of people say this is a beautiful, positive thing. Yes, some people actually try to justify 20+ mutually intelligible dialects in a small country as a GOOD thing. Of course, most of the times they don't actually know any of the languages.

In fact, it gets taken even further. The government down here pushes “bilingual” education. At first, I thought that was great -- teach the kids Spanish and English so they'll have valuable skills. Nope. Instead, they're teaching math in Mayan. Thus, they'll have a hard time finding better jobs, working with society, etc. In fact, some of the indigenous people in the villages where my parents work think that their kids are being taught this on purpose to keep them back. I.e., they *want* to learn in Spanish (and other popular languages), since they know it'll help them. So, this kind of thinking does indeed limit them from getting ahead. I suppose proponents will take pride in noting that their “culturally rich”. Sigh.

Guatemala
Saturday, December 11, 2004 5:39:28 AM UTC  #    Comments [4]  |  Trackback