cygwin user’s guide...expectations for unix programmers.....8 1.5. expectations for windows...

74
Cygwin User’s Guide DJ Delorie Pierre Humblet Geoffrey Noer

Upload: others

Post on 24-Aug-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Cygwin User’s Guide

DJ Delorie

Pierre Humb let

Geoffre y Noer

Page 2: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Cygwin User’s Guideby DJ Delorie,PierreHumblet,andGeoffrey Noer

Copyright © 1998,1999CygnusSolutions.

RevisionHistory

Revision0.0 1998-10-06Revisedby: [email protected] revisionRevision20.1.01999-02-08Revisedby: [email protected],describeCygwin20.1

Page 3: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Table of Contents1. Cygwin Overview.......................................................................................................7

1.1.Whatis it? .........................................................................................................71.2.Are theCygwin toolsfreesoftware?................................................................71.3.A brief historyof theCygwinproject...............................................................71.4.Expectationsfor UNIX Programmers...............................................................81.5.Expectationsfor WindowsProgrammers..........................................................91.6.Highlightsof Cygwin Functionality.................................................................9

1.6.1.Introduction............................................................................................91.6.2.SupportingbothWindowsNT and9x .................................................101.6.3.PermissionsandSecurity.....................................................................101.6.4.File Access...........................................................................................111.6.5.Text Modevs.BinaryMode................................................................121.6.6.ANSI C Library....................................................................................131.6.7.ProcessCreation...................................................................................131.6.8.Signals..................................................................................................141.6.9.Sockets.................................................................................................151.6.10.Select..................................................................................................15

2. SettingUp Cygwin ...................................................................................................17

2.1.CygwinContents.............................................................................................172.2.Installingthebinaryrelease............................................................................172.3.Installingthesourcecode................................................................................182.4.DirectoryStructure..........................................................................................192.5.EnvironmentVariables....................................................................................212.6.NT securityandthentsec usage...................................................................22

2.6.1.NT security...........................................................................................232.6.2.Processprivileges.................................................................................262.6.3.File permissions...................................................................................262.6.4.New sinceCygwin release1.1.............................................................292.6.5.Themappingleak.................................................................................312.6.6.New aclAPI.........................................................................................32

2.7.Customizingbash............................................................................................33

3

Page 4: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

3. UsingCygwin............................................................................................................36

3.1.Mappingpathnames.......................................................................................363.1.1.Introduction..........................................................................................363.1.2.TheCygwinMount Table....................................................................363.1.3.CygwinMount TableStrategies...........................................................383.1.4.AdditionalPath-relatedInformation....................................................39

3.2.Text andBinarymodes...................................................................................393.2.1.TheIssue..............................................................................................393.2.2.ThedefaultCygwin behavior...............................................................403.2.3.Example...............................................................................................413.2.4.Binaryor text?......................................................................................423.2.5.Programming........................................................................................43

3.3.File permissions..............................................................................................433.4.Specialfilenames............................................................................................44

3.4.1.DOSdevices.........................................................................................443.4.2.POSIXdevices.....................................................................................443.4.3.The.exeextension................................................................................453.4.4.The@pathnames.................................................................................45

3.5.TheCYGWIN environmentvariable..............................................................463.6.CygwinUtilities ..............................................................................................48

3.6.1.cygcheck..............................................................................................483.6.2.cygpath.................................................................................................493.6.3.kill ........................................................................................................503.6.4.mkgroup...............................................................................................523.6.5.mkpasswd.............................................................................................533.6.6.passwd..................................................................................................543.6.7.mount...................................................................................................55

3.6.7.1.Usingmount..............................................................................563.6.7.2.Cygdrivemountpoints..............................................................583.6.7.3.Limitations................................................................................58

3.6.8.ps..........................................................................................................593.6.9.umount.................................................................................................593.6.10.strace..................................................................................................603.6.11.regtool................................................................................................61

4

Page 5: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

4. Programming with Cygwin.....................................................................................63

4.1.UsingGCCwith Cygwin................................................................................634.1.1.ConsoleModeApplications.................................................................634.1.2.GUI ModeApplications.......................................................................63

4.2.DebuggingCygwinPrograms.........................................................................644.3.Building andUsingDLLs...............................................................................66

4.3.1.Building DLLs .....................................................................................674.3.2.Linking AgainstDLLs .........................................................................68

4.4.DefiningWindowsResources.........................................................................68

5

Page 6: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

List of Examples2-1. /etc/passwd..............................................................................................................282-2. /etc/group................................................................................................................283-1.Displayingthecurrentsetof mountpoints.............................................................373-2.POSIX-likemountsetup.........................................................................................383-3. Identitymountsetup...............................................................................................383-4.Using@pathname..................................................................................................463-5.Examplecygpathusage..........................................................................................503-6.Specifyingsignalswith thekill command..............................................................513-7.Settingup thegroupsfile........................................................................................533-8.Settingup thepasswdfile .......................................................................................533-9.Displayingthecurrentsetof mountpoints.............................................................563-10.Addingmountpoints............................................................................................573-11.Changingthedefault prefix..................................................................................584-1.Building Hello World with GCC............................................................................634-2.Compilingwith -g...................................................................................................654-3. "break"in gdb.........................................................................................................654-4.Debuggingwith commandline arguments.............................................................66

6

Page 7: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter 1. Cygwin Overview

1.1. What is it?TheCygwin toolsareportsof thepopularGNU developmenttoolsandutilities forWindowsNT and9x. They functionthroughtheuseof theCygwin library whichprovidestheUNIX systemcallsandenvironmentthattheseprogramsrequire.

With thetoolsinstalled,programmersmaywrite Win32 consoleor GUI applicationsthatmakeuseof thestandardMicrosoft Win32API and/ortheCygwin API. As aresult,it is possibleto easilyport many significantUNIX programswithout theneedfor extensivechangesto thesourcecode.This includesconfiguringandbuilding mostof theavailableGNU software(includingthedevelopmenttoolsincludedwith theCygwin distributions).Evenif thecompilertoolsareof little to nouseto you,youmayhave interestin themany standardUNIX utilities. They canbeusedbothfrom thebashshell(provided)or from thecommand.com.

1.2. Are the Cygwin tools free software?Yes.PartsareGNU software(gcc,gas,ld, etc...),partsarecoveredby thestandardX11license,someof it is publicdomain,someof it waswritten by CygnusandplacedundertheGPL.Noneof it is shareware.You don’t have to payanyoneto useit but youshouldbesureto readthecopyright sectionof theFAQ moremoreinformationonhowtheGNU GeneralPublicLicensemayaffect youruseof thesetools.If you intendtoport aproprietaryapplicationusingtheCygwin library, youmaywanttheCygwinproprietary-uselicense.For moreinformationabouttheproprietary-uselicense,[email protected] thenativeWin32GNUProshouldfeel freetosubmitbug reportsandaskquestionsthroughthenormalchannels.All otherquestionsshouldbesentto theprojectmailing list [email protected].

7

Page 8: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter1. CygwinOverview

1.3. A brief histor y of the Cygwin projectThefirst thing donewasto enhancethedevelopmenttools(gcc,gdb,gas,et al) sothatthey couldgenerate/interpretWin32nativeobjectfiles.

Thenext taskwasto port thetoolsto Win NT/9x. Wecouldhavedonethis by rewritinglargeportionsof thesourceto work within thecontext of theWin32API. But thiswouldhavemeantspendingahugeamountof timeon eachandevery tool. Instead,wetookasubstantiallydifferentapproachby writing asharedlibrary (theCygwin DLL)thataddsthenecessaryUNIX-lik e functionalitymissingfrom theWin32API (fork,spawn, signals,select,sockets,etc.).Wecall thisnew interfacetheCygwinAPI. Oncewritten, it waspossibleto build workingWin32 toolsusingUNIX-hostedcross-compilers,linking againstthis library.

Fromthis point,wepursuedthegoalof producingnative toolscapableof rebuildingthemselvesunderWindows9x andNT (this is oftencalledself-hosting).SinceneitherOSshipswith standardUNIX usertools(fileutils, textutils, bash,etc...),wehadto gettheGNU equivalentsworkingwith theCygwinAPI. Mostof thesetoolswerepreviouslyonly built natively sowehadto modify their configurescriptsto becompatiblewith cross-compilation.Otherthantheconfigurationchanges,very fewsource-level changeshadto bemade.Runningbashwith thedevelopmenttoolsandusertoolsin place,Windows9x andNT look likeaflavor of UNIX from theperspectiveof theGNU configuremechanism.Self hostingwasachievedasof thebeta17.1release.

1.4. Expectations for UNIX Programmer sDeveloperscomingfrom aUNIX backgroundwill find asetof utilities they arealreadycomfortableusing,includingaworkingUNIX shell.ThecompilertoolsarethestandardGNU compilersmostpeoplewill havepreviouslyusedunderUNIX, onlyportedto theWindowshost.Programmerswishingto port UNIX softwareto WindowsNT or 9x will find thattheCygwin library providesaneasyway to portmany UNIXpackages,with only minimal sourcecodechanges.

8

Page 9: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter1. CygwinOverview

1.5. Expectations for Windo ws Programmer sDeveloperscomingfrom aWindowsbackgroundwill find asetof toolscapableofwriting consoleor GUI executablesthatrely on theMicrosoft Win32API. Thelinkeranddlltool utility maybeusedto write WindowsDynamicallyLinkedLibraries(DLLs). Theresourcecompiler"windres"is alsoprovidedwith thenativeWindowsGNUProtools.All toolsmaybeusedfrom theMicrosoft commandline prompt,withfull supportfor normalWindowspathnames.

1.6. Highlights of Cygwin Functionality

1.6.1. Intr oductionWhenabinarylinkedagainstthelibrary is executed,theCygwin DLL is loadedintotheapplication’s text segment.Becausewearetrying to emulateaUNIX kernelwhichneedsaccessto all processesrunningunderit, thefirst Cygwin DLL to runcreatessharedmemoryareasthatotherprocessesusingseparateinstancesof theDLL canaccess.This is usedto keeptrackof openfile descriptorsandassistfork andexec,amongotherpurposes.In additionto thesharedmemoryregions,everyprocessalsohasaper_processstructurethatcontainsinformationsuchasprocessid, userid, signalmasks,andothersimilarprocess-specificinformation.

TheDLL is implementedusingtheWin32API, whichallows it to runon all Win32hosts.BecauseprocessesrununderthestandardWin32subsystem,they canaccessboththeUNIX compatibilitycallsprovidedby Cygwinaswell asany of theWin32APIcalls.Thisgivestheprogrammercompleteflexibility in designingthestructureof theirprogramin termsof theAPIsused.For example,they couldwrite aWin32-specificGUI usingWin32API callson topof aUNIX back-endthatusesCygwin.

Early on in thedevelopmentprocess,wemadetheimportantdesigndecisionthatitwouldnotbenecessaryto strictly adhereto existingUNIX standardslikePOSIX.1if itwasnotpossibleor if it wouldsignificantlydiminishtheusabilityof thetoolson the

9

Page 10: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter1. CygwinOverview

Win32platform.In many cases,anenvironmentvariablecanbesetto overridethedefault behavior andforcestandardscompliance.

1.6.2. Suppor ting both Windo ws NT and 9xWhile Windows95andWindows98aresimilarenoughto eachotherthatwecansafelyignorethedistinctionwhenimplementingCygwin,WindowsNT is anextremelydifferentoperatingsystem.For this reason,whenever theDLL is loaded,thelibrarycheckswhich operatingsystemis activesothatit canactaccordingly.

In somecases,theWin32API is only differentfor historicalreasons.In this situation,thesamebasicfunctionalityis availableunderWindows9x andNT but themethodusedto gainthis functionalitydiffers.A trivial example:in our implementationofuname,thelibrary examinesthesysinfo.dwProcessorTypestructurememberto figureout theprocessortypeunderWindows9x. Thisfield is not supportedin NT, whichhasits own operatingsystem-specificstructuremembercalledsysinfo.wProcessorLevel.

OtherdifferencesbetweenNT and9x aremuchmorefundamentalin nature.Thebestexampleis thatonly NT providesasecuritymodel.

1.6.3. Permissions and SecurityWindowsNT includesasophisticatedsecuritymodelbasedonAccessControlLists(ACLs).AlthoughsomemodernUNIX operatingsystemsincludesupportfor ACLs,Cygwin mapsWin32file ownershipandpermissionsto themorestandard,olderUNIXmodel.Thechmodcall mapsUNIX-style permissionsbackto theWin32equivalents.Becausemany programsexpectto beableto find the/etc/passwdand/etc/groupfiles,weprovideutilities thatcanbeusedto constructthemfrom theuserandgroupinformationprovidedby theoperatingsystem.

UnderWindowsNT, theadministratoris permittedto chown files.Thereis currentlynomechanismto supportthesetuidconceptor API call. Althoughwehopeto supportthisfunctionalityat somepoint in thefuture,in practice,theprogramswehaveportedhavenotneededit.

10

Page 11: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter1. CygwinOverview

UnderWindows9x, thesituationis considerablydifferent.Sinceasecuritymodelisnotprovided,Cygwin fakesfile ownershipby makingall files look like they areownedby adefault userandgroupid. As underNT, file permissionscanstill bedeterminedbyexaminingtheir read/write/executestatus.Ratherthanreturnanunimplementederror,underWindows9x, thechown call succeedsimmediatelywithout actuallyperformingany actionwhatsoever. This is appropriatesinceessentiallyall usersjointly own thefileswhennoconceptof file ownershipexists.

It is importantthatwediscusstheimplicationsof our "kernel"usingsharedmemoryareasto storeinformationaboutCygwin processes.Becausetheseareasarenotyetprotectedin any way, in principlea malicioususercouldmodify themto causeunexpectedbehavior in Cygwin processes.While this is notanew problemunderWindows9x (becauseof thelackof operatingsystemsecurity),it doesconstituteasecurityholeunderWindowsNT. This is becauseoneusercouldaffect theCygwinprogramsrun by anotheruserby changingthesharedmemoryinformationin waysthatthey couldnot in amoretypicalWinNT program.For this reason,it is notappropriateto useCygwin in high-securityapplications.In practice,this will notbeamajorproblemfor mostusesof thelibrary.

