Docsity

Slides on Cyclone - Programming Analysis and Understanding | CMSC 631, Study notes of Computer Science

Toggle sidebar
bg1
1
Cyclone
A Safe Dialect of C
CMSC 631
Fall 2006
Credit where credit is due …
• Cyclone is a research language, the
product of many collaborators:
– Greg Morrisett, Yanling Wang (Harvard)
– Dan Grossman (Washington)
– Nikhil Swamy (Maryland)
– Trevor Jim (AT&T)
1988? 2006?
• “In order to start copies of itself ru nning on
other machines, the worm took advantage of
a buffer overrun...
• ...it is estimated that it infected and
crippled 5 to 10 percent of the machines on
the Internet.”
• More than 15 years later, nearly half of CERT
advisories involve buffer overruns, format
string attacks, and similar low-level atta cks.
The C Programming Language
• Critical software is often coded in C
– device drivers, kernels
– file systems, web servers, email systems
– switches, routers, firewalls
• … most arguably because it is low-level
– Control over data structure representations
– Control over memory management
–Manifest cost: good performance
Low-level, but unsafe
• Must bypass the type system to do even simple
things (e.g., allocate and in itialize an object)
• Libraries put the onus on the programme r to do the
“right thing” (e.g., c heck return codes, pass in large
enough buffer)
• For efficienc y, programmers stack-alloca te arrays of
size K (is K big enough? does the array escape
downwards?)
• Programmers assume objects can be safe ly recycled
when they cannot, and fail to recycle memory when
they should.
• It’s not “fail-stop”-errors don’t manifest themselves
until well after they happe n (e.g., buffer overruns.)
What about Java?
• Java provides safety in part via:
–hidden data fields and run-time checks
–automatic memory management
• Data representation and resource
management are essential aspects of
low-level systems
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Slides on Cyclone - Programming Analysis and Understanding | CMSC 631 and more Study notes Computer Science in PDF only on Docsity!

Cyclone

A Safe Dialect of C

CMSC 631

Fall 2006

Credit where credit is due …

• Cyclone is a research language, the

product of many collaborators:

  • Greg Morrisett, Yanling Wang (Harvard)
  • Dan Grossman (Washington)
  • Nikhil Swamy (Maryland)
  • Trevor Jim (AT&T)
  • “In order to start copies of itself running on

other machines, the worm took advantage of

a buffer overrun...

  • ...it is estimated that it infected and

crippled 5 to 10 percent of the machines on

the Internet.”

  • More than 15 years later, nearly half of CERT

advisories involve buffer overruns, format

string attacks, and similar low-level attacks.

The C Programming Language

• Critical software is often coded in C

  • device drivers, kernels
  • file systems, web servers, email systems
  • switches, routers, firewalls

• … most arguably because it is low-level

  • Control over data structure representations
  • Control over memory management
  • Manifest cost : good performance

Low-level, but unsafe

  • Must bypass the type system to do even simple things (e.g., allocate and initialize an object)
  • Libraries put the onus on the programmer to do the “right thing” (e.g., check return codes, pass in large enough buffer)
  • For efficiency, programmers stack-allocate arrays of size K (is K big enough? does the array escape downwards?)
  • Programmers assume objects can be safely recycled when they cannot, and fail to recycle memory when they should.
  • It’s not “fail-stop”-errors don’t manifest themselves until well after they happen (e.g., buffer overruns.)

What about Java?

• Java provides safety in part via:

  • hidden data fields and run-time checks
  • automatic memory management

• Data representation and resource

management are essential aspects of

low-level systems

Cyclone A safe, convenient, and modern language at the C level of abstraction

  • Safe: memory safety, abstract types; fail-stop
  • C-level: user-controlled data representation and resource management, easy interoperability, “manifest cost”
  • Convenient: may need more type annotations, but work hard to avoid it
  • Modern: add features to capture common idioms “New code for legacy or inherently low-level systems” Outline
  • Status
  • How Cyclone handles pointer errors
  • Spatial Errors
  • Temporal Errors
  • Programming Experience
  • Performance Analysis Status
  • 110K lines of Cyclone code - 80K compiler, libraries - 30K various servers, applications, device drivers

  • gcc back-end (Linux, Cygwin, OSX, LEGO, …)
  • User’s manual, mailing lists, …
  • Still a research vehicle (though winding down) Projects using Cyclone
  • Open Kernel Environment [Bos/Samwel, OPENARCH 02]
  • MediaNet [Hicks et al, OPENARCH 03]
  • RBClick [Patel/Lepreau, OPENARCH 03]
  • STP [Patel et al., SOSP 03]
  • FPGA synthesis [Teifel/Manohar, ISACS 04]
  • O/S class at Maryland [2004-2005] What is a C buffer overflow? #include int login() { char user [100]; printf(“login: “); scanf(“%s”,&user); … // get password etc. } What happens if the user types In something that’s more than 100 characters? Calling scanf() Stack grows 32 bits downward user:

