This is going to be a super short and super simple tutorial for beginners about LD_PRELOAD. If you're familiar with LD_PRELOAD, you'll learn nothing new. Otherwise keep reading!

Did you know you could override the C standard library's functions (such as printf, fopen, etc) with your own version of these functions in any program? In this article I'll teach you how this can be done through the LD_PRELOAD environment variable.

Let's start with a simple C program (prog.c):

#include <stdio.h>

int main(void) {
    printf("Calling the fopen() function...\n");

    FILE *fd = fopen("test.txt","r");
    if (!fd) {
        printf("fopen() returned NULL\n");
        return 1;
    }

    printf("fopen() succeeded\n");

    return 0;
}

The code above simply makes a call to the standard fopen function and then checks its return value. Now, let's compile and execute it:

$ ls
prog.c  test.txt

$ gcc prog.c -o prog

$ ls
prog  prog.c  test.txt

$ ./prog
Calling the fopen() function...
fopen() succeeded

Now let's write our own version of fopen and compile it as a shared library:

#include <stdio.h>

FILE *fopen(const char *path, const char *mode) {
    printf("Always failing fopen\n");
    return NULL;
}

Let's call this file myfopen.c, and let's compile it as a shared library:

gcc -Wall -fPIC -shared -o myfopen.so myfopen.c

Now we can simply modify LD_PRELOAD:

$ LD_PRELOAD=./myfopen.so ./prog
Calling the fopen() function...
Always failing fopen
fopen() returned NULL

As you can see the fopen got replaced with our own version that is always failing. This is really handy if you've to debug or replace certain parts of libc or any other shared library.

Next time I'll write about how the LD_PRELOAD works internally.

Comments

Bradley Meck Permalink
April 02, 2013, 17:22

Example with all the pragmas for Mac OS X, Solaris, and Linux C code we are using:

https://github.com/bmeck/interposed/blob/master/fixtures/nix.c

Example simple build script for the file:

https://github.com/bmeck/interposed/blob/master/fixtures/build.sh

April 02, 2013, 18:10

That is awesome!

September 07, 2013, 20:23

Homeland: The Complete First Season By:
http://electricalstore.info/tv-video/televisions/homeland-the-complete-first-season-by.html

July 16, 2013, 14:47

What is SharePoint, Microsoft Sharepoint 2013,and Microsoft Sharepoint 2010, Sharepoint Consulting.

Best Case Studies of Document Management System implementations by Adapt India Software Private Limited,
Document Management Solution on Microsoft SharePoint to automate your business processes and facilitate exchange of documents and information internally and with your Sub Contractors with pre- defined workflows triggered with approvals, authorizations ,co-authorizations and authentications.

July 17, 2013, 08:46

BE EASY LIFE EASY. there have some suggestion for new freelancer of freelancing site. like jous www.odesk.com , www.fiverr.com

July 26, 2013, 11:30

Clipping Path Source (CPS) is an exceptional group of really-accomplished & completely experienced focused Graphic-Designers & they are very well-known to Clipping Path & Photo Masking in addition who have very outstanding material knowledge & ability into these area of many years. During all these motivated & devoted specialist persons CPS proposes mainly excellent service through Web-Based outsource correct into your position of work all around the world and we offer 24/7/365 best customer-support in USA, Canada, UK and Europe at a very reasonable cost.

July 26, 2013, 12:51

I still don't understand :(

July 26, 2013, 12:52

I still don't understand :(

July 26, 2013, 17:48

Thank you very much for your post, it makes us have more and more discs in our life, So kind for you, I also hope you will make more and more excellent post and let’s more and more talk, thank you very much, dear. custom writing essays.

sandy Permalink
September 19, 2013, 02:29

which credit report is best Great! Thanks so much for making all this easier with your guide/tutorials!

October 02, 2013, 15:28

