home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_02_09 / 2n09047a < prev    next >
Text File  |  1991-07-23  |  2KB  |  72 lines

  1.  
  2. /*******************************************************
  3.  *  readonly.c: Test program for Tony Ingenoso's
  4.  *              method for created "Read only"
  5.  *              data under OS/2.
  6.  *
  7.  *  The idea is that a code segment in OS/2 can't be
  8.  *  written to, and any attempt to do so will cause
  9.  *  an instant Trap-D.  Since debugging traps is
  10.  *  *MUCH* easier than debugging memory overwrite
  11.  *  problems, we use OS/2's ability to give a code
  12.  *  segment "alias" for data segments to make read
  13.  *  only pointers we pass to functions that should
  14.  *  not modify their data.
  15.  ******************************************************/
  16.  
  17.  
  18. #define INCL_DOSMEMMGR
  19. #include <os2.h>
  20. #include <stdio.h>
  21. #include <process.h>
  22.  
  23. void WriteOK(USHORT FAR *ptr)
  24.     {
  25.     *ptr = 10;    /* This reference will be OK */
  26.     printf("Read/Write assignment complete\n\n");
  27.     }
  28.  
  29. void WriteNotOK(USHORT FAR *ptr)
  30.     {
  31.     printf("About to do R/O assignment(will Trap-D)\n");
  32.     printf("Strike a key to cause the trap\n");
  33.     getch();
  34.     *ptr = 10;    /* This reference will cause a Trap-D */
  35.     }
  36.  
  37. SEL MakeReadOnly(SEL data)
  38.     {
  39.     SEL       CodeSel;   /* Code alias for read only data */
  40.  
  41.     /*
  42.       Note that DosCreateCSAlias() gives back a ring 2
  43.       conforming selector.  We'll frob it into a normal
  44.       ring 3 selector like any other normal data selector.
  45.     */
  46.     if (DosCreateCSAlias(data, &CodeSel))
  47.         {
  48.         printf("Can't make alias\n");
  49.         exit(-1);
  50.         }
  51.             /* Force ring 2 conforming alias into ring 3 */
  52.     return (CodeSel | 0x0003);
  53.     }
  54.  
  55. void main(void)
  56.     {
  57.     SEL       DataSel;        /* Selector for read/write data   */
  58.  
  59.     /*
  60.       Allocate a bit of memory to play with(4 bytes).
  61.     */
  62.     if (DosAllocSeg(4, &DataSel, 0))
  63.         {
  64.         printf("Can't get memory\n");
  65.         exit(-1);
  66.         }
  67.  
  68.     WriteOK(MAKEP(DataSel, 0));
  69.  
  70.     WriteNotOK(MAKEP(MakeReadOnly(DataSel), 0));
  71.     }
  72.