1.6.4. File AccessCygwin supportsbothWin32- andPOSIX-stylepaths,usingeitherforwardor backslashesasthedirectorydelimiter. Pathscominginto theDLL aretranslatedfromWin32 to POSIXasneeded.As a result,thelibrary believesthatthefile systemis aPOSIX-compliantone,translatingpathsbackto Win32pathswhenever it callsaWin32API function.UNC pathnames(startingwith two slashes)aresupported.

Thelayoutof this POSIXview of theWindowsfile systemspaceis storedin theWindowsregistry. While theslash(’/’) directorypointsto thesystempartitionbydefault, this is easyto changewith theCygwinmountutility. In additionto selectingtheslashpartition,it allowsmountingarbitraryWin32pathsinto thePOSIXfile systemspace.Many peopleusetheutility to mounteachdrive letterundertheslashpartition(e.g.C:\ to /c, D:\ to /d, etc...).

Thelibrary exportsseveralCygwin-specificfunctionsthatcanbeusedby external

11

Page 12: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter1. CygwinOverview

programsto convertapathor pathlist from Win32to POSIXor viceversa.ShellscriptsandMakefilescannotcall thesefunctionsdirectly. Instead,they cando thesamepathtranslationsby executingthecygpathutility programthatweprovidewith Cygwin.

Win32file systemsarecasepreservingbut caseinsensitive.Cygwindoesnotcurrentlysupportcasedistinctionbecause,in practice,few UNIX programsactuallyrely on it.While wecouldmanglefile namesto supportcasedistinction,this wouldaddunnecessaryoverheadto thelibrary andmake it moredifficult for non-Cygwinapplicationsto accessthosefiles.

Symboliclinks areemulatedby filescontainingamagiccookiefollowedby thepathtowhich thelink points.They aremarkedwith theSystemattributesothatonly fileswiththatattributehave to bereadto determinewhetheror not thefile is asymboliclink.Hardlinks arefully supportedunderWindowsNT on NTFSfile systems.Ona FAT filesystem,thecall falls backto simplycopying thefile, astrategy thatworksin manycases.

Theinodenumberfor afile is calculatedby hashingits full Win32path.Theinodenumbergeneratedby thestatcall alwaysmatchestheonereturnedin d_inoof thedirentstructure.It is worthnotingthatthenumberproducedby this methodis notguaranteedto beunique.However, wehavenot foundthis to bea significantproblembecauseof thelow probabilityof generatinga duplicateinodenumber.

1.6.5. Text Mode vs. Binar y ModeInteroperabilitywith otherWin32programssuchastext editorswascritical to thesuccessof theport of thedevelopmenttools.MostCygnuscustomersupgradingfromtheolderDOS-hostedtoolchainsexpectedthenew Win32-hostedonesto continuetowork with theirold developmentsources.

Unfortunately, UNIX andWin32usedifferentend-of-lineterminatorsin text files.Consequently, carriage-returnnewlineshave to betranslatedon thefly by Cygwin intoasinglenewline whenreadingin text mode.Thecontrol-zcharacteris interpretedasavalid end-of-filecharacterfor asimilar reason.

12

Page 13: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter1. CygwinOverview

Thissolutionaddressesthecompatibilityrequirementat theexpenseof violating thePOSIXstandardthatstatesthattext andbinarymodewill beidentical.Consequently,processesthatattemptto lseekthroughtext filescanno longerrely on thenumberofbytesreadasanaccurateindicatorof positionin thefile. For this reason,theCYGWINenvironmentvariablecanbesetto overridethis behavior.

1.6.6. ANSI C Librar yWechoseto includeCygnus’own existingANSI C library "newlib" aspartof thelibrary, ratherthanwrite all of thelib C andmathcallsfrom scratch.Newlib is aBSD-derivedANSI C library, previouslyonly usedby cross-compilersfor embeddedsystemsdevelopment.

Thereuseof existing freeimplementationsof suchthingsastheglob, regexp, andgetoptlibrariessavedusconsiderableeffort. In addition,CygwinusesDougLea’s freemallocimplementationthatsuccessfullybalancesspeedandcompactness.Thelibraryaccessesthemalloccallsvia anexportedfunctionpointer. Thismakesit possiblefor aCygwin processto provide its own mallocif it sodesires.

1.6.7. Process CreationThefork call in Cygwin is particularlyinterestingbecauseit doesnotmapwell on topof theWin32API. Thismakesit verydifficult to implementcorrectly. Currently, theCygwin fork is anon-copy-on-writeimplementationsimilar to whatwaspresentinearlyflavorsof UNIX.

Thefirst thing thathappenswhenaparentprocessforksa child processis thattheparentinitializesa spacein theCygwinprocesstablefor thechild. It thencreatesasuspendedchild processusingtheWin32 CreateProcesscall. Next, theparentprocesscallssetjmpto save its own context andsetsapointerto this in aCygwin sharedmemoryarea(sharedamongall Cygwin tasks).It thenfills in thechild’s .dataand.bsssectionsby copying from its own addressspaceinto thesuspendedchild’saddressspace.After thechild’saddressspaceis initialized, thechild is run while theparent

13

Page 14: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter1. CygwinOverview

waitson amutex. Thechild discoversit hasbeenforkedandlongjumpsusingthesavedjump buffer. Thechild thensetsthemutex theparentis waitingonandblocksonanothermutex. This is thesignalfor theparentto copy its stackandheapinto thechild,afterwhich it releasesthemutex thechild is waitingonandreturnsfrom thefork call.Finally, thechild wakesfrom blockingon thelastmutex, recreatesanymemory-mappedareaspassedto it via thesharedarea,andreturnsfrom fork itself.

While wehavesomeideasasto how to speedupour fork implementationby reducingthenumberof context switchesbetweentheparentandchild process,fork will almostcertainlyalwaysbeinefficientunderWin32.Fortunately, in mostcircumstancesthespawn family of callsprovidedby Cygwincanbesubstitutedfor a fork/execpair withonly a little effort. Thesecallsmapcleanlyon topof theWin32API. As a result,theyaremuchmoreefficient.Changingthecompiler’sdriverprogramto call spawn insteadof fork wasa trivial changeandincreasedcompilationspeedsby twentyto thirtypercentin our tests.

However, spawn andexecpresenttheirown setof difficulties.Becausethereis no wayto doanactualexecunderWin32,Cygwinhasto inventits own ProcessIDs (PIDs).Asa result,whenaprocessperformsmultipleexeccalls,therewill bemultipleWindowsPIDsassociatedwith asingleCygwinPID. In somecases,stubsof eachof theseWin32processesmaylinger, waiting for theirexec’d Cygwin processto exit.

1.6.8. SignalsWhenaCygwin processstarts,thelibrary startsasecondarythreadfor usein signalhandling.This threadwaitsfor Windowseventsusedto passsignalsto theprocess.Whenaprocessnoticesit hasasignal,it scansits signalbitmaskandhandlesthesignalin theappropriatefashion.

Severalcomplicationsin theimplementationarisefrom thefactthatthesignalhandleroperatesin thesameaddressspaceastheexecutingprogram.Theimmediateconsequenceis thatCygwinsystemfunctionsareinterruptibleunlessspecialcareistakento avoid this.We go to somelengthsto preventthesig_sendfunctionthatsendssignalsfrom beinginterrupted.In thecaseof aprocesssendingasignalto anotherprocess,weplaceamutex aroundsig_sendsuchthatsig_sendwill notbeinterrupted

14

Page 15: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter1. CygwinOverview

until it hascompletelyfinishedsendingthesignal.

In thecaseof aprocesssendingitself asignal,weuseaseparatesemaphore/eventpairinsteadof themutex. sig_sendstartsby resettingtheeventandincrementingthesemaphorethatflagsthesignalhandlerto processthesignal.After thesignalisprocessed,thesignalhandlersignalstheeventthatit is done.Thisprocesskeepsintraprocesssignalssynchronous,asrequiredby POSIX.

Most standardUNIX signalsareprovided.Jobcontrolworksasexpectedin shellsthatsupportit.

1.6.9. SocketsSocket-relatedcallsin Cygwinsimplycall thefunctionsby thesamenamein Winsock,Microsoft’s implementationof Berkeley sockets.Only a few changeswereneededtomatchtheexpectedUNIX semantics- oneof themosttroublesomedifferenceswasthatWinsockmustbeinitializedbeforethefirst socket functionis called.As a result,Cygwin hasto performthis initialization whenappropriate.In orderto supportsocketsacrossfork calls,child processesinitialize Winsockif any inheritedfile descriptoris asocket.

Unfortunately, implicitly loadingDLLs at processstartupis usuallyaslow affair.Becausemany processesdonotusesockets,Cygwin explicitly loadstheWinsockDLLthefirst time it callstheWinsockinitialization routine.ThissinglechangespedupGNU configuretimesby thirty percent.

1.6.10. SelectTheUNIX selectfunctionis anothercall thatdoesnotmapcleanlyon top of theWin32API. Much to ourdismay, wediscoveredthattheWin32selectin Winsockonly workedon sockethandles.Our implementationallowsselectto functionnormallywhengivendifferenttypesof file descriptors(sockets,pipes,handles,anda custom/dev/windowsWindowsmessagespseudo-device).

15

Page 16: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter1. CygwinOverview

Uponentryinto theselectfunction,thefirst operationis to sortthefile descriptorsintothedifferenttypes.Therearethentwo casesto consider. Thesimplecaseis whenatleastonefile descriptoris a typethatis alwaysknown to beready(suchasadiskfile).In thatcase,selectreturnsimmediatelyassoonasit haspolledeachof theothertypesto seeif they areready. Themorecomplex caseinvolveswaiting for socketor pipefiledescriptorsto beready. This is accomplishedby themainthreadsuspendingitself, afterstartingonethreadfor eachtypeof file descriptorpresent.Eachthreadpolls thefiledescriptorsof its respective typewith theappropriateWin32API call. As soonasathreadidentifiesa readydescriptor, thatthreadsignalsthemainthreadto wakeup.Thiscaseis now thesameasthefirst onesinceweknow at leastonedescriptoris ready. Soselectreturns,afterpolling all of thefile descriptorsonelasttime.

16

Page 17: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter 2. Setting Up Cygwin

2.1. Cygwin ContentsThefollowing packagesareincludedin thefull release:

Developmenttools:binutils,bison,byacc,dejagnu,diff, expect,flex, gas,gcc,gdb,itcl,ld, libstdc++,make,patch,tcl, tix, tk

Usertools:ash,bash,bzip2,diff, fileutils, findutils,gawk, grep,gzip, less,m4,sed,shellutils,tar, textutils, time

Theusertoolsreleaseonly containstheusertools.

Full sourcecodeis availablefor thesetools.

2.2. Installing the binar y releaseImportant!Be sureto removeany olderversionsof theCygwin toolsfrom your PATHenvironmentvariablesoyoudonot executethemby mistake.

Connectto oneof theftp serverslistedinhttp://sourceware.cygnus.com/cygwin/mirrors.html andcd to thedirectorycontainingthelatestrelease.

If youwantthedevelopmenttoolsandtheprogramsnecessaryto run theGNUconfiguremechanism,youshoulddownloadthefull binaryreleasecalledfull.exe. Ifyou only careabouttheusertoolslistedabove,downloadusertools.exe instead.

If youhaveanunreliableconnection,downloadtheappropriatebinaryin smallerchunksinstead.For thesplit full installer, getthefiles in the‘full-split’ subdirectory.Oncedownloaded,combinethesplit filesat thecommandpromptby doinga:

C:\Cygnus\>copy /b xaa + xab + xac + ... + xak + xal full.exeC:\Cygnus\>del xa*.*

17

Page 18: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

A similar processcanbeusedfor theusertools.

Onceyou have installedtheexecutableon yoursystem,run it. Firstoff, theinstallerwill promptyou for a locationto extractthetemporaryfiles it needsto install thereleaseonyour system.Thedefault shouldbefine for mostpeople.

Next it will askyou to chooseaninstall location.Thedefault issystem-drive:\cygnus\cygwin-b20. Feelfreeto chooseanotherlocationif youwouldprefer.

Finally, it will askyou for thenameof theProgramFilesfolder shortcutto add.Bydefault, theinstallerwill createa ‘Cygwin B20’ entryin a folder called‘CygnusSolutions’.Whenthisstepis completed,it will install thetoolsandexit.

If youshouldeverwantto uninstallthetools,you maydo sovia the"Add/RemovePrograms"controlpanel.

At this pointyou shouldbeableto look underthestartmenuandselect"Cygwin Beta20" (or whateveryounamedit). Thiswill popup abashshellwith specialenvironmentvariablessetup for you. If youarerunningWindows95 or 98 andarefacedwith theerrormessage"Out of environmentspace",you needto increasetheamountofenvironmentspace.Adding theline shell=C:\command.com/e:4096/p to thefileC:\CONFIG.SYS andthenrebootingshoulddo thetrick if C: is your systemdriveletter.

If youwantto install thesourcesfollow theinstructionsin thenext section,elsegodirectly to Section2.4to completeyoursystemsetup.

2.3. Installing the sour ce codeBeforedownloadingthesourcecodecorrespondingto therelease,youshouldinstallthelatestreleaseof thetools(eitherthefull releaseor just theusertools).

Createthedirectorythatwill housethesourcecode.cd there.

Connectto oneof theftp serverslistedaboveandcd to thedirectorycontainingthelatestrelease.

18

Page 19: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

Thesourcecodeis split into two units:usertoolsanddevelopmenttools.If you wanttheusertoolssourcecode,cd into theuser-src-split subdirectory. Downloadthefiles there.If you wantthedevelopmenttoolssources,cd into thedev-src-splitsubdirectory. Downloadthefiles there.