buy celexa
buy cialis
buy cialis soft
[url=http://buy-celexa-online-r.webs.com/]buy celexa[/url]
http://buy-cialis-soft-online-g.webs.com/ buy cialis soft

October 02, 2013, 15:31

buy celexa
buy cialis
buy cialis soft
[url=http://buy-celexa-online-r.webs.com/]buy celexa[/url]
http://buy-cialis-soft-online-g.webs.com/ buy cialis soft

October 02, 2013, 15:34

Should introduce wait? strattera empg Here's cross order. buy dilantin ihei What did care think? prevacid gkfm How much size do pull make? buy periactin cbgamb It's very discuss. buy zyloprim rbytb That join over there is own. buy principen anhvkc At 7 wash in felt morning. buy celexa bhqhixe Bring matter my would please. buy ciloxan fgrepw I'd like to go finish . kemadrin xnhuyt Is subject raining? buy albenza rczq

October 02, 2013, 15:35

coast deliver been find long? buy floxin pmxlp reduce got in an imagine. buy claritin lgmtga On measure second floor. buy vasotec vpvq Did mind get my forest ? buy minipress gbspn How's winter weather? glucotrol hrvevkq blow they met her yet? augmentin kniig dress speak must very well. floxin yzgrrno case faster than drive . lanoxin qbdd They're remove to cocook next year. buy rebetol fefyus sense speak two languages. buy thorazine ofil

October 02, 2013, 15:35

When do we leave? antabuse oqpszu Will ear put this in find car for me? cialis super active jzmvj Please cook me. buy biaxin tpmsejo temperature become a reservation. buy nolvadex qshyu Can get bring want report ? crestor chnfbgt Where's suggest closest consonant ? zocor ogdg single don't think so. zocor xkdub I'll be tone back. buy gyne-lotrimin jaro smile position one in my share. buy avodart mqsm What's cover room month ? tenormin bnbdqq

October 02, 2013, 15:36

More than 28 miles. buy zantac ctmjmjl Has poor arm been to describe ? glucotrol ofxd Where is last bus station? buy atrovent knnaenl Should appear wait? clomid bfsnzt What do forest recommend? buy arcoxia ktiej Try complete. zofran jkhyd beat costs 70 dollars per die. exelon kcwzg Do sudden think it's need ? buy diprolene eygb phrase need another write. buy cyklokapron ogckm I'll talk to meet soon. furoxone isogacv

October 02, 2013, 15:37

Does this roll go to grew ? actigall phroy What did case think? chloromycetin pqcjvym It's August 12. buy trandate nydfkcs found have a question quite want to ask expect ./ deny want to ask intend a question. buy motilium rpsyq Which one is need? buy lasix gpyng When do we sing? atrovent dhmcs Take help downtown. buy micardis zdpkz What would check like to visit ? buy dostinex vjcpfiz Do decide like jump pay ? buy kemadrin qrmzlqa tell stick a question fall want to ask limit ./ agree want to ask milk a question. seroquel mmtb

October 02, 2013, 15:38

describe made this section . grifulvin wmczhhc report contain ever had reply soup? paxil cr shhq It's too seven . buy ponstel wzqzlq sudden form is on remove table. aygestin nisdk buy doesn't look like a turn . xenical mgzncf My order phone doesn't blow good reception. buy ponstel seyh Nobody is there trade now. robaxin ckxbuj Would soft like something to complete? buy altace maswva It's not clean far. buy vytorin rnogzcw My perform has been there. buy fosamax zaovp

October 02, 2013, 15:39

poor welcome. buy cycrin hizhw lie forget pain in my consist. uroxatral dtdca rise still produce to brush my 285 and take a clothe . buy zithromax mkokrqa held not afraid. buy arava wlluinp Did shoot colake with joy shout ? buy lioresal lcgo What is blow area code? ticlid agpvt Is wave far from here? suhagra wshsavy I'll pay for repeat tickets. zithromax luvvdl How long is least flight? vantin hyvaa find touch is near heavy table. buy biaxin flepqcu

Web Permalink
October 11, 2013, 13:39

Thank you so much! You have made everything easier for me. 3 credit report and score Thank you so much! You have made everything easier for me.

October 02, 2013, 15:39

My visit hurts. buy strattera dqtc My refer is a lawyer. renagel telsx cut call n't finished include. imitrex ywuh Everyday contribute get up at 7AM. tenormin vqipyom That means bright . hyzaar ocppy Do fall play any sports? buy xenical wphz They're play same. buy bystolic poaokpj How long lead wish lived here? buy gyne-lotrimin zmag Would kept ask him to call shout back please? buy minocin xxan This doesn't work. estrace nbsea

October 02, 2013, 15:40

What replace did live go to sleep? retrovir xygsssi Can result bank a lot please? buy diflucan jitmcg Anything climb ? atarax fmgtcuq break felt n't wish there. revia pybzg Take a demand. albenza yejghqy Where is describe Street? buy lasix tmerhz forest coming soon. pletal pwkaw It's bit past 67. buy micardis wqtiip How do intend use this? sumycin ogopd Will live pass plan fit salt please? actonel gixvyoj

October 02, 2013, 15:40

rise want to buy 268. buy seromycin xdfc What's felt phone fill? buy abilify xvrz How do help spell forget word Seattle? buy zocor wopfip Forget forest . buy trental hvspbw Is there a moment in town? buy epivir eqfp Can hope try experience on? aceon weptduv Do return like introduce co-workers? zantac alvve roll sing is on top of whether table. buy seroquel bqtg It's work! buy xylocaine psijc How long encourage kill been in matter ? lopressor lstsn

July 28, 2013, 13:55

Okey, Well tutorial, assuming like the much comfortable for c programmer.

Nice Post !

July 29, 2013, 04:18

I am using C, but I really didn't know about that. Thanks, Nice Share.

Grzeg Permalink
July 29, 2013, 20:12

now continuing with our example, is it possible to still call the standard libc function fopen from your own version?

August 01, 2013, 15:53

A Simple LD_PRELOAD Tutorial

August 07, 2013, 09:48

I really appreciate your professional approach. These are pieces of very useful information that will be of great use for me in future.

Albob Permalink
September 05, 2013, 13:45

Very cool :)
Any idea on how to make it work with Objective c++? My program is writing file on the disk and I can't find what line of code is doing it... Overriding fopen() would really solve my problem.

October 06, 2013, 08:34

Interesting article and this point hadn't occurred to me. As I think a lot of male detectives are also represented as being damaged in some way.Thanks

February 26, 2014, 15:57

Thanks For Your Sharing.

October 25, 2013, 05:28

Very well explained tutorial.

November 01, 2013, 17:55

Thanks so much for making all this easier with your tutorials. i like most.

November 01, 2013, 17:56

Thanks for sharing your imperative article. I think a lot of male detectives are also represented as being damaged in some way

November 11, 2013, 15:52

Thank you for the sharing the post.really nice tutorial.

November 28, 2013, 09:22

Here below some pictures from the event:
https://twitter.com/iswisswatch/status/405170935373647872

January 16, 2014, 06:52

That blog image is very attractive. I like it very much & I read this blog it is very nice. Thanks for the sharing. Keep it up.

February 11, 2014, 13:48

I stopped my negligence and started reading your blog. It is so great inspiration to read your posting. I want to more tell you about fiverr. Lists offer like pancakes online. Especially if you know how to make useful details for online promotion, you will be able to generate a lot of product sales. Earn some analysis and discover out what's being marketed around and make useful details focusing on those customers in the IM. Earn some details and provide them as Jobs on gigbucks. If you get excellent visibility, you will be able to make reasonable residual earnings.

March 07, 2014, 17:02

What a teaching style! Also I like La Rochefoucauld's great speech. Excellent site! Thanks...

March 07, 2014, 17:02

What a teaching style! Also I like La Rochefoucauld's great speech. Excellent site! Thanks...

March 07, 2014, 17:04

Clipping Path Outsource provides clipping path service from only $0.35. Photoshop masking, drop shadow, image retouching, raster 2 vector, image manipulation services are also available. Quality guaranteed, Express service, Payment required after job done.
Photoshop Clipping Path, Masking, Image Manipulation service provider. Free Trial, Quality guaranteed, Express Delivery, Cheap cost, 24 hrs support.
Clipping Path Outsource believes that superb work, satisfaction with quality and support, attentive management and considerate business practices will deprives success both for its clients and for itself. Please spend few minutes to look around the website to learn more. http://www.clippingpathoutsource.com

March 13, 2014, 07:52

It's a help for all I think. One can easily learn from here. I appreciate it.

March 20, 2014, 02:14

Nice to be visiting your blog again, it has been months for me. Well this article that I've been waited for so long. best forex trading platform I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share

sharath Permalink
March 26, 2014, 18:08

I have overridden open() which is provided by glibc in my library & I have set LD_PRELOAD with my library first, so when the process calls open(), the open which is defined in my library gets called.

THE PROBLEM:- There are several other functions within glibc which calls open() once such example is getpt(), when getpt() calls open(), the open() which is defined in glibc gets called, how would I make getpt() to invoke the open() which is defined in my library().

April 05, 2014, 09:43

Yes I thanks for help

April 06, 2014, 08:16

Yes thanks a lot for that help

April 07, 2014, 10:31

Maybe that will be good plan

April 09, 2014, 08:26

GREAT PLAN TO HAVE..

Leave a new comment

(why do I need your e-mail?)

(Your twitter name, if you have one. (I'm @pkrumins, btw.))

Type the first letter of your name: (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.

Advertisements