int login() { char user [100]; printf(“login: “); scanf(“%s”,&user); … } “%s”

login retaddr Buffer indexes proceed upward

Thin Pointers H E L L O p A^ “thin”^ pointer (one word) *p p = NULL; *p Thin Pointers H E L L O p Only dereference permitted, no bounds check needed *p p = NULL; *p Thin Pointers H E L L O p May be null *p p = NULL; *p Thin Pointers H E L L O p Requires a null check if so *p p = NULL; *p Thin Pointers H E L L O p Types and qualifiers for more flexibility and/or fewer checks char *p; char * @notnull p1; // illegal: p1=NULL; p1=p char * @notnull @numelts(6) p2; // illegal: p2=p Thin Pointers H E L L O p Shorthand char *p; char @ p1; char @{6} p2;

Fat Pointers H E L L O q: c f b q++; q[0] q--; q--; q[0] A “fat” pointer; has run time bounds: 3-word representation Fat Pointers H E L L O q: c f b Pointer arithmetic OK q++; q[0] q--; q--; q[0] Fat Pointers H L L O q: c f b q++; q[0] q--; q--; q[0] Bounds check on dereference E Fat Pointers H E L L O q: c f b q++; q[0] q--; q--; q[0] Fat Pointers H E L L O q: c f b q++; q[0] q--; q--; q[0] Dangling pointers OK ... Fat Pointers H E L L O q: c f b q++; q[0] q--; q--; q[0] … caught on dereference