Backin theWindowscommandshell,for theusertoolssource:

C:\Cygnus\> copy /b xba + xbb + xbc + xbd + xbe + xbf + xbg user-src.tar.bz2C:\Cygnus\> del xb*.*C:\Cygnus\> bunzip2 user-src.tar.bz2C:\Cygnus\> tar xvf user-src.tar

For thedevelopmenttoolssource:

C:\Cygnus\> copy /b xca + xcb + xcc + xcd + ... + xck + xcl dev-src.tar.bz2C:\Cygnus\> del xc*.*C:\Cygnus\> bunzip2 dev-src.tar.bz2C:\Cygnus\> tar xvf dev-src.tar

Both will expandinto adirectorycalledsrc.

Note:if you wantthesourcescorrespondingto everythingin thefull.exebinaryinstaller, youwill needto downloadandexpandboththeuser-src.tar.bz2 anddev-src.tar.bz2 sourcearchives!

2.4. Director y StructureCygwin knowshow to emulateastandardUNIX directorystructure,to someextent.This is donethroughtheuseof mounttablesthatmapWin32pathsto POSIXones.Themounttablemaybesetup andmodifiedwith themount command.Thissectionexplainshow to properlyorganizethestructure.

19

Page 20: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

Whenyousetup thesystemyoushoulddecidewhereyouwanttheroot to bemapped.Possiblechoicesaretherootof yourWindowssystem,suchasc: or adirectorysuchasc:\progra~1\root.

Executethefollowing commandsinsidebashasit is difficult to changethepositionoftheroot from theWindowscommandprompt.ChangingthemountpointsmayinvalidatePATH, if this happenssimply exit andrelaunchbash.Createthedirectoryifneeded,thenumount / thecurrentrootandmount it in its new place.You alsohave todecideif youwantto usetext or binarymode.

Next, createthetraditionalmainUNIX directories,with thefollowing command(insomeshellsit is necessaryto issueseparatemkdir commands,eachwith asingleargument).

/$ mkdir /tmp /bin /etc /var /usr

Next wewill initialize thecontentof thesedirectories.

Youshouldmakesurethatyoualwayshaveavalid /tmp directory. If youwantto avoidcreatinga real/tmp, you canusethemount utility to point/tmp to anotherdirectory,suchasc:\tmp, or createasymboliclink /tmp to point to sucha directory.

The/bin directoryshouldcontaintheshellsh.exe. Youhave threechoices.Thefirstis to copy thisprogramfrom theCygnusbin directory. Thesecondis to usemount tomounttheCygnusbin directoryto /bin (theadvantageof this approachis thatyourPATH will beshorterinsidebash).Thethird is to make/bin asymboliclink to theCygnusbin directory.

NotethatCygwin comeswith two shells:bash.exeandsh.exe, which is basedonash.Thesystemis fasterwhenash is usedasthenon-interactiveshell.Theonlyfunctionalitysupportedin ash is thatof thetraditionalsh. In caseof troublewith ashmakesh.exepoint to bash.exe.

Wenow turn to /etc. You maywantto copy in it thetermcap file from theCygnusetc directory, althoughthedefaultsbuilt into theprogramssuffice for thenormalconsole.You mayalsousemount or createassymboliclink to theCygnusetc, just asfor /bin above.

20

Page 21: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

UnderWindowsNT, if you wantto create/etc/passwd and/etc/group (i.e. sothatwhoami worksandls -l replacestheUID with aname)just do this:

/$ cd /etc/etc$ mkpasswd -l > /etc/passwd/etc$ mkgroup -l > /etc/group

Futurechangesto yourNT registry will NOT bereflectedin /etc/passwd or/etc/group afterthis soyoumaywantto regeneratethesefilesperiodically. UnderWindows9x, youcancreateandedit thesefileswith a text editor.

Thewho commandrequiresthe/var/run/utmp to exist. Createit if youwish.Thesystemalsologsinformationin /var/log/wtmp, if it exists.

The/usr directoryis notusedby theCygwinsystembut it is astandardplaceto installoptionalpackages.

You mayalsowantto mountdirectoriessuchas/a and/d to referto your local andnetwork drives.

You donot needto create/dev in orderto setup mountsfor devicessuchas/dev/null asthesearealreadyautomaticallysimulatedinsidetheCygwin library.

2.5. Envir onment Variab lesBeforestartingbash,you mustsetsomeenvironmentvariables,someof whichcanalsobesetor modifiedinsidebash.Cygnusprovidesyouwith a .batfile wherethemostimportantonesaresetbeforebashin launched.This is thesafestway to launchbashinitially. The.batfile is installedby default in \cygnus\cygwin-b20/cygnus.bat

andpointedto in theStartMenu.Youcanedit it to your liking.

TheCYGWIN variableis usedto configuremany globalsettingsfor theCygwinruntimesystem.Initially youcanleaveCYGWIN unsetor setit to tty (e.g.to supportjob controlwith ^Z etc...)usingasyntaxlike this in theDOSshell,beforelaunchingbash.

21

Page 22: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

C:\Cygnus\> set CYGWIN=tty notitle strace=0x1

ThePATH environmentvariableis usedby Cygwin applicationsasa list of directoriesto searchfor executablefiles to run.Thisenvironmentvariableis convertedfromWindows format(e.g.C:\WinNT\system32;C:\WinNT) to UNIX format(e.g.,/WinNT/system32:/WinNT) whenaCygwinprocessfirst starts.Setit sothatitcontainsat leasttheCygnusbin directoryC:\cygnus\cygwin-b20\H-i586-cygwin32\bin beforelaunchingbash.

TheHOME environmentvariableis usedby many programsto determinethelocationof your homedirectoryandwerecommendthatit bedefined.Thisenvironmentvariableis alsoconvertedfrom WindowsformatwhenaCygwinprocessfirst starts.Setit to point to your homedirectorybeforelaunchingbash.

make usesanenvironmentvariableMAKE_MODE to decideif it usescommand.comor /bin/sh to run commandlines.If youaregettingstrangeerrorsfrom makeabout"/c not found",setMAKE_MODE to UNIX at thecommandpromptor in bash.

C:\Cygnus\> set MAKE_MODE=UNIX

/Cygnus$ export MAKE_MODE=UNIX

TheTERM environmentvariablespecifiesyour terminaltype.You cansetit tocygwin.

TheLD_LIBRARY_PATH environmentvariableis usedby theCygwin functiondlopen () asa list of directoriesto searchfor .dll files to load.Thisenvironmentvariableis convertedfrom Windowsformatto UNIX formatwhenaCygwin processfirst starts.Most Cygwinapplicationsdonot makeuseof thedlopen () call anddonotneedthis variable.

2.6. NT security and the ntsec usageThedesigngoalof thentsecpatchwasto getamoreUNIX likepermissionstructurebaseduponthesecurityfeaturesof WindowsNT. To describethechanges,I will givea

22

Page 23: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

shortoverview of NT securityin chapterone.

Chaptertwo discussesthechangesin ntsecrelatedto privilegeson processes.

Chapterthreeshowsthebasicsof UNIX likesettingof file permissions.

Chapterfour talksabouttheadvancedsettingsintroducedin release1.1

Chapterfive illustratesthepermissionmappingleakof WindowsNT.

Chaptersix describesin shortthenew aclAPI sincerelease1.1

Thesettingof UNIX likeobjectpermissionsis controlledby thenew CYGWINvariablesetting(no)ntsec. On NT ntsecis now turnedonby default.

2.6.1. NT securityTheNT securityallowsaprocessto allow or deny accessof differentkind to ‘objects’.‘Objects’ arefiles,processes,threads,semaphores,etc.

Themaindatastructureof NT securityis the‘securitydescriptor’(SD)structure.Itexplainsthepermissions,thataregranted(or denied)to anobjectandcontainsinformation,thatis relatedto socalled‘securityidentifiers’(SID).

A SID is auniqueidentifierfor users,groupsanddomains.SIDsarecomparabletoUNIX UIDs andGIDs,but aremorecomplicatedbecausethey areuniqueacrossnetworks.Example:

SID of asystem‘foo’:

S-1-5-21-165875785-1005667432-441284377

SID of auser‘johndoe’of thesystem‘foo’:

S-1-5-21-165875785-1005667432-441284377-1023

Theaboveexampleshowstheconventionfor printing SIDs.Theleading‘S’ shouldshow thatit is aSID. Thenext numberis aversionnumberwhich is always1. Thenextnumberis thesocalled‘top-level authority’ thatidentifiesthesourcethatissuedtheSID.

23

Page 24: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

While eachsystemin aNT network hasit’ sown SID, thesituationis modifiedin NTdomains:TheSID of thedomaincontrolleris thebaseSID for eachdomainuser. If anNT userhasoneaccountasdomainuserandanotheraccountonhis localmachine,thisaccountsareunderany circumstancesDIFFERENT, regardlessof theusageof thesameusernameandpassword!

SID of adomain‘bar’:

S-1-5-21-186985262-1144665072-740312968

SID of auser‘johndoe’ in thedomain‘bar’:

S-1-5-21-186985262-1144665072-740312968-1207

Thelastpartof theSID, thesocalled‘relative identifier’ (RID), is by default usedasUID and/orGID undercygwin. As thenameandtheaboveexampleimplies,this id isuniqueonly relative to onesystemor domain.

Note,thatit’ spossible,thatanuserhasthesameRID on two differentsystems.TheresultingSIDsareneverthelessdifferent,sotheSIDsarerepresentingdifferentusersinanNT network.

Thereis abig differencebetweenUNIX IDs andNT SIDs,theexistenceof thesocalled‘well known groups’.For exampleUNIX hasnoGID for thegroupof ‘all users’.NT hasanSID for them,called‘Everyone’in theEnglishversions.TheSIDsofwell-known groupsarenotuniqueacrossanNT network but theirmeaningsareunmistakable.Examplesof well-known groups:

everyone S-1-1-0creator/owner S-1-3-0batch process (via ‘at’) S-1-5-3authenticated users S-1-5-11system S-1-5-18

Thelastimportantgroupof SIDsarethe‘predefinedgroups’.Thisgroupsareusedmainly onsystemsoutsideof domainsto simplify theadministrationof userpermissions.ThecorrespondingSIDsarenot uniqueacrossthenetwork sothey areinterpretedonly locally:

24

Page 25: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

administrators S-1-5-32-544users S-1-5-32-545guests S-1-5-32-546...

Now, how arepermissionsgivento objects?A processmayassignanSDto theobject.TheSDof anobjectconsistsof threeparts:

• theSID of theowner• theSID of thegroup• a list of SIDswith theirpermissions,called‘accesscontrollist’ (ACL)

UNIX is ableto createthreedifferentpermissions,thepermissionsfor theowner, forthegroupandfor theworld. In contrasttheACL hasapotentiallyinfinite numberofmembers.Everymemberis asocalled‘accesscontrolelement’(ACE).An ACEcontainsthreeparts:

• thetypeof theACE• permissions,describedwith a DWORD• theSID, for which theabovementionedpermissionsareset

Thetwo importanttypesof ACEsarethe‘accessallowedACE’ andthe‘accessdeniedACE’. Thentsecpatchonly uses‘accessallowedACEs’.

Thepossiblepermissionson objectsaremorecomplicatedthanin UNIX. For example,thepermissionto deleteanobjectis differentfrom thewrite permission.

With theaforementionedmethodNT is ableto grantor revokepermissionsto objectsina far morespecificway. But whataboutcygwin?In aPOSIXenvironmentit wouldbefine to have thesecuritybehavior of aPOSIXsystem.TheNT securitymodelisMOSTLY ableto reproducethePOSIXmodel.Thentsecpatchtriesto do this incygwin.

You ask"Mostly? Why mostly???"Becausethere’s a leakin theNT model.I willdescribethatin detail in chapter4.

Thecreationof explicit objectsecurityis abit complicated,sotypically only twosimplevariationsareused:

25

Page 26: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

• default permissions,computedby theoperatingsystem• eachpermissionto everyone

For parametersto functionsthatcreateor opensecurableobjectsanotherdatastructureis used,the‘securityattributes’(SA). ThisstructurecontainsanSDandaflag, thatspecifieswhetherthereturnedhandleto thecreatedor openedobjectis inheritedtochild processesor not.Thispropertyis not importantfor thentsecpatchdescription,soin this documentSDsandSAsaremoreor lessidentical.

2.6.2. Process privileg esAny processstartedundercontrolof cygwin hasasemaphoreattachedto it, thatis usedfor signalingpurposes.Thecreationof this semaphorecanbefoundin sigproc.cc,function‘getsem’.Thefirst parameterto thefunctioncall ‘CreateSemaphore’is anSA.Without ntsecpatchthis SA assignsdefault securityto thesemaphore.Thereis asimpledisadvantage:Only theownerof theprocessmaysendsignalsto it. Or, in otherwords,if theownerof theprocessis notamemberof theadministrators’group,noadministratormaykill theprocess!This is especiallyannoying, if processesarestartedvia servicemanager.

Thentsecpatchnow assignsanSA to theprocesscontrolsemaphore,thathaseachpermissionsetfor theuserof theprocess,for theadministrators’groupandfor‘system’,which is asynonym for theoperatingsystemitself. Thecreationof this SA isdoneby thefunction‘sec_user’,thatcanbefoundin ‘shared.cc’.Eachmemberof theadministrators’groupis now allowedto sendsignalsto any processcreatedin cygwin,regardlessof theprocessowner.

Moreover, eachprocessnow hastheappropriatesecuritysettings,whenit is startedvia‘CreateProcess’.Youwill find this in function‘spawn_guts’in module‘spawn.cc’.Thesecuritysettingsfor startingaprocessin anotherusercontext have to addthesidof thenew user, too. In thecaseof the‘CreateProcessAsUser’call, sec_usercreatesanSAwith anadditionalentryfor thesidof thenew user.

26

Page 27: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

2.6.3. File permissionsIf ntsecis turnedon,file permissionsaresetasin UNIX. An SD is assignedto thefilecontainingtheownerandgroupandACEsfor theowner, thegroupand‘Everyone’.

Thecompletesettingsof UNIX likepermissionscanbefoundin thefile ‘security.cc’.Thetwo functions‘get_nt_attribute’ and‘set_nt_attribute’ arethemaincode.Thereadingandwriting of theSDsis doneby thefunctions‘read_sd’and‘write_sd’.‘write_sd’ usesthefunction‘BackupRead’insteadof thesimplerfunction‘SetFileSecurity’becausethelatteris unableto setownersdifferentfrom thecaller.

If youarecreatingafile ‘foo’ outsideof cygwin, youwill seesomethinglike thefollowing on ls -ln:

If your login is memberof theadministrators’group:

rwxrwxrwx 1 544 513 ... foo

if not:

rwxrwxrwx 1 1000 513 ... foo

NotetheuserandgroupIDs. 544is theUID of theadministrators’group.This is a‘feature’:-P of WinNT. If oneis a memberof theadministrators’group,everyfile,thathehascreatedis ownedby theadministrators’group,insteadby him.

ThesecondexampleshowstheUID of thefirst user, thathasbeencreatedwith NT’stheuseradministrationtool. Theusersandgroupsaresequentiallynumbered,startingwith 1000.Usersandgroupsareusingthesamenumberingscheme,soauserandagroupdon’t sharethesameID.

In bothexamplestheGID 513is of specialinterest.ThisGID is awell known groupwith differentnamingin local systemsanddomains.Outsideof domainsthegroupisnamed’None’ (‘K ein’ in German,‘Aucun’ in French,etc.),in domainsit is named’DomainUsers’.Unfortunately, thegroup‘None’ is nevershown in theuseradmintooloutsideof domains!This is veryconfusingbut it seemsthatthishasno negativinfluences.

27

Page 28: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

To work correctlythentsecpatchdependson reasonedfiles/etc/passwd/ and/etc/group. In cygwin release1.0 thenamesandtheIDs mustcorrespondto theappropriateNT IDs! TheIDs usedin cygwin aretheRID of theNT SID, asmentionedearlier. An SID of e.g.theuser‘corinna’ on my NT workstation:

S-1-5-21-165875785-1005667432-441284377-1000

Notethelastnumber:It’ s theRID 1000,thecygwin’sUID.

Unfortunately, workstationsandserversoutsideof domainsarenotableto setprimarygroups!In thesecases,wherethereis nocorrelationof usersto primarygroups,NTreturns513(None)asprimarygroup,regardlessof themembershipto existing localgroups.

whenusingmkpasswd-l -g onsuchsystems,youhave to changetheprimarygroupbyhandif ‘None’ asprimarygroupis notwhatyou want(andI’m sure,it’ snotwhatyouwant!)

To gethelpin creatingcorrectpasswdandgroupfiles, look at thefollowing examples,thatarepartof my files.With theexceptionof my personaluserentry, all entriesarewell known entries.For abetterunderstanding,thenamesaretranslatedto theequivalentsof theEnglishNT version.

Example 2-1. /etc/passwd

everyone:*:0:0:::system:*:18:18:::administrator::500:544::/home/root:/bin/bashguest:*:501:546:::administrators:*:544:544::/home/root:corinna::1000:547:Corinna Vinschen:/home/corinna:/bin/tcsh

Example 2-2. /etc/group

everyone::0:system::18:none::513:

28

Page 29: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

administrators::544:users::545:guests::546:powerusers::547:

Groupsmaybementionedin thepasswdfile, too.Thishastwo advantages:

• BecauseNT assignsthemto filesasowners,a ls -l is oftenbetterreadable.• Moreover it’ spossibleto assignedthemto filesasownerswith cygwin’schown.

Thegroup‘system’is theaforementionedsynonym for theoperatingsystemitself andis normallytheownerof processes,thatarestartedthroughservicemanager. Thesameis truefor files, thatarecreatedby processes,whicharestartedthroughservicemanager.

2.6.4. New since Cygwin release 1.1In Cygwin release1.1a new techniqueof usingthe/etc/passwd and/etc/group isintroduced.

Both filesmaynow containSIDsof usersandgroups.They aresavedin thelastfield ofpw_gecosin /etc/passwd andin thegr_passwdfield in /etc/group.

Thishasthefollowing advantages:

• ntsecworksbetterin domainenvironments.• Accounts(usersandgroups)maygetanothernamein cygwin thattheirNT account

name.Thenamein /etc/passwd or /etc/group is transparentlyusedby cygwinapplications(eg. chown, chmod, ls):

root::500:513::/home/root:/bin/sh

insteadof

adminstrator::500:513::/home/root:/bin/sh

29

Page 30: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

Caution:If you like to usetheaccountaslogin accountvia telnet etc.you have toremainthenameunchangedor you have to useaspecialversionof login whichwillbepartof therelease1.1soon.

• CygwinUIDs andGIDsarenow notnecessarilytheRID partof theNT SID:

root::0:513:S-1-5-21-54355234-56236534-345635656-500:/home/root:/bin/sh

insteadof

root::500:513::/home/root:/bin/sh

• As in U*X systemsUIDs andGIDs numberingschemenow don’t influenceeachother. Soit’ spossibleto havesameId’s for auserandagroup:

Example2-3. /etc/passwd:

root::0:0:S-1-5-21-54355234-56236534-345635656-500:/home/root:/bin/sh

Example2-4. /etc/group:

root:S-1-5-32-544:0:

Thetoolsmkpasswdandmkgroup createtheneededentriesby default. If you don’twantthatyou canusetheoptions-s or -no-sids. In this casentsecbehaveslike thepreviousversion.

Pleasenotethatthepw_gecosfield in /etc/passwd is definedasacommaseperatedlist. TheSID hasto bethelastfield!

As aforementionedyouareableto usecygwin accountnamesdifferentfrom theNTaccountnames.If youwantto login thru ‘telnet’ or somethingelseyou have to usethespeciallogin. You maythenaddanotherfield to pw_gecoswhichcontainstheNT usernameincludingit’ sdomain.Soyouareableto login aseachdomainuser. Thesyntaxiseasy:Justaddanentryof theform U-ntdomain\ntusernameto thepw_gecosfield. NotethattheSID muststill remainthelastfield in pw_gecos!

30

Page 31: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

the_king::1:1:Elvis Presley,U-STILLHERE\elvis,S-1-5-21-1234-5678-9012-1000:/bin/sh

For a local userjust dropthedomain:

the_king::1:1:Elvis Presley,U-elvis,S-1-5-21-1234-5678-9012-1000:/bin/sh

In eachcasethepasswordof theuseris takenfrom theNT userdatabase,NOT fromthepasswdfile!

2.6.5. The mapping leakNow its time to point out theleakin theNT permissions.Theofficial documentationexplainsin shortthefollowing:

• accessallow ACEsareaccumulatedregardingto thegroupmembershipof thecaller.• Theorderof ACEsis important.Thesystemreadsthemin sequenceuntil eitherany

neededright is deniedor all neededrightsaregranted.LaterACEsarethennot takeninto account.

• ALl accessdeniedACEs_should_precedeany accessallowedACE.

Notethatthelastrule is apreference,nota law. NT will correctlydealwith theACLregardlessof thesequenceorder. Thesecondrule is notmodifiedto gettheACEsin thepreferedorder.

Unfortunatelythesecuritytabof theNT4 exploreris completelyunableto dealwithaccessdeniedACEswhile theexplorerof W2K rearrangestheorderof theACEsbeforeyoucanreadthem.ThankGod,thesortorderremainsunchangedif onepressestheCancelbutton.

You still ask"Whereis theleak?"NT ACLsareunableto reflecteachpossiblecombinationof POSIXpermissions.Example:

rw-r-xrw-

31

Page 32: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

1sttry:

UserAllow: 110GroupAllow: 101OthersAllow: 110

Hmm,becauseof theaccumulationof allow rightstheusermayexecutebecausethegroupmayexecute.

2sttry:

UserDeny: 001GroupAllow: 101OthersAllow: 110

Now theusermayreadandwrite but not execute.Better?No! Unfortunatelythegroupmaywrite now becauseothersmaywrite.

3rd try:

UserDeny: 001GroupDeny: 010GroupAllow: 001OthersAllow: 110

Now thegroupmaynotwrite asintendedbut unfortunatelytheusermaynot writeanymore,too.How shouldthis problembesolved?Accordingto theofficial rulesaUserAllow hasto follow theGroupDeny but it’ seasyto seethatthis canneverbesolvedthatway.

Theonly chance:

UserDeny: 001UserAllow: 010GroupDeny: 010GroupAllow: 001OthersAllow: 110

32

Page 33: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

Again:Thisworksfor both,NT4 andW2K. Only theGUIs aren’t ableto dealwith thatorder.

2.6.6. New acl APIFor dealingwith ACLsCygwin now hastheaclAPI asit’ s implementedin newerversionsof Solaris.Thenew datastructurefor asingleACL entry(ACE in NTterminology)is definedin sys/acl.h as:

typedef struct acl {int a_type; /* entry type */uid_t a_id; /* UID | GID */mode_t a_perm; /* permissions */

} aclent_t;

Thea_permmemberof theaclent_ttypecontainsonly thebits for read,write andexecuteasin thefile mode.If eg. readpermissionis granted,all readbits (S_IRUSR,S_IRGRP, S_IROTH) areset.CLASS_OBJor MASK ACL entriesarenot fullyimplementedyet.

Thenew API callsare

acl(2), facl(2)aclcheck(3),aclsort(3),acltomode(3), aclfrommode(3),acltopbits(3), aclfrompbits(3),acltotext(3), aclfromtext(3)

Like in Solaris,Cygwinhastwo new commandsfor workingwith ACLson thecommandline: getfaclandsetfacl.

Onlinemanpagesfor theaforementionedcommandsandAPI callscanbefoundon eg.http://docs.sun.com

33

Page 34: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

2.7. Customizing bashTo setbashup sothatcut andpastework properly, click on the"Properties"buttonofthewindow, thenon the"Misc" tab. Makesurethat"Quick Edit" is checkedand"FastPasting"isn’t. Thesesettingswill berememberednext timeyou run bashfrom thatshortcut.Similarly youcansettheworkingdirectoryinsidethe"Program"tab. Theentry"%HOME%" is valid.

Your homedirectoryshouldcontainthreeinitializationfiles thatcontrolthebehavior ofbash.They are.profile, .bashrc and.inputrc. Theseinitializationfileswill onlybereadif HOME is definedbeforestartingbash.

.profile (othernamesarealsovalid, seethebashmanpage)containsbashcommands.It is executedwhenbashis startedaslogin shell,e.g.from thecommandbash–login (theprovided.batfile doesnot settheswitch).This is ausefulplacetodefineandexportenvironmentvariablesandbashfunctionsthatwill beusedby bashandtheprogramsinvokedby bash.It is agoodplaceto redefinePATH if needed.Werecommendaddinga ":." to theendof PATH to alsosearchthecurrentworkingdirectory(contraryto DOS,thelocal directoryis not searchedby default).Also toavoid delaysyoushouldeitherunsetMAILCHECK or defineMAILPATH to point toyour existingmail inbox.

.bashrc is similar to .profile but is executedeachtime aninteractivebashshell islaunched.It servesto defineelementsthatarenot inheritedthroughtheenvironment,suchasaliases.If you donotuselogin shells,youmaywantto put thecontentsof.profile asdiscussedabove in this file instead.

shopt -s nocaseglob

will allow bashto globfilenamesin acase-insensitivemanner. Notethat.bashrc isnot calledautomaticallyfor login shells.You cansourceit from .profile.

.inputrc controlshow programsusingthereadlinelibrary (includingbash)behave.Itis loadedautomatically. Thefull detailsarein thereadline.info. Dueto abug in thecurrentreadlineversion,.inputrc cannotcontain\r, evenon text mountedsystems.Considerthefollowing settings:

34

Page 35: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter2. SettingUp Cygwin

# Make Bash 8bit cleanset meta-flag onset convert-meta offset output-meta on# Ignore case while completingset completion-ignore-case on

Thefirst threecommandsallow bashto display8-bit characters,usefulfor languageswith accentedcharacters.Thelastline makesfilenamecompletioncaseinsensitive,which canbeconvenientin aWindowsenvironment.

35

Page 36: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter 3. Using CygwinThischapterexplainssomekey differencesbetweentheCygwinenvironmentandtraditionalUNIX systems.It assumesaworkingknowledgeof standardUNIXcommands.

3.1. Mapping path names

3.1.1. Intr oductionCygwin supportsbothWin32- andPOSIX-stylepaths,wheredirectorydelimitersmaybeeitherforwardor backslashes.UNC pathnames(startingwith two slashesandanetwork name)arealsosupported.

POSIXoperatingsystems(suchasLinux) do nothave theconceptof drive letters.Instead,all absolutepathsbegin with aslash(insteadof adrive lettersuchas"c:") andall file systemsappearassubdirectories(for example,youmightbuy anew diskandmake it bethe/disk2 directory).

Becausemany programswritten to runon UNIX systemsassumetheexistanceof asingleunifiedPOSIXfile systemstructure,CygwinmaintainsaspecialinternalPOSIXview of theWin32file systemthatallows theseprogramsto successfullyrun underWindows.Cygwin usesthis mappingto translatebetweenWin32andPOSIXpathsasnecessary.

3.1.2. The Cygwin Mount TableThemount utility programis usedto to mapWin32drivesandnetwork sharesintoCygwin’s internalPOSIXdirectorytree.This is asimilar conceptto thetypicalUNIXmountprogram.For thosepeoplecomingfrom aWindowsbackground,themountutility is verysimilar to theold DOS join , in thatit makesyourdrive lettersappearas

36

Page 37: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

subdirectoriessomewhereelse.