Preventing Temporal Errors

  • Tracks object lifetimes by associating a region with each pointer: int* @region(`r) - A pointer can only be dereferenced while

the region is still live. int *`r for short.

  • Two basic kinds of regions
    • A lexical block (I.e., an activation record)
    • The heap (H); has a global lifetime. Simple Region Example pt a = {1,2}; void foo() { pt b = {3,4}; pt @H aptr = &a; pt @foo bptr = &b; addTo(&a, &b); } a lives in the heap region, so &a has type pt @H. b lives in the activation record of foo so &b has type pt @foo. region inference can figure out the regions, so the programmer doesn't have to write them Region Polymorphism void addTo<r1,r2>(pt *r1 p, pt *`r2 q) { p->x += q->x; p->y += q->y; }

This is standard parametric polymorphism:

addTo: ∀r1. ∀r2. (pt *r1 **×** pt *r2) → void addTo is parameterized by the regions for p and q. So this would go through... pt *H add<r1,r2>(pt *r1 p, pt *r2 q) { pt *r = malloc(sizeof(pt)); r->x = p->x + q->x; r->y = p->y + q->y; return r; } pt a = {1,2}; void foo() { pt b = {3,4}; pt *H c = add<H,foo>(&a, &b); pt *H d = add<foo,foo>(&b, &b); c->x = 10; } And this would be caught pt *H add<r1,r2>(pt *r1 p, pt *r2 q) { pt r; r.x = p->x + q->x; r.y = p->y + q->y; return &r; } pt a = {1,2}; void foo() { pt b = {3,4}; pt *H c = add<H,foo>(&a, &b); pt *H d = add<foo,foo>(&b, &b); c->x = 10; } region of r is add, notH On the other hand... pt *H add<r1,r2>(pt *r1 p, pt *r2 q) { p->x += q->x; p->y += q->y; return p; } pt a = {1,2}; void foo() { pt b = {3,4}; pt *H c = add<H,foo>(&a, &b); pt *H d = add<foo,foo>(&b, &b); c->x = 10; } region of p isr1, not `H

So we must be explicit pt *r1 add<r1,r2>(pt *r1 p, pt *r2 q) { p->x += q->x; p->y += q->y; return p; } pt a = {1,2}; void foo() { pt b = {3,4}; pt *H c = add<H,foo>(&a, &b); pt *foo d = add<foo,foo>(&b, &b); c->x = 10; } What has to be written is thus: pt *r1 add(pt *r1 p, pt * q) { p->x += q->x; p->y += q->y; return p; } pt a = {1,2}; void foo() { pt b = {3,4}; pt * c = add(&a, &b); pt * d = add(&b, &b); c->x = 10; } The types say it all pt * add (pt * p, pt * q); pt *r1 add (pt *r1 p, pt * q); pt *r2 add (pt * p, pt *r2 q); char * @zerotermr fgets(char *{len} @zeroterm `r, int len, FILE @); Dynamic Allocation

  • How can we be sure data is live?
  • Can use a GC, or safe manual techniques
  • GC-based
    • Data allocated in heap is given region `H
      • Region is always live; dereferences are always safe
    • Conservative collector reclaims dead objects
    • Simple, but little control over performance
      • Potentially significant memory overheads
      • Pause times
      • May not be feasible in some environments (e.g., Linux) Safe Manual Techniques
  • Approach: generalize regions, track pointers
  • New region kind: Arenas
  • Dynamic allocation, but all objects freed at once
  • And/or impose aliasing restrictions
  • Can free individual objects using malloc/free or reference counting if aliasing is tracked
  • When writing apps, use GC first, tune as

necessary

  • Can result in significantly improved memory footprint and throughput LIFO Arenas
  • Dynamic allocation mechanism
  • Lifetime of entire arena is scoped
  • At conclusion of scope, all data allocated

in the arena is freed

  • Like a stack frame, but permits dynamic

allocation

  • Useful when caller doesn’t know how much memory needed by callee, but controls lifetime
  • Aliasing qualifier \RC
    • pointed-to data have hidden count field
  • Aliasing tracked as with unique pointers. Explicit aliasing/freeing via

a *\RCr alias_refptr(a *\RCr);

void drop_refptr(a *\RCr);

Reference-counted Pointers Interesting Combinations

  • Tracked pointers can be freed manually,

with free or drop_refptr, or automatically

  • Pointers into the heap freed by GC
  • Pointers into LIFO arenas freed at end of scope
    • Called a reap by Berger et al
  • Can use tracked pointers to keys to permit

arenas to have non-lexical lifetimes

  • Lifetime of arena corresponds to the lifetime of the key
  • Called dynamic arena

Refcounted

Unique manual^ restricted

single GC

objects

Heap

Dynamic manual

LIFO dynamic

exit of ok

scope

whole

region

Stack static

Aliasing

(objs)

Deallocation

(what) (when)

Allocation

(objects)

Region

Variety

Summary

  • Many different idioms could be hard to use
    • Duplicated library functions
    • Hard-to-change application code
  • We have solved this problem by
    • Using region types as a unifying theme
    • Region (and aliasing) polymorphism
      • E.g., functions independent of arguments’ regions/aliasing
    • All regions can be treated as if lexical
      • Temporarily, under correct circumstances
      • Using alias and open (for dynamic arenas) Ensuring Uniformity and Reuse

Boa web server

Cfrac Prime factorization

BetaFTPD ftp server

Epic image compression

Kiss-FFT portable fourier transform

MediaNet streaming overlay network

Linux Drivers net, video, sound

CycWeb web server

CycScheme scheme interpreter

Some Application Experience Application Characteristics

  • Platform
    • Dual 1.6 GHz AMD Athlon MP 2000
      • 1 GB RAM
      • Switched Myrinet
    • Linux 2.4.20 (RedHat)
  • Software
    • C code: gcc 3.2.
    • Cyclone code: cyclone 0.
    • GC: BDW conservative collector 6.2α 4
    • malloc/free: Lea allocator 2.7. Experimental Measurements - CPU time - I/O bound applications have comparable performance - All applications: at most 60% slowdown - GC has little impact on elapsed time - MediaNet is the exception - Memory usage - Using GC requires far more memory than manual - Cyclone manual techniques approach footprint of C original Bottom Line Throughput (Webservers) Throughput (MediaNet) Memory Usage (Web) Memory Usage II (Web)

Related Work: Checking C

  • Model-checking C code (SLAM, BLAST, …)
    • Leverages scalability of MC
    • Key is automatic building and refining of model
    • Assumes (weak) memory safety
  • Lint-like tools (Splint, Metal, PreFIX, …)
    • Good at reducing false positives
    • Cannot ensure absence of bugs
    • Metal particularly good for user-defined checks
  • Cqual (user-defined qualifiers, lots of inference) Better for unchangeable code or user-defined checks (i.e., they’re complementary) Related work: higher and lower - Adapted/extended ideas: - polymorphism [ML, Haskell, …] - regions [Tofte/Talpin, Walker et al., …] - safety via dataflow [Java, …] - existential types [Mitchell/Plotkin, …] - controlling data representation [Ada, Modula-3, …] - Safe lower-level languages [TAL, PCC, …] - engineered for machine-generated code - Vault: stronger properties via restricted aliasing
  • Tracked pointers can be painful; want
  • Better inference (e.g. for alias)
  • Richer API (restrict; autorelease)
  • Prevent leaks
  • unique and reference-counted pointers
  • Specified aliasing
  • for doubly-linked lists, etc.
  • Concurrency Future Work
  • High degree of control, safely:
  • Sound mechanisms for low-level control
  • Checked pointers for spatial errors
  • Variety of techniques for temporal errors
  • Region-based vs. object-based deallocation
  • Manual vs. automatic reclamation
  • Region- and alias-annotated pointers within a coherent framework
  • Scoped regions unifying theme (alias,open)
  • Polymorphism, for code reuse Conclusions
  • Cyclone homepage

http://cyclone.thelanguage.org

  • Has papers, benchmarks, distribution More Information MediaNet Data structures

Other Details

  • Can store unique pointers in non- unique containers - Must use “swap” operator to extract

them, to ensure soundness of analysis.

  • Alias construct
    • Like Walker/Watkins (and Wadler) let!
    • Fresh region is crucial to soundness -

normal typing machinery ensures that

aliased pointers will not escape the scope.

Sharing Unique Pointers

  • Can we have unique pointers in non- unique containers? Options: - Don't allow them; norm in linear type

systems

  • Track sharable containers
    • E.g., guarded types in Vault; restricts container aliasing, and may not be thread-safe
  • Swap out unique pointers Swap to the rescue int *U g = NULL; // cannot access directly void init(int v) { int *U x = malloc(sizeof(int)); *x = v; g :=: x; // atomically swap *x with *g free(x); } Tying it together: Polymorphism
  • Goal: avoid writing slightly different versions of the same functions
  • One for unique pointers, one for lexically-

scoped region pointers, etc.

  • Approach: parametric polymorphism, differentiated by kinds. - Need to differentiate between generic

functions that operate on alias-restricted

pointers and freely-aliasable ones.

Unique-path access restriction

Invariant : Only ever one (unique) path by

which to access a unique object at any

program point

void f(int *U*r x, int U*r y) { free(x);

**y = 1; // error if *x == *y

} x y rU Dynamic Arenas

  • Unique and reference-counted objects can be freed at any time
  • Also want to be able to free an entire arena at any time - Not just at the conclusion of a scope; I.e.

want separate region allocation and

deallocation functions.

Growable Regions typedef int head; struct List<r> { struct List<r> *r tl; } *r list_t<r>; void region<d> foo(unsigned h { int i) { list_t<d> for (; i != x 0;= NULL,i++) {temp; temp = rmalloc(h, sizeof(struct List)); temp->head x = temp; = i; temp->tl = x; }; process(h,x); } } Growable Regions typedef int head; struct List<r> { struct List<r> *r tl; } *r list_t<r>; void region<d> foo(unsigned h { int i) { list_t<d> for (; i != x 0;= NULL,i++) {temp; temp = rmalloc(h, sizeof(struct List)); temp->head x = temp; = i; temp->tl = x; }; process(h,x); } } The list structure is parameterized by a region Growable Regions typedef struct List<r> { int struct head; List<r> *r tl; } *r list_t<r>; void region<d> foo(unsigned h { int i) { list_t<d> x = NULL, temp; for temp (; i= !=rmalloc(h 0; i++), {sizeof(struct List)); temp->head x = temp; = i; temp->tl = x; }; }^ process(h,x); } The “region<d> h{...}” introduces a new dynamic region d with handle h. Growable Regions typedef struct List<r> { int struct head; List<r> *r tl; } *r list_t<r>; void region<d> foo(unsigned h { int i) { list_t<d> x = NULL, temp; for temp (; i= !=rmalloc(h 0; i++), {sizeof(struct List)); temp->head x = temp; = i; temp->tl = x; }; }^ process(h,x); } Objects can be allocated into region d using rmalloc(h,...) where h is a handle for the region. Unlike the stack, any number of objects can be placed in the region. Growable Regions typedef int head; struct List<r> { struct List<r> *r tl; } *r list_t<r>; void foo(unsigned int i) { region<d> list_t<d> h {x = NULL, temp; for temp (; i= !=rmalloc(d 0; i++), {sizeof(struct List)); temp->head = i; temp->tl = x; };^ x^ =^ temp; }^ process(h,x); } Since this function is given the handle for d, it can allocate objects in there too, or return results in that region. Growable Regions typedef int head; struct List<r> { struct List<r> *r tl; } *r list_t<r>; void foo(unsigned int i) { region<d> list_t<d> h {x = NULL, temp; for temp (; i= !=rmalloc(h 0; i++), {sizeof(struct List)); temp->head = i; temp->tl = x; };^ x^ =^ temp; }^ process(h,x); } (^) The entire region is deallocated at the end of its scope.

So Far: Advantages

  • Type system makes sure that:
    • can’t dereference a pointer to a freed object.
    • can’t forget to free a region.
    • supports some dangling pointers.
  • Runtime system ensures that:
    • region and object allocation are constant time.
    • region deallocation is constant time – and faster than individually free’ing the objects.
  • So the approach is quite attractive for real-time systems when compared to GC.

struct conn *\RC cmd_pasv(struct conn *\RC c) {

struct ftran *\RC f;

int sock = socket(...);

f = alloc_new_ftran(sock,alias_refptr(c));

c->transfer = alias_refptr(f);

listen(f->sock, 1);

f->state = 1;

drop_refptr(f);

return c;

Example