Themappingis storedin thecurrentuser’sCygwinmounttable in theWindowsregistry sothattheinformationwill beretrievednext time theuserlogsin. Becauseit issometimesdesirableto havesystem-wideaswell asuser-specificmounts,thereis alsoasystem-widemounttablethatall Cygwinusersinherit.Thesystem-widetablemayonly bemodifiedby auserwith theappropriatepriviledges(Administratorpriviledgesin WindowsNT).

Thecurrentuser’s tableis locatedunder"HKEY_CURRENT_USER/Software/CygnusSolutions/Cygwin/mountsv<version>"where<version>is thelatestregistry versionassociatedwith theCygwin library (this versionis not thesameasthereleasenumber).Thesystem-widetableis locatedunderthesamesubkeysunderHKEY_LOCAL_SYSTEM.

By default, thePOSIXroot/ pointsto thesystempartitionbut it canberelocatedtoany directoryin theWindowsfile systemusingthemount command.WheneverCygwin generatesaPOSIXpathfrom aWin32one,it usesthelongestmatchingprefixin themounttable.Thus,if C: is mountedas/c andalsoas/, thenCygwin wouldtranslateC:/foo/bar to /c/foo/bar.

Invokingmount withoutany argumentsdisplaysCygwin’scurrentsetof mountpoints.In thefollowing example,theC drive is thePOSIXrootandD drive is mappedto /d.Notethatin thiscase,theroot mountis asystem-widemountpoint thatis visible to allusersrunningCygwinprograms,whereasthe/d mountis only visible to thecurrentuser.

Example 3-1.Displaying the current setof mount points

c:\cygnus\> mountDevice Directory Type FlagsD: /d user textmodeC: / system textmode

You canalsousethemount commandto addnew mountpoints,andtheumount todeletethem.SeeSection3.6.7andSection3.6.9for moreinformationonhow to usetheseutilities to setupyour CygwinPOSIXfile system.

37

Page 38: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

WheneverCygwincannotuseany of theexistingmountsto convert from a particularWin32pathto aPOSIXone,Cygwinwill automaticallydefault to animaginarymountpoint underthedefault POSIXpath/cygdrive. For example,if CygwinaccessesZ:\foo andtheZ drive is not currentlyin themounttable,thenZ:\ wouldbeautomaticallyconvertedto /cygdrive/Z. Thedefault prefix of /cygdrive maybechanged(seetheSection3.6.7for moreinformation).

It is possibleto assignsomespecialattributesto eachmountpoint.Automaticallymountedpartitionsaredisplayedas"auto"mounts.Mountscanalsobemarkedaseither"textmode"or "binmode"– whethertext filesarereadin thesamemannerasbinaryfilesby default or not (seeSection3.2for moreinformationon text andbinarymodes.

3.1.3. Cygwin Mount Table StrategiesWhich setof mountsis right for agivenCygwinuserdependslargely on how closelyyou wantto simulateaPOSIXenvironment,whetheryou mix WindowsandCygwinprograms,andhow many drive lettersyouareusing.If youwantto beveryPOSIX-like(assuming"CygwinRoot"is thetopdirectoryof yourCygwin distribution),you maywantto do somethinglike this:

Example 3-2.POSIX-lik emount setup

C:\> mount c:\Cygnus\CygwinRoot /C:\> mount c:\ /cC:\> mount d:\ /dC:\> mount e:\ /cdrom

However, if you mix WindowsandCygwin programsa lot, youmight wantto createan"identity" mapping,sothatconversionsbetweenthetwo (seeSection3.6.2)canbeeliminated:

Example 3-3. Identity mount setup

C:\> mount c:\ \

38

Page 39: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

C:\> mount d:\foo /fooC:\> mount d:\bar /barC:\> mount e:\grill /grill

You’d have to repeatthis for all top-level subdirectorieson all drives,but thenyou’dalwayshave thetop-level directoriesavailableasthesamenamesin bothsystems.

3.1.4. Additional Path-related InformationThecygpath programprovidestheability to translatebetweenWin32 andPOSIXpathnamesin shellscripts.SeeSection3.6.2for thedetails.

TheHOME, PATH, andLD_LIBRARY_PATH environmentvariablesareautomaticallyconvertedfrom Win32 formatto POSIXformat(e.g.fromC:\cygnus\cygwin-b20\H-i586-cygwin32\bin to /bin, if therewasamountfrom thatWin32pathto thatPOSIXpath)whenaCygwinprocessfirst starts.

Symboliclinks canalsobeusedto mapWin32pathnamesto POSIX.For example,thecommandln -s //pollux/home/joe/data/data wouldhaveaboutthesameeffectascreatingamountpoint from //pollux/home/joe/data to /data usingmount,exceptthatsymboliclinks cannotsetthedefault file accessmode.Otherdifferencesarethatthemappingis distributedthroughoutthefile systemandproceedsby iterativelywalking thedirectorytreeinsteadof matchingthelongestprefix in a kerneltable.Notethatsymboliclinks will only work on network drivesthatareproperlyconfiguredtosupportthe"system"file attribute.Many donotdo soby default (theUnix Sambaserverdoesnotby default, for example).

3.2. Text and Binar y modes

3.2.1. The Issue

39

Page 40: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

On aUNIX system,whenanapplicationreadsfrom a file it getsexactlywhat’s in thefile on diskandtheconverseis truefor writing. Thesituationis differentin theDOS/Windowsworld whereafile canbeopenedin oneof two modes,binaryor text. Inthebinarymodethesystembehavesexactlyasin UNIX. However in text modetherearemajordifferences:

a.Onwriting in text mode,aNL (\n, ^J) is transformedinto thesequenceCR(\r, ^M)NL.

b. Onreadingin text mode,a CRfollowedby anNL is deletedanda^Z charactersignalstheendof file.

Thiscanwreakhavocwith theseek/fseekcallssincethenumberof bytesactuallyin thefile maydiffer from thatseenby theapplication.

Themodecanbespecifiedexplicitly asexplainedin theProgrammingsectionbelow.In anidealDOS/Windowsworld, all programsusinglinesasrecords(suchasbash,make, sed...) wouldopenfiles (andchangethemodeof their standardinput andoutput)astext. All otherprograms(suchascat, cmp, tr ...) wouldusebinarymode.Inpracticewith Cygwin,programsthatdealexplicitly with objectfilesspecifybinarymode(this is thecaseof od, which is helpful to diagnoseCR problems).Most otherprograms(suchascat, cmp, tr ) usethedefault mode.

3.2.2. The default Cygwin behaviorTheCygwin systemgivesussomeflexibility in decidinghow filesareto beopenedwhenthemodeis not specifiedexplicitly. Therulesareevolving, this sectiongivesthedesigngoals.

a. If thefile appearsto resideon afile systemthatis mounted(i.e. if its pathnamestartswith adirectorydisplayedby mount), thenthedefault is specifiedby themountflag. If thefile is asymboliclink, themodeof thetargetfile systemapplies.

b. If thefile appearsto resideon afile systemthatis not mounted(ascanhappenwhenthepathcontainsadrive letter),thedefault is text.

40

Page 41: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

c. Pipesandnon-filedevicesareopenedin binarymode,exceptif theCYGWINenvironmentvariablecontainsnobinmode.

Warning!In b20.1 of 12/98, a file will be opened in binary mode ifany of the following conditions hold:

1. binary mode is specified in theopen call

2. CYGWIN contains binmode

3. the file resides in a binarymounted partition

4. the file is not a disk file

d. WhenaCygwinprogramis launchedby ashell,its standardinput,outputanderrorarein binarymodeif theCYGWIN variablecontainstty, elsein text mode,exceptif they arepipedor redirected.

Whenredirecting,theCygwin shellsusesrules(a-c).For theseshellstherelevantvalueof CYGWIN is thatat thetime theshellwaslaunchedandnot thatat thetime theprogramis executed.Non-Cygwinshellsalwayspipeandredirectwithbinarymode.With non-Cygwinshellsthecommandscat filename| programand program < filename arenot equivalentwhenfilename is on atext-mountedpartition.

3.2.3. ExampleTo illustratethevariousrules,weprovidescriptsto deleteCRsfrom filesby usingthetr program,whichcanonly write to standardoutput.Thescript

#!/bin/sh# Remove \r from the file given as argumenttr -d ’\r’ < "$1" > "$1".nocr

41

Page 42: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

will notwork on a text mountedsystemsbecausethe\r will bereintroducedonwriting.Howeverscriptssuchas

#!/bin/sh# Remove \r from the file given as argumenttr -d ’\r’ | gzip | gunzip > "$1".nocr

andthe.batfile

REM Remove \r from the file given as argument@echo offtr -d \r < %1 > %1.nocr

work fine. In thefirst case(assumingthepipesarebinary)we rely on gunzip to setitsoutputto binarymode,possiblyoverridingthemodeusedby theshell.In thesecondcasewerely on theDOSshellto redirectin binarymode.

3.2.4. Binar y or text?UNIX programsthathavebeenwritten for maximumportabilitywill know thedifferencebetweentext andbinaryfilesandactappropriatelyunderCygwin.For thoseprograms,thetext modedefault is agoodchoice.Programsincludedin official Cygnusdistributionsshouldwork well in thedefault mode.

Text modemakesit mucheasierto mix filesbetweenCygwinandWindowsprograms,sinceWindowsprogramswill usuallyusetheCRLF format.Unfortunatelyyoumaystill havesomeproblemswith text mode.First,someof theutilities includedwithCygwin donotyet specifybinarymodewhenthey should,e.g.cat will not work withbinaryfiles (inputwill stopat^Z, CRswill beintroducedin theoutput).Second,youwill introduceCRsin text filesyou write, whichcancauseproblemswhenmovingthembackto aUNIX system.

If youaremountinga remotefile systemfrom a UNIX machine,or moving filesbackandforth to aUNIX machine,youmaywantto accessthefiles in binarymode.Thetextfiles foundtherewill normallybein UNIX NL format,andyou wouldwantany files

42

Page 43: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

put thereby Cygwinprogramsto bestoredin a formatunderstoodby UNIX. Be suretoremoveCRsfrom all Makefilesandshellscriptsandmakesurethatyouonly edit thefileswith DOS/Windowseditorsthatcancopewith andpreserveNL terminatedlines.

Notethatyoucandecidethisonadiskby diskbasis(for example,mountinglocaldisksin text modeandnetwork disksin binarymode).Youcanalsopartitionadisk, forexampleby mountingc: in text mode,andc:\home in binarymode.

3.2.5. ProgrammingIn theopen() functioncall, binarymodecanbespecifiedwith theflagO_BINARY andtext modewith O_TEXT. Thesesymbolsaredefinedin fcntl.h.

In thefopen() functioncall, binarymodecanbespecifiedby addingab to themodestring.Thereis nodirectway to specifytext mode.

Themodeof afile canbechangedby thecall setmode(fd,mode) wherefd is a filedescriptor(aninteger)andmode is O_BINARY or O_TEXT. ThefunctionreturnsO_BINARY or O_TEXT dependingon themodebeforethecall, andEOF on error.

3.3. File permissionsOn Windows9x systems,filesarealwaysreadable,andCygwin usesthenativeread-onlymodeto determineif they arewritable.Filesareconsideredto beexecutableif thefilenameendswith .bat,.comor .exe,or if its contentstartswith #!. Consequentlychmod canonly affect the"w" mode,it silently ignoresactionsinvolving theothermodes.Thismeansthat ls -l needsto openandreadfiles. It canthusberelatively slow.

UnderNT, file permissionsdefault to thesamebehavior asWindows9x but thereisoptionalfunctionalityin Cygwin thatcanmakefile systemsbehavemorelikeon UNIXsystems.This is turnedon by addingthe"ntea"optionto theCYGWIN environmentvariable.

43

Page 44: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

Whenthe"ntea"featureis activated,Cygwin will startwith basicpermissionsasdeterminedabove,but canstorePOSIXfile permissionsin NT ExtendedAttributes.This featureworksquitewell onNTFSpartitionsbecausetheattributescanbestoredsensiblyinsidethenormalNTFSfilesystemstructure.However, onaFAT partition,NTstoresextendedattributesin aflat file at therootof thepartitioncalledEA DATA. SF.Thisfile cangrow to extremelylargesizesif youhavea largenumberof fileson thepartitionin question,slowing thesystemto acrawl. In addition,theEA DATA. SF filecanonly bedeletedoutsideof Windowsbecauseof its "in use"status.For thesereasons,theuseof NT ExtendedAttributesis off by default in Cygwin.Finally, notethatspecifying"ntea"in CYGWIN hasno effectunderWindows9x.

UnderNT, thetest"[ -w filename]"is only trueif filenameis writableacrosstheboard,e.g.chmod +w filename.

3.4. Special filenames

3.4.1. DOS devicesWindowsfilenamesinvalid underWindowsarealsoinvalid underCygwin.ThismeansthatbasefilenamessuchasAUX, COM1, LPT1 or PRN (to nameafew) cannotbeusedin aregularCygwinWindowsor POSIXpath,evenwith anextension(prn.txt). Howeverthespecialnamescanbeusedasfilenameextensions(file.aux). You canusethespecialnamesasyou wouldunderDOS,for exampleyou canprint onyour defaultprinterwith thecommandcat filename> PRN (makesureto endwith a FormFeed).

3.4.2. POSIX devicesThereis noneedto createaPOSIX/dev directoryasit is simulatedwithin Cygwinautomatically. It supportsthefollowing devices:/dev/null, /dev/tty and/dev/comX (theserialports).Thesedevicescannotbeseenwith thecommandls /dev

44

Page 45: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

althoughcommandssuchasls /dev/tty work fine.

* FIXME: Are thereotherdevicesunder/dev. Whataboutthefunnyonesmountedbydefault,such as/dev/fd1.

Whatdo they reallydo?

3.4.3. The .exe extensionExecutableprogramfilenamesendwith .exebut the.exeneednot beincludedin thecommand,sothattraditionalUNIX namescanbeused.However, for programsthatendin ".bat" and".com", youcannotomit theextension.

As asideeffect, the ls filenamegivesinformationaboutfilename.exe iffilename.exe existsandfilename doesnot. In thesamesituationthefunctioncallstat("filename",..) givesinformationaboutfilename.exe. Thetwo filescanbedistinguishedby examiningtheir inodes,asdemonstratedbelow.

C:\Cygnus\> ls *a a.exe b.exeC:\Cygnus\> ls -i a a.exe445885548 a 435996602 a.exeC:\Cygnus\> ls -i b b.exe432961010 b 432961010 b.exe

If ashellscriptmyprog andaprogrammyprog.exe coexist in adirectory, theprogramhasprecedenceandis selectedfor executionof myprog.

Thegcccompilerproducesanexecutablenamedfilename.exe whenaskedtoproducefilename. Thisallowsmany makefileswritten for UNIX systemsto workwell underCygwin.

Unfortunately, the install andstrip commandsdodistinguishbetweenfilename andfilename.exe. They fail whenworkingon anon-existingfilename eveniffilename.exe exists,thusbreakingsomemakefiles.Thisproblemcanbesolvedbywriting install andstrip shellscriptsto provide theextension".exe" whenneeded.

45

Page 46: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

3.4.4. The @pathnamesTo circumventthelimitationson shell line lengthin thenativeWindowscommandshells,Cygwinprogramsexpandtheirargumentsstartingwith "@" in aspecialway. Ifafile pathname exists,theargument@pathname expandsrecursively to thecontentofpathname. Doublequotescanbeusedinsidethefile to delimit stringscontainingblankspace.Embeddeddoublequotesmustberepeated.In thefollowing examplecomparethebehaviorsof thebashbuilt-in echoandof theprogram/bin/echo.

Example 3-4. Using @pathname

/Cygnus$ echo ’This is "a long" line’ > mylist/Cygnus$ echo @mylist@mylist/Cygnus$ /bin/echo @mylistThis is a long line/Cygnus$ rm mylist/Cygnus$ /bin/echo @mylist@mylist

3.5. The CYGWIN envir onment variab leTheCYGWIN environmentvariableis usedto configuremany globalsettingsfor theCygwin runtimesystem.It containstheoptionslistedbelow, separatedby blankcharacters.Many optionscanbeturnedoff by prefixingwith no .

• (no)binmode- if set,non-disk(e.g.pipeandCOM ports)file opensdefault to binarymode(no CR/LF/Ctrl-Z translations)insteadof text mode.Defaultsto set(binarymode).ThisoptionmustbesetbeforestartingaCygwin shellto haveaneffectonredirection.

46

Page 47: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

Warning!If set in 12/98 b20.1, all files always open in binary mode.

• (no)envcache- If set,environmentvariableconversions(betweenWin32andPOSIX)arecached.Notethatthis is maycauseproblemsif themounttablechanges,asthecacheis not invalidatedandmaycontainvaluesthatdependon thepreviousmounttablecontents.Defaultsto set.

• (no)export - if set,thefinal valuesof thesesettingsarere-exportedto theenvironmentas$CYGWIN again.

• (no)glob- if set,commandline argumentscontainingUNIX-style file wildcardcharacters(brackets,questionmark,asterisk,escapedwith \) areexpandedinto listsof files thatmatchthosewildcards.This is applicableonly to programsrunningfromaDOScommandline prompt.Default is set.

• (no)ntea- if set,usethefull NT ExtendedAttributesto storeUNIX-lik e inodeinformation.Thisoptiononly operatesunderWindowsNT. Defaultsto notset.

Warning!This may create additional large files on non-NTFSpartitions.

• (no)ntsec- if set,usetheNT securitymodelto setUNIX-lik epermissionsonfilesandprocesses.Thefile permissionscanonly beseton NTFSpartitions.FAT andSAMBA doesn’t supporttheNT file security. For moreinformation,readthedocumentationin [ntsec.sgml].

• (no)reset_com- if set,serialportsareresetto 9600-8-N-1with no flow controlwhenused.This is doneat opentimeandwhenhandlesareinherited.Defaultsto set.

• strace=n[:cache][,filename]- configuressystemtracing.Off by default,settingvariousbits in n (abit flag) enablesvarioustypesof systemmessages.Settingn to 1enablesmostmessages.Othervaluescanbefoundin sys/strace.h. The:cache

47

Page 48: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

optionletsyouspecifyhow many linesto cachebeforeflushingtheoutput(example:strace=1:20). Thefilename optionletsyousendthemessagesto afile insteadofthescreen.

• (no)strip_title- if set,stripsthedirectorypartoff thewindow title, if any. Default isnot set.

• (no)title - if set,thetitle barreflectsthenameof theprogramcurrentlyrunning.Default is not set.NotethatunderWin9x thetitle baris alwaysenabledandit isstrippedby default,but this is becauseof thewayWin9x works.In ordernot to strip,specifytitle or title nostrip_title.

• (no)tty- if set,Cygwinenablesextrasupport(i.e., termios)for UNIX-lik e ttys. It isnot compatiblewith someWindowsprograms.Defaultsto notset,in which casethetty is openedin text modewith ^Z asEOF. Notethatthis hasbeenchangedsuchthat^D worksasexpectedinsteadof ^Z, andis settablevia stty. ThisoptionmustbespecifiedbeforestartingaCygwin shellandit cannotbechangedin theshell.

3.6. Cygwin UtilitiesCygwin comeswith anumberof command-lineutilities thatareusedto managetheUNIX emulationportionof theCygwinenvironment.While many of thesereflecttheirUNIX counterparts,eachwaswrittenspecificallyfor Cygwin.

3.6.1. cygc heck

Usage: cygcheck [-s] [-v] [-r] [-h] [program ...]-s = system information-v = verbose output (indented) (for -s or programs)-r = registry search (requires -s)-h = give help about the info

You must at least give either -s or a program name

48

Page 49: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

Thecygcheckprogramis adiagnosticutility thatexaminesyour systemandreportstheinformationthatis significantto theproperoperationof Cygwin programs.It cangiveinformationaboutaspecificprogram(or program)you aretrying to run,generalsysteminformation,or both.If you list oneor moreprogramson thecommandline, itwill diagnosetheruntimeenvironmentof thatprogramor programs.If you specifythe-s option,it will givegeneralsysteminformation.If you specify-s andlist oneormoreprogramson thecommandline, it reportson both.

Thecygcheckprogramshouldbeusedto sendinformationaboutyour systemtoCygnusfor troubleshooting(if your supportrepresentative requestsit). Whenaskedtorun this command,includeall theoptionsplusany commandsyouarehaving troublewith, andsave theoutputsothatyou canmail it to Cygnus,like this:

C:\Cygnus> cygcheck -s -v -r -h > tocygnus.txt

The-v optioncausestheoutputto bemoreverbose.Whatthis meansis thatadditionalinformationwill bereportedwhich is usuallynot interesting,suchastheinternalversionnumbersof DLLs, additionalinformationaboutrecursiveDLL usage,andif afile in onedirectoryin thePATH alsooccursin otherdirectorieson thePATH.

The-r optioncausescygcheckto searchyour registry for informationthatis releventto Cygnusprograms.Theseregistry entriesaretheonesthathave "Cygnus"in thename.If youareparanoidaboutprivacy, you mayremove informationfrom this report,but pleasekeepin mind thatdoingsomakesit harderfor Cygnusto diagnoseyourproblems.

The-h optionprintsadditionalhelpful messagesin thereport,at thebeginningof eachsection.It alsoaddstablecolumnheadings.While this is usefulinformation,it alsoaddssometo thesizeof thereport,soif youwantacompactreportor if youknow whateverythingis already, just leave this out.

3.6.2. cygpath

Usage: cygpath [-p|-path] (-u|-unix)|(-w|-windows) filenamecygpath [-v|-version]

49

Page 50: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

cygpath [-W|-windir|-S|-sysdir]-u|-unix print UNIX form of filename-w|-windows print Windows form of filename-p|-path filename argument is a path-v|-version print program version-W|-windir print windows directory-S|-sysdir print system directory

Thecygpath programis a utility thatconvertsWindowsnativefilenamesto CygwinPOSIX-stylepathnamesandback.It canbeusedwhenaCygwin programneedstopassafile nameto anativeWindowsprogram,or expectsto getafile namefrom anativeWindowsprogram.You mayusethelongor shortoptionnamesinterchangeably,eventhoughonly theshortonesaredescribedhere.

The-u and-w optionsindicatewhetheryou wantaconversionfrom WindowstoUNIX (POSIX)format(-u) or a conversionfrom UNIX (POSIX)to Windowsformat(-w). You mustgiveexactlyoneof these.To giveneitheror bothis anerror.

The-p optionmeansthatyouwantto converta path-stylestringratherthanasinglefilename.For example,thePATH environmentvariableis semicolon-delimitedinWindows,but colon-delimitedin UNIX. By giving -p you areinstructingcygpath toconvertbetweentheseformats.

Example 3-5.Examplecygpath usage

#!/bin/shfor i in ‘echo *.exe | sed ’s/\.exe/cc/’‘do

notepad ‘cygpath -w $i‘done

3.6.3. kill

Usage: kill [-sigN] pid1 [pid2 ...]

50

Page 51: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

Thekill programallowsyou to sendarbitrarysignalsto otherCygwin programs.Theusualpurposeis to enda runningprogramfrom someotherwindow when^C won’twork, but youcanalsosendprogram-specifiedsignalssuchasSIGUSR1to triggeractionswithin theprogram,likeenablingdebuggingor re-openinglog files.Eachprogramdefinesthesignalsthey understand.

Notethatthe"pid" valuesaretheCygwinpids,not theWindowspids.To geta list ofrunningprogramsandtheir Cygwinpids,usetheCygwin psprogram.

To senda specificsignal,usethe-signN option,eitherwith asignalnumberor asignalname(minusthe"SIG" part),like theseexamples:

Example 3-6.Specifyingsignalswith the kill command

$ kill 123$ kill -1 123$ kill -HUP 123

Hereis a list of availablesignals,theirnumbers,andsomecommentaryon them,fromthefile <sys/signal.h>, which shouldbeconsideredtheofficial sourceof thisinformation.

SIGHUP 1 hangupSIGINT 2 interruptSIGQUIT 3 quitSIGILL 4 illegal instruction (not reset when caught)SIGTRAP 5 trace trap (not reset when caught)SIGABRT 6 used by abortSIGEMT 7 EMT instructionSIGFPE 8 floating point exceptionSIGKILL 9 kill (cannot be caught or ignored)SIGBUS 10 bus errorSIGSEGV 11 segmentation violationSIGSYS 12 bad argument to system callSIGPIPE 13 write on a pipe with no one to read itSIGALRM 14 alarm clockSIGTERM 15 software termination signal from kill

51

Page 52: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

SIGURG 16 urgent condition on IO channelSIGSTOP 17 sendable stop signal not from ttySIGTSTP 18 stop signal from ttySIGCONT 19 continue a stopped processSIGCHLD 20 to parent on child stop or exitSIGCLD 20 System V name for SIGCHLDSIGTTIN 21 to readers pgrp upon background tty readSIGTTOU 22 like TTIN for output if (tp->t_local&LTOSTOP)SIGIO 23 input/output possible signalSIGPOLL 23 System V name for SIGIOSIGXCPU 24 exceeded CPU time limitSIGXFSZ 25 exceeded file size limitSIGVTALRM 26 virtual time alarmSIGPROF 27 profiling time alarmSIGWINCH 28 window changedSIGLOST 29 resource lost (eg, record-lock lost)SIGUSR1 30 user defined signal 1SIGUSR2 31 user defined signal 2

3.6.4. mkgr oup

usage: mkgroup <options> [domain]This program prints group information to stdoutOptions:\n");

-l,-local print pseudo group information if there is

no domain-d,-

domain print global group information from the domainspecified (or from the current do-

main if there isno domain specified)

-?,-help print this message

52

Page 53: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

Themkgroup programcanbeusedto helpconfigureyour Windowssystemto bemoreUNIX-lik eby creatinganinitial /etc/group substitute(somecommandsneedthisfile) from your systeminformation.It only worksonNT. To initially setupyourmachine,you’d dosomethinglike this:

Example 3-7.Settingup the groupsfile

$ mkdir /etc$ mkgroup -l > /etc/group

Notethatthis informationis static.If youchangethegroupinformationin your system,you’ll needto regeneratethegroupfile for it to have thenew information.

The-d and-l optionsallow you to specifywheretheinformationcomesfrom, eitherthelocalmachineor thedefault (or given)domain.

3.6.5. mkpass wd

Usage: mkpasswd [options] [domain]This program prints a /etc/passwd file to stdoutOptions are

-l,-local print local accounts-d,-

domain print domain accounts (from current domainif no domain specified

-g,-local-groups print local group information too-?,-help displays this message

This program does only work on Windows NT

Themkpasswdprogramcanbeusedto helpconfigureyourWindowssystemto bemoreUNIX-lik eby creatinganinitial /etc/passwd substitute(somecommandsneedthis file) from your systeminformation.It only worksonNT. To initially setupyourmachine,you’d dosomethinglike this:

53

Page 54: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

Example 3-8.Settingup the passwdfile

$ mkdir /etc$ mkpasswd -l > /etc/passwd

Notethatthis informationis static.If youchangetheuserinformationin yoursystem,you’ll needto regeneratethepasswdfile for it to have thenew information.

The-d and-l optionsallow you to specifywheretheinformationcomesfrom, eitherthelocalmachineor thedefault (or given)domain.

3.6.6. pass wd

Usage passwd [name]passwd [-x max] [-n min] [-i inact] [-L len]passwd {-l|-u|-S} name

-x max set max age of passwords-n min set min age of passwords-i inact disables account after inact days of expiry-L len set min password length-l lock an account-u unlock an account-S show account information

passwdchangespasswordsfor useraccounts.A normalusermayonly changethepassword for theirown account,theadministratorsmaychangethepassword for anyaccount.passwdalsochangesaccountinformation,suchaspassword expiry datesandintervals.

Password changes:Theuseris first promptedfor theirold password, if oneis present.Thispassword is thenencryptedandcomparedagainstthestoredpassword.Theuserhasonly onechanceto enterthecorrectpassword.Theadministratorsarepermittedtobypassthis stepsothatforgottenpasswordsmaybechanged.

54

Page 55: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

Theuseris thenpromptedfor a replacementpassword.passwdwill promptagainandcomparethesecondentryagainstthefirst. Both entriesarerequireto matchin orderforthepassword to bechanged.

After thepasswordhasbeenentered,passwordaginginformationis checkedto seeiftheuseris permittedto changetheir passwordat this time. If not,passwdrefusestochangethepasswordandexits.

Password expiry andlength:Thepasswordaginginformationmaybechangedby theadministratorswith the-x, -n and-i options.The-x optionis usedto setthemaximumnumberof daysapassword remainsvalid. After maxdays,thepassword isrequiredto bechanged.The-n optionis usedto settheminimumnumberof daysbeforeapasswordmaybechanged.Theuserwill notbepermittedto changethepassworduntil mindayshaveelapsed.The-i optionis usedto disableanaccountafterthepasswordhasbeenexpiredfor anumberof days.After auseraccounthashadanexpiredpassword for inact days,theusermayno longersignon to theaccount.Allowedvaluesfor theaboveoptionsare0 to 999.The-L optionsetstheminimumlengthof allowedpasswordsfor users,whichdoesn’t belongto theadministratorsgroup,to len characters.Allowedvaluesfor theminimumpassword lengthare0 to 14.In any of theabovecases,avalueof 0 means‘no restrictions’.

Accountmaintenance:Useraccountsmaybelockedandunlockedwith the-l and-uflags.The-l optiondisablesanaccount.The-u optionre-enablesanaccount.

Theaccountstatusmaybegivenwith the-S option.Thestatusinformationis selfexplanatory.

Limitations:Usersmaynotbeableto changetheir passwordonsomesystems.

3.6.7. mount

Usage mountmount [-bfs] <win32path> <posixpath>mount [-bs] -change-cygdrive-prefix<posixpath>mount -import-old-mounts

55

Page 56: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

-b = text files are equivalent to binary files (newline = \n)-x = files in the mounted directory are automati-

cally given execute permission.-f = force mount, don’t warn about miss-

ing mount point directories-s = add mount point to system-wide registry location-change-automount-

prefix = change path prefix used for automatic mount points-import-old-mounts = copy old registry mount ta-

ble mounts into the current mount areas

When invoked without any arguments, mount displays the cur-rent mount table.

Themount programis usedto mapyourdrivesandsharesontoCygwin’ssimulatedPOSIXdirectorytree,muchlikeasis doneby mountcommandson typicalUNIXsystems.PleaseseeSection3.1.2for moreinformationon theconceptsbehindtheCygwin POSIXfile systemandstrategiesfor usingmounts.

3.6.7.1. Using mount

If you just typemount with noparameters,it will displaythecurrentmounttableforyou.

Example 3-9.Displaying the current setof mount points

c:\cygnus\> mountDevice Directory Type FlagsD: /d user textmodeC: / system textmode

In this example,theC drive is thePOSIXroot andD drive is mappedto /d. Notethatin this case,theroot mountis asystem-widemountpoint thatis visible to all usersrunningCygwin programs,whereasthe/d mountis only visible to thecurrentuser.

56

Page 57: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

Themount utility is alsothemechanismfor addingnew mountsto themounttable.Thefollowing exampledemonstrateshow to mountthedirectoryC:\cygnus\cygwin-b20\H-i586-cygwin32\bin to /bin andthenetworkdirectory\\pollux\home\joe\data to /data. /bin is assumedto alreadyexist.

Example 3-10.Adding mount points

c:\cygnus\> ls /bin /datals: /data: No such file or directoryc:\cygnus\> mount C:\cygnus\cygwin-b20\H-i586-cygwin32\bin /binc:\cygnus\> mount \\pollux\home\joe\data /dataWarning: /data does not exist!c:\cygnus\> mountDevice Directory Type Flags\\pollux\home\joe\data /data user textmodeC:\cygnus\cygwin-b20\H-i586-cygwin32\bin /bin user textmodeD: /d user textmode\\.\tape1: /dev/st1 user textmode\\.\tape0: /dev/st0 user textmode\\.\b: /dev/fd1 user textmode\\.\a: /dev/fd0 user textmodeC: / system textmodec:\cygnus\> ls /bin/sh/bin/sh

Notethatmount wasinvokedfrom theWindowscommandshell in thepreviousexample.In many Unix shells,includingbash,it is legalandconvenientto usetheforward"/" in Win32pathnamessincethe"\" is theshell’sescapecharacter.

The"-s" flag to mount is usedto addamountin thesystem-widemounttableusedbyall Cygwinuserson thesystem,insteadof theuser-specificone.System-widemountsaredisplayedby mount asbeingof the"system"type,asis thecasefor the/ partitionin thelastexample.UnderWindowsNT, only thoseuserswith Administratorpriviledgesarepermittedto modify thesystem-widemounttable.

57

Page 58: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

NotethatagivenPOSIXpathmayonly exist oncein theusertableandoncein theglobal,system-widetable.Attemptsto replacethemountwill fail with abusyerror. The"-f" (force)flagcausestheold mountto besilently replacedwith thenew one.It willalsosilencewarningsaboutthenon-existenceof directoriesat theWin32pathlocation.

The"-b" flag is usedto instructCygwin to treatbinaryandtext files in thesamemannerby default.Binarymodemountsaremarkedas"binmode"in theFlagscolumnofmount output.By default,mountsarein text mode("textmode"in theFlagscolumn).

The"-x" flag is usedto instructCygwin thatthemountedfile is "executable".If the"-x"flag is usedwith adirectorythenall files in thedirectoryareexecutable.Filesendingincertainextensions(.exe,.com,.bat,.cmd)areassumedto beexecutableby default.Fileswhosefirst two charactersbegin with ’#!’ arealsoconsideredto beexecutable.Thisoptionallowsotherfiles to bemarkedasexecutableandavoidstheoverheadofopeningeachfile to checkfor a ’#!’.

3.6.7.2. Cygdrive mount points

WheneverCygwincannotuseany of theexistingmountsto convert from a particularWin32pathto aPOSIXone,Cygwinwill, instead,convert to aPOSIXpathusingadefault mountpoint:/cygdrive. For example,if Cygwin accessesZ:\foo andtheZdrive is not currentlyin themounttable,thenZ:\ will beaccessibleas/cygdrive/Z.Thedefault prefixof /cygdrive maybechangedvia theSection3.6.7command.

Themount utility canbeusedto changethis default automountprefix throughtheuseof the"–change-cygdrive-prefix"flag. In thefollowing example,wewill settheautomountprefix to /:

Example 3-11.Changing the default prefix

c:\cygnus\> mount -change-cygdrive-prefix /

Notethatyou if you setanew prefix in thismanner, youcanspecifythe"-s" flag tomake this thesystem-widedefault prefix.By default, thecygdrive-prefixappliesonlyto thecurrentuser. In thesameway, you canspecifythe"-b" flag suchthatall new

58

Page 59: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

automountedfilesystemsdefault to binarymodefile accesses.

3.6.7.3. Limitations

Limitations:thereis ahard-codedlimit of 30 mountpoints.Also, althoughyoucanmountto pathnamesthatdonotstartwith "/", thereis no way to makeuseof suchmountpoints.

Normally thePOSIXmountpoint in Cygwin is anexistingemptydirectory, asinstandardUNIX. If this is thecase,or if thereis aplace-holderfor themountpoint (suchasafile, a symboliclink pointinganywhere,or anon-emptydirectory),youwill gettheexpectedbehavior. Filespresentin a mountpoint directorybeforethemountbecomeinvisible to Cygwinprograms.

It is sometimesdesirableto mountto a non-existentdirectory, for exampleto avoidclutteringtherootdirectorywith namessuchasa, b, c pointingto disks.Althoughmount will giveyou awarning,mosteverythingwill work properlywhenyou refertothemountpoint explicitly. Somestrangeeffectscanoccurhowever. For exampleifyour currentworkingdirectoryis /dir, say, and/dir/mtpt is amountpoint, thenmtpt will not show up in an ls or echo* commandandfind . will not find mtpt.

3.6.8. ps

Usage ps [-aefl] [-u uid]-f show process uids, ppids-l show process uids, ppids, pgids, winpids-u uid list processes owned by uid-a, -e show processes of all users

Thepsprogramgivesthestatusof all theCygwin processesrunningon thesystem(ps= "processstatus").Dueto thelimitationsof simulatingaPOSIXenvironmentunderWindows,thereis little informationto give.ThePID columnis theprocessID you

59

Page 60: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

needto give to thekill command.TheWINPID columnis theprocessID that’sdisplayedby NT’sTaskManagerprogram.

3.6.9. umount

Usage umount [-s] <posixpath>-s = remove mount point from system-wide registry location

-remove-all-mounts = remove all mounts-remove-auto-mounts = remove all automatically mounted mounts-remove-user-mounts = remove all mounts in the cur-rent user mount registry area, including auto mounts-remove-system-mounts = Remove all mounts in the system-wide mount registry area

Theumount programremovesmountsfrom themounttable.If youspecifyaPOSIXpaththatcorrespondsto acurrentmountpoint,umount will remove it from theuser-specificregistryarea.The-s flagmaybeusedto specifyremoving themountfromthesystem-wideregistry areainstead(Administratorpriviledgesarerequired).

Theumount utility mayalsobeusedto removeall mountsof aparticulartype.Withtheextendedoptionsit is possibleto removeall mounts,all automatically-mountedmounts,all mountsin thecurrentuser’s registry area,or all mountsin thesystem-wideregistry area(with Administratorpriviledges).

SeeSection3.6.7)for moreinformationon themounttable.

3.6.10. strace

Usage strace [-m mask] [-o output-file] [ft] program [args...]

-m mask mask for reporting cygwin events (default 1)-o output-fileoutput file to hold strace events (default stderr)

60

Page 61: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

-f follow forked subprocesses-t convert Win32 error messages to text-s remove mount point from system-wide registry location

Thestraceprogramexecutesaprogram,andoptionallythechildrenof theprogram,reportingany CygwinDLL outputfrom theprogram(s)to file. Thisprogramis mainlyusefulfor debuggingtheCygwinDLL itself. Themaskargumentis ahexadecimalstringsignifyingwhicheventsshouldbereported.Thevalid bits to setareasfollows:

Bit Explanation0x00000001 All strace output is collected0x00000002 Unusual or weird phenomenon0x00000010 System calls0x00000020 argv/envp printout at startup0x00000040 Information useful for DLL debugging0x00000080 Paranoid information0x00000100 Termios debbugging0x00000200 Select() function debugging0x00000400 Window message debugging0x00000800 Signal and process handling0x00001000 Very minimal strace output0x00020000 Malloc calls0x00040000 Thread locking calls

3.6.11. regtool

regtool -h - print this messageregtool [-v] list [key] - list subkeys and valuesregtool [-v] add [key\subkey] - add new subkeyregtool [-v] remove [key] - remove keyregtool [-v|-q] check [key] - exit 0 if key exists, 1 if notregtool [-i|-s|-e|-m] set [key\value] [data ...] - set value

-i=integer -s=string -e=expand-string -m=multi-stringregtool [-v] unset [key\value] - removes value from keyregtool [-q] get [key\value] - prints value to stdout

61

Page 62: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter3. UsingCygwin

-q=quiet, no error msg, just re-turn nonzero exit if key/value missingkeys are like \prefix\key\key\key\value, where prefix is any of:

root HKCR HKEY_CLASSES_ROOTconfig HKCC HKEY_CURRENT_CONFIGuser HKCU HKEY_CURRENT_USERmachine HKLM HKEY_LOCAL_MACHINEusers HKU HKEY_USERS

example: \user\software\Microsoft\Clock\iFormat

Theregtoolprogramallowsshellscriptsto accessandmodify theWindowsregistry.Notethatmodifying theWindowsregistry is dangerous,andcarelessnessherecanresultin anunusablesystem.Becareful.

The-v optionmeans"verbose".For mostcommands,thiscausesadditionalor lengthiermessagesto beprinted.Conversely, the-q optionsupresseserrormessages,soyou canusetheexit statusof theprogramto detectif akey existsor not (for example).

Thelist commandlists thesubkeysandvaluesbelongingto thegivenkey. Theaddcommandaddsanew key. Theremove commandremovesakey. Notethatyou mayneedto removeeverythingin thekey beforeyoumayremove it, but don’t rely on thisstoppingyou from accidentallyremoving toomuch.Thecheck commandcheckstoseeif akey exists(theexit codeof theprogramis zeroif it does,nonzeroif it doesnot).

Theset commandsetsavaluewithin a key. -i meansthevalueis aninteger(DWORD).-s meansthevalueis astring.-e meansit’ sanexpandingstring(itcontainsembeddedenvironmentvariables).-m meansit’ samulti-string(list). If youdon’t specifyoneof these,it triesto guessthetypebasedon thevalueyou give.If itlookslikea number, it’ sa number. If it startswith apercent,it’ sanexpandingstring.Ifyou givemultiplevalues,it’ samulti-string.Else,it’ sa regularstring.

Theunset commandremovesavaluefrom akey. Theget commandgetsthevalueofavalueof akey, andprintsit (andnothingelse)to stdout.Note:if thevaluedoesn’texist, anerrormessageis printedandtheprogramreturnsanon-zeroexit code.If yougive-q, it doesn’t print themessagebut doesreturnthenon-zeroexit code.

62

Page 63: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter 4. Programming with Cygwin

4.1. Using GCC with Cygwin

4.1.1. Console Mode ApplicationsUsegccto compile,just likeunderUNIX. Referto theGCCUser’s Guideforinformationonstandardusageandoptions.Here’s asimpleexample:

Example 4-1.Building Hello World with GCC

C:\cygnus\> gcc hello.c -o hello.exeC:\cygnus\> hello.exeHello, World

C:\cygnus\>

4.1.2. GUI Mode ApplicationsCygwin allowsyou to build programswith full accessto thestandardWindows32-bitAPI, includingtheGUI functionsasdefinedin any Microsoft or off-the-shelfpublication.However, theprocessof building thoseapplicationsis slightly different,asyou’ll beusingtheGNU toolsinsteadof theMicrosoft tools.

For themostpart,your sourceswon’t needto changeat all. However, youshouldremoveall __exportattributesfrom functionsandreplacethemlike this:

int foo (int) __attribute__ ((__dllexport__));

intfoo (int i)

63

Page 64: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter4. Programmingwith Cygwin

For mostcases,youcanjust remove the__exportandleave it at that.For conveniencesake,youmight wantto includethefollowing codesnippetwhencompilingGUIprograms.If youdon’t, you will wantto add"-e _mainCRTStartup"to your link line inyour Makefile.

#ifdef __CYGWIN__WinMainCRTStartup() { mainCRTStartup(); }#endif

TheMakefile is similar to any otherUNIX-lik eMakefile,andlikeany otherCygwinmakefile.Theonly differenceis thatyouusegcc-mwindows to link yourprogramintoaGUI applicationinsteadof acommand-lineapplication.Here’s anexample:

myapp.exe : myapp.o myapp.resgcc -mwindows myapp.o myapp.res -o $@

myapp.res : myapp.rc resource.hwindres $< -O coff -o $@

Notetheuseof windres to compiletheWindowsresourcesinto aCOFF-format.resfile. Thatwill includeall thebitmaps,icons,andotherresourcesyou need,into onehandyobjectfile. Normally, if you omittedthe"-O coff" it wouldcreateaWindows.res formatfile, but wecanonly link COFFobjects.So,we tell windres to produceaCOFFobject,but for compatibilitywith themany examplesthatassumeyour linkercanhandleWindowsresourcefilesdirectly, wemaintainthe.res namingconvention.For moreinformationonwindres, consulttheBinutils manual.

4.2. Debugging Cygwin ProgramsWhenyour programdoesn’t work right, it usuallyhasa "bug" in it, meaningthere’ssomethingwrongwith theprogramitself thatis causingunexpectedresultsor crashes.Diagnosingthesebugsandfixing themis madeeasyby specialtoolscalleddebuggers.In thecaseof Cygwin, thedebuggeris GDB, which standsfor "GNU DeBugger".This

64

Page 65: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter4. Programmingwith Cygwin

tool letsyou run yourprogramin acontrolledenvironmentwhereyoucaninvestigatethestateof your programwhile it is runningor afterit crashes.Crashingprogramssometimescreate"core"files. In Cygwin theseareregulartext files thatcannotbeuseddirectly by GDB.

Beforeyou candebugyour program,youneedto prepareyour programfor debugging.Whatyouneedto do is add-g to all theotherflagsyou usewhencompilingyoursourcesto objects.

Example 4-2.Compiling with -g

$ gcc -g -O2 -c myapp.c$ gcc -g myapp.c -o myapp

Whatthis doesis addextra informationto theobjects(they getmuchbiggertoo) thattell thedebuggeraboutline numbers,variablenames,andotherusefulthings.Theseextra symbolsanddebugginginformationgiveyour programenoughinformationabouttheoriginal sourcessothatthedebuggercanmakedebuggingmucheasierfor you.

In Windowsversionsof GNUPro,GDB comeswith a full-featuredgraphicalinterface.In Cygwin Netdistributions,GDB is only availableasacommand-linetool. To invokeGDB, simply typegdb myapp.exeat thecommandprompt.It will displaysometexttelling youaboutitself, then(gdb) will appearto promptyou to entercommands.Wheneveryouseethis prompt,it meansthatgdbis waiting for you to typein acommand,like run or help. Oh:-) typehelp to gethelpon thecommandsyoucantypein, or readthe[GDB User’s Manual]for acompletedescriptionof GDB andhowto useit.

If yourprogramcrashesandyou’re trying to figureoutwhy it crashed,thebestthing todo is typerun andlet yourprogramrun.After it crashes,youcantypewhere to findoutwhereit crashed,or info localsto seethevaluesof all thelocal variables.There’salsoaprint thatletsyou look at individualvariablesor whatpointerspoint to.

If yourprogramis doingsomethingunexpected,youcanusethebreak commandtotell gdbto stopyour programwhenit getsto aspecificfunctionor line number:

65

Page 66: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter4. Programmingwith Cygwin

Example 4-3."br eak" in gdb

(gdb) break my_function(gdb) break 47

Now, whenyou typerun your programwill stopat that"breakpoint"andyou canusetheothergdbcommandsto look at thestateof yourprogramat thatpoint,modifyvariables,andstepthroughyour program’sstatementsoneat a time.

Notethatyou mayspecifyadditionalargumentsto therun commandto providecommand-lineargumentsto your program.Thesetwo casesarethesameasfar asyourprogramis concerned:

Example 4-4.Debugging with commandline arguments

$ myprog -t foo -queue 47

$ gdb myprog(gdb) run -t foo -queue 47

4.3. Building and Using DLLsDLLs areDynamicLink Libraries,whichmeansthatthey’re linkedinto your programat run time insteadof build time.Therearethreepartsto a DLL:

• theexports• thecodeanddata• theimport library

Thecodeanddataarethepartsyouwrite - functions,variables,etc.All thesearemergedtogether, like if youwerebuilding onebig objectfiles,andput into thedll.They arenotput into your .exeat all.

Theexportscontainsa list of functionsandvariablesthatthedll makesavailabletootherprograms.Think of this asthelist of "global" symbols,therestbeinghidden.

66

Page 67: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter4. Programmingwith Cygwin

Normally, you’d createthis list by handwith a text editor, but it’ spossibleto do itautomaticallyfrom thelist of functionsin yourcode.Thedlltool programcreatestheexportssectionof thedll from your text file of exportedsymbols.

Theimport library is a regularUNIX-lik e.a library, but it only containsthetiny bit ofinformationneededto tell theOShow your programinteractswith ("imports") thedll.This informationis linkedinto your.exe. This is alsogeneratedby dlltool.

4.3.1. Building DLLsOK, let’sgo throughasimpleexampleof how to build adll. For thisexample,we’ll useasinglefile myprog.c for theprogram(myprog.exe) andasinglefile mydll.c forthecontentsof thedll (mydll.dll).

Now compileeverythingto objects:

gcc -c myprog.cgcc -c mydll.c

Unfortunately, theprocessfor building adll is, well, convoluted.You have to run fivecommands,like this:

gcc -s -Wl,-base-file,mydll.base -o mydll.dll mydll.o -Wl,-e,_mydll_init@12dlltool -base-file mydll.base -def mydll.def -output-exp mydll.exp -dllname mydll.dllgcc -s -Wl,-base-file,mydll.base,mydll.exp -o mydll.dll mydll.o -Wl,-e,_mydll_init@12dlltool -base-file mydll.base -def mydll.def -output-exp mydll.exp -dllname mydll.dllgcc -Wl,mydll.exp -o mydll.dll mydll.o -Wl,-e,_mydll_init@12

Theextra stepsgivedlltool theopportunityto generatetheextrasections(exportsandrelocation)thatadll needs.After this,youbuild theimport library:

dlltool -def mydll.def -dllname mydll.dll -output-lib mydll.a

67

Page 68: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter4. Programmingwith Cygwin

Now, whenyou build yourprogram,you link againsttheimport library:

gcc -o myprog myprog.o mydll.a

Notethatwe linkedwith -e _mydll_init@12. This tells theOSwhattheDLL’s "entrypoint" is, andthis is aspecialfunctionthatcoordinatesbringingthedll to life withingtheOS.Theminimumfunctionlookslike this:

#include <windows.h>

int WINAPImydll_init(HANDLE h, DWORD reason, void *foo){

return 1;}

4.3.2. Linking Against DLLsIf youhaveanexistingDLL already, you needto build aCygwin-compatibleimportlibrary (Thesuppliedonesshouldwork, but you mightnothave them)to link against.Unfortunately, thereis not yet any tool to do this automatically. However, youcangetmostof thewayby creatinga .deffile with thesecommands(you mightneedto do thisin bash for thequotingto work correctly):

echo EXPORTS > foo.defnm foo.dll | grep ’ T _’ | sed ’s/.* T _//’ » foo.def

Notethatthis will only work if theDLL is not stripped.Otherwiseyou will getanerrormessage:"No symbolsin foo.dll".

Onceyou have the.def file, youcancreateanimport library from it like this:

dlltool -def foo.def -dllname foo.dll -output-lib foo.a

68

Page 69: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter4. Programmingwith Cygwin

4.4. Defining Windo ws Resour ceswindres readsaWindowsresourcefile (*.rc) andconvertsit to a resor coff file. Thesyntaxandsemanticsof theinput file arethesameasfor any otherresourcecompiler,sopleasereferto any publicationdescribingtheWindowsresourceformatfor details.Also, thewindres programitself is fully documentedin theBinutils manual.Here’sanexampleof usingit in aproject:

myapp.exe : myapp.o myapp.resgcc -mwindows myapp.o myapp.res -o $@

myapp.res : myapp.rc resource.hwindres $< -O coff -o $@

Whatfollows is aquick-referenceto thesyntaxwindres supports.

id ACCELERATORS suboptionsBEG"^C" 12"Q" 1265 1265 12 , VIRTKEY ASCII NOINVERT SHIFT CONTROL ALT65 12 , VIRTKEY, ASCII, NOINVERT, SHIFT, CONTROL, ALT(12 is an acc_id)END

SHIFT, CONTROL, ALT require VIRTKEY

id BITMAP memflags "filename"memflags defaults to MOVEABLE

id CURSOR memflags "filename"memflags defaults to MOVEABLE,DISCARDABLE

69

Page 70: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter4. Programmingwith Cygwin

id DIALOG memflags exstyle x,y,width,height styles BEG con-trols ENDid DIALOGEX memflags exstyle x,y,width,height styles BEG con-trols ENDid DIALOGEX mem-flags exstyle x,y,width,height,helpid styles BEG controls END

memflags defaults to MOVEABLEexstyle may be EXSTYLE=numberstyles: CAPTION "string"CLASS idSTYLE FOO | NOT FOO | (12)EXSTYLE numberFONT number, "name"FONT number, "name",weight,italicMENU idCHARACTERISTICS numberLANGUAGE number,numberVERSIONK numbercontrols:AUTO3STATE paramsAUTOCHECKBOX paramsAUTORADIOBUTTON paramsBEDIT paramsCHECKBOX paramsCOMBOBOX paramsCONTROL ["name",] id, class, style, x,y,w,h [,exstyle] [data]CONTROL ["name",] id, class, style, x,y,w,h, exstyle, helpid [data]CTEXT paramsDEFPUSHBUTTON paramsEDITTEXT paramsGROUPBOX paramsHEDIT paramsICON ["name",] id, x,y [data]ICON ["name",] id, x,y,w,h, style, exstyle [data]ICON ["name",] id, x,y,w,h, style, exstyle, helpid [data]IEDIT params

70

Page 71: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter4. Programmingwith Cygwin

LISTBOX paramsLTEXT paramsPUSHBOX paramsPUSHBUTTON paramsRADIOBUTTON paramsRTEXT paramsSCROLLBAR paramsSTATE3 paramsUSERBUTTON "string", id, x,y,w,h, style, exstyleparams:["name",] id, x, y, w, h, [data]["name",] id, x, y, w, h, style [,exstyle] [data]["name",] id, x, y, w, h, style, exstyle, helpid [data]

[data] is op-tional BEG (string|number) [,(string|number)] (etc) END

id FONT memflags "filename"memflags defaults to MOVEABLE|DISCARDABLE

id ICON memflags "filename"memflags defaults to MOVEABLE|DISCARDABLE

LANGUAGE num,num

id MENU options BEG items ENDitems:"string", id, flagsSEPARATORPOPUP "string" flags BEG menuitems ENDflags:CHECKEDGRAYEDHELPINACTIVEMENUBARBREAK

71

Page 72: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter4. Programmingwith Cygwin

MENUBREAK

id MENUEX suboptions BEG items ENDitems:MENUITEM "string"MENUITEM "string", idMENUITEM "string", id, type [,state]POPUP "string" BEG items ENDPOPUP "string", id BEG items ENDPOPUP "string", id, type BEG items ENDPOPUP "string", id, type, state [,helpid] BEG items END

id MESSAGETABLE memflags "filename"memflags defaults to MOVEABLE

id RCDATA subop-tions BEG (string|number) [,(string|number)] (etc) END

STRINGTABLE suboptions BEG strings ENDstrings:id "string"id, "string"

(User data)id id subop-tions BEG (string|number) [,(string|number)] (etc) END

id VERSIONINFO stuffs BEG verblocks ENDstuffs: FILEVERSION num,num,num,numPRODUCTVERSION num,num,num,numFILEFLAGSMASK numFILEOS numFILETYPE numFILESUBTYPE numverblocks:BLOCK "StringFileInfo" BEG BLOCK BEG vervals END ENDBLOCK "VarFileInfo" BEG BLOCK BEG vertrans END END

72

Page 73: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and

Chapter4. Programmingwith Cygwin

vervals: VALUE "foo","bar"vertrans: VALUE num,num

suboptions:memflagsCHARACTERISTICS numLANGUAGE num,numVERSIONK num

memflags are MOVE-ABLE/FIXED PURE/IMPURE PRELOAD/LOADONCALL DISCARDABLE

73

Page 74: Cygwin User’s Guide...Expectations for UNIX Programmers.....8 1.5. Expectations for Windows Programmers.....9 1.6. Highlights of Cygwin 1.6.1 1.6.2. Supporting both Windows NT and