Week 01 Lectures


Course Introduction


CP1521
Computer Systems Fundamentals
2/78

[Diagram:Pics/intro/chip0-small.jpg]


CP1521 on the Web3/78

Primary entry point is Webcms3

   http://webcms3.cse.unsw.edu.au/DPST1092/19T2/

Most of the content lives under

   /home/dp1092/public_html/19T2/...    (e.g.lecs,labs,tutes,...)

Most content is web-accessible via

   http://cgi.cse.unsw.edu.au/~dp1092/19T2/index.php


... CP1521 on the Web4/78

Most material on Webcms3 is publically readable.

Login to Webcms3 is via zID/zPass, and is needed for

 
Submit work via give   (on cmd line)

Check marks via sturec https://cgi.cse.unsw.edu.au/~give/Student/sturec.php

 

For questions: use Webcms3 forum or email A.Finlayson@unswglobal.unsw.edu.au


Course Goals5/78

CP1511

CP1521 ...


CP1511 vs CP15216/78

CP1511

[Diagram:Pics/intro/jumping-small.jpg]


... CP1511 vs CP15217/78

CP1521 ...
 

[Diagram:Pics/intro/military-small.jpg]


Themes8/78

Major themes ...

  1. software components of modern computer systems
  2. how C programs execute (at the machine level)
  3. how to write (MIPS) assembly language
  4. Unix/Linux system-level programming
  5. how operating systems and networks are structured
  6. introduction to concurrency, concurrent programming

Goal: you are able to understand execution of software in detail


Textbook9/78

There is no prescribed textbook
    Recommended reference ...
  • Computer Systems:
    A Programmer's Perspective
    ,
    Bryant and O'Halloren
  • covers most topics, and quite well
  • but uses a different machine code


Acknowledgements10/78

Material and resources have been mainly drawn from:


Systems and Tools11/78

Prac work based on Linux tools

Compilers: gcc  (also dcc on CSE machines, however this will not be available to use in the final exam)

Assembly language:  MIPS  on  QtSpim  

Use your own favourite text editor  

Other tools:   man,  gdb,   valgrind,  make,  bc

Learn to love the shell and command-line ... very useful


Classes12/78

Lectures

Tutorials ... Labs ...


Assessments13/78

Lab exercises contribute 10% to overall mark.

Ideally, the lab exercise for Week X must be

Late submissions will get feedback and reduced mark.

Exceptionally good submissions can get bonus (A+)

Total mark for labs can be > 10   (capped at 11).


... Assessments14/78

Two assignments ...

Late penalty: 1% off max mark for each hour late
 

Good time management avoids late penalties


Quizzes15/78

Five small online quizzes ...

A Practice quiz in week 1 ... C revision quiz. This will help you work out any areas you need to revise.

Then in weeks 3, 6, 8, 10, 12

Each quiz released on the wednesday at 9am, due before Sunday 11:59pm at end of week. A quiz in week X could contain material covered in lectures up to week X-1 and covered in tutorials and labs in week X.


Final Exam16/78

3-hour on-line exam during the exam period.

Held in CSE labs   (must know lab environment)

On-line documentation available in exam:

Format: No dcc available in the exam, just gcc.

How to pass?   Practice, practice, practice, ...


Course Assessment17/78

CourseWorkMark = QuizMark + LabMark + Ass1Mark + Ass2Mark
                                                   (out of 40)
ExamPracMark   = marks for prac questions on final exam
                                                   (out of 30)
ExamTheoryMark = marks for written questions on final exam
                                                   (out of 30)
ExamMark       = ExamPracMark + ExamTheoryMark     (out of 60)

ExamOK         = ExamMark ≥ 24/60                 (true/false)

FinalMark      = CourseWorkMark + ExamMark        (out of 100)

FinalGrade     = UF, if !ExamOK && FinalMark ≥ 50
               = FL, if FinalMark < 50/100 
               = PS, if 50/100 ≤ FinalMark < 65/100 
               = CR, if 65/100 ≤ FinalMark < 75/100 
               = DN, if 75/100 ≤ FinalMark < 85/100 
               = HD, if FinalMark ≥ 85/100   


Computer Systems


What they used to look like19/78

ENIAC ( Electronic Numeric Integrator and Computer) : 1945

[Diagram:Pics/system/eniac-small.jpg]


Computer Systems20/78

Component view of typical modern computer system

[Diagram:Pics/system/components-small.png]


Processor21/78

Modern processors provide

We do not consider multi-core CPUs in this course


Storage22/78

Memory (main memory) consists of

Disk storage consist of


... Storage23/78

Run-time memory usage depends on language processor.

How typical C compiler uses the memory:

[Diagram:Pics/memory/regions-small.png]


Computer System Layers24/78

View of software layers in typical computer system

[Diagram:Pics/system/layers-small.png]


C Program Life-cycle25/78

From source code to machine code ...

[Diagram:Pics/compile/compilation-small.png]


Exercise 1: C Compiler Stages26/78

Using a small program

#include <stdio.h>
#include "x.h"
#define NUM 10

int main(void)
{
   int x = NUM;
   printf("Hello\n");
   return 0;
}

investigate intermediate stages of compilation using flags -E, -S, -c


The Linux Manual


man28/78

The linux manual (man) is divided into the following sections

You can find the full table by using the command man man which shows the manual page about the manual.

You can get more information about individual sections by using man 1 intro, man 2 intro etc.

Advice: man will be available in the exam. Google will not! Get used to using it!


Exercise 2: Using the linux manual29/78

Use man to find out:


Searching the manual30/78

You can search the manual for a keyword using man -k.

For example, I want to find a command to view a pdf I could type

$ man -k pdf


Linux Streams and Pipes


Standard Streams32/78

A stream is a sequence of bytes

stdio.h defines three streams


IO Redirection33/78


Using stderr for error Messages34/78


Unix Pipes35/78


Makefiles


Multi-module C Programs and Makefiles37/78

All large systems written in C ...

Small (tiny) example:

$ gcc -c Stack.c              # produces Stack.o
$ gcc -c main.c               # produces main.o
$ gcc -o main main.o Stack.o  # links Stack.o + main.o


... Multi-module C Programs and Makefiles38/78

While developing a large system ...

If you edit several .c files ...


... Multi-module C Programs and Makefiles39/78

Within a large software system ...

A  Makefile  contains definitions and rules

The  make  command uses a Makefile to rebuild a system


... Multi-module C Programs and Makefiles40/78

Example dependencies and actions

[Diagram:Pics/compile/MakeDepend-small.png]


... Multi-module C Programs and Makefiles41/78

Example  Makefile (i)

main : main.o Stack.o
	gcc -o main main.o Stack.o

main.o : main.c Stack.h
	gcc -c -Wall -Werror main.c

Stack.o : Stack.c Stack.h
	gcc -c -Wall -Werror Stack.c


Legend:  target,  source,  action

Note: The lines with actions MUST begin with a tab (not spaces).


... Multi-module C Programs and Makefiles42/78

Example  Makefile (ii)

CC = gcc
CFLAGS = -Wall -Werror

main : main.o Stack.o

main.o : main.c Stack.h

Stack.o : Stack.c Stack.h


... Multi-module C Programs and Makefiles43/78

Example  Makefile (iii)

CC = gcc
CFLAGS = -Wall -Werror

main : main.o Stack.o

main.o : main.c Stack.h

Stack.o : Stack.c Stack.h

clean : 
	rm -f *.o core main


Debugging Tools


Debugging Tools45/78


[Diagram:Pics/misc/detective-small.png]


... Debugging Tools46/78

Debugging is like detective work ...

DetectingDebugging
Examine the crime scence Examine the output
Form a hypothesis
(what happened? whodunnit?)
Form a hypothesis
(what might have caused this behaviour?)
Look for clues
(to strengthen hypothesis)
Look at code
(to strengthen hypothesis)
Gather evidence Observe program behaviour**
If hypothesis supported,
arrest the perpetrator
If hypothesis supported,
change code to fix problem

** A debugging tool like gdb or qtspim (once we get to MIPS programming) can help with this.


GDB: The Gnu Debugger47/78

gdb provides facilities to

Plain gdb uses a command-line interface.

ddd provides a GUI wrapper around gdb.

For initial debugging, gdb is very useful.


Using GDB48/78

Program must be compiled using -g option.

[Diagram:Pics/tools/gdb-usage-small.png]

gdb provides control of execution, monitoring of state


... Using GDB49/78

Executing program under gdb control:

$ gdb myProg
(gdb) run < dataFile
... crashes, displaying line of code
(gdb) where
... stack trace
(gdb) list
... show code around current location
(gdb) print expr
... display value of expression
(gdb) help
... documentation
(gdb) quit


Basic GDB Commands50/78

quit -- quits from gdb

help [CMD] -- on-line help

run ARGS -- run the program


GDB Status Commands51/78

where -- stack trace

up [N] -- move down the stack list [LINE] --- show code print EXPR -- display expression values


GDB Execution Commands52/78

break [FUNC|LINE] - set break-point

next - single step (over functions) step - single step (into functions) continue - resume program execution For more details see gdb's on-line help.


Exercise 3: Monitoring Program Execution53/78

Use GDB to examine the execution of the following:

Do each of the following:


valgrind54/78

valgrind is a tool that can

Program must be compiled using -g option.

Can be run like:

$ valgrind ./a.out 

Or for more information about memory leaks:

$ valgrind --leak-check=full ./a.out 


Exercise 4: Finding Memory Leaks55/78

Use valgrind to examine the execution of the following:

Do each of the following:


C Revisited


What (I assume) You Know57/78

Given a problem specification ...

I don't assume that you know ...


Fine Control58/78

Good programming style often dictates ...

C has constructs to violate all of these


... Fine Control59/78

Example: scan a[N], stop on zero or at end, ignore negative values

for (i = 0; i < N; i++) {
   if (a[i] == 0) break;
   if (a[i] < 0) continue;
   sum += a[i];
}

/* vs */

for (i = 0; i < N && a[i] != 0; i++) {
   if (a[i] > 0) {
      sum += a[i];
   }
}


Type Definitions60/78

Reminder: you can give a name to a C type definition e.g.

typedef int Integer;
typedef long long int BigInt;
typedef unsigned char Byte;
typedef struct { int x; int y; } Coord;

and then use the name instead of the type definition e.g.

Byte  byte;         // one 8-bit variable
Coord here, there;  // two Coord variables


Assignment as Expression61/78

Assignments can be treated as expressions returning a value

x = 5;          // returns 5

Can be useful

x = y = z = 0;  // equiv to x = (y = (z = 0))

Can be dangerous

if (x = 0)      // "test" always fails


... Assignment as Expression62/78

Assignment-as-expression often used to simplify loops, e.g.

// read stdin one char at-a-time
while ((ch = getchar()) != EOF) {
   // do something with ch
}

rather than

ch = getchar();
while (ch != EOF) {
   // do something with ch
   ch = getchar();
}


Exercise 5: Assignment as Expression63/78

In the example above, we wrote:

// read stdin one char at-a-time
while ((ch = getchar()) != EOF) {
   // do something with ch
}

which reads a char into ch and tests it against EOF

What would the following code do?

// read stdin one char at-a-time
while  ( ch = getchar() != EOF)  {
   // do something with ch
}

Hint: Check precedence table in the C Reference Card or by typing the command

man 7 operator


Ignoring Expression Results64/78

We usually ignore the value returned by an assignment.

Some C functions return a result which is usually ignored. These are usually

E.g. main() returns zero (success) and non-zero (error)

Ignored return error statuses should be


... Ignoring Expression Results65/78

printf() returns the number of characters printed. (See man 3 printf for more details)

int x = 123, y = 42;
printf("%d %d\n", x, y);

 

Exercise 6: printf 65/78

What value does the above printf() return?


Switch-statements66/78

switch encapsulates a common type of selection:

if (v == C1) {
   S1;
} else if (v == C2) {
   S2;
}
...
else if (v == Cn) {
   Sn;
}
else {
   Sn+1;
}

switch (v) {
case C1:
   S1; break;
case C2:
   S2; break;
...
case Cn:
   Sn; break;
default:
   Sn+1;
}

Note: The expression v must be an integral type
Warning: break is critical; if not present, falls through to next case.


... Switch-statements67/78

if (colour == 'r') {
   printf("Red");
} else if (colour == 'g') {
   printf("Green");
} else if (colour == 'b') {
   printf("Blue");
}
else {
   printf("Invalid Colour");
}

switch (colour) {
case 'r':
   printf("Red"); break;
case 'g':
   printf("Green"); break;
case 'b':
   printf("Blue"); break;
default:
   printf("Invalid Colour");
}


Exercise 7: Displaying Months68/78

Write a function monthName(int) that

Suggest an alternative approach using an array.


Conditional Expressions69/78

Encapsulates a common usage for an if:

if (cond) {
   v = Expr1;
} else {
   v = Expr2;
}

can be written as

v = cond ? Expr1 : Expr2;

Examples:

x = (y > 0) ? z+1 : z-1;
or
x = z + ((y > 0) ? 1 : -1);


Exercise 8: Conditionals70/78

For each of the following:

// (a)
if (x > 0)
   y = x - 1;
else
   y = x + 1;

// (b)
if (x > 0)
   y = x - 1;
else
   z = x + 1;

// (c)
if (x > 0) {
   y = x - 1;  z = x + 1;
} else {
   y = x + 1;  z = x - 1;
}


Pointer arithmetic71/78

Pointers can "move" from object to object by pointer arithmetic

For any pointer T *p;,   p++ increases p by sizeof(T )

Examples (assuming 16-bit pointers):

char   *p = 0x6060;  p++;  assert(p == 0x6061)
int    *q = 0x6060;  q++;  assert(q == 0x6064)
double *r = 0x6060;  r++;  assert(r == 0x6068)

A common (efficient) paradigm for scanning a string

char *s = "a string";
char *c;
// print a string, char-by-char
for (c = s; *c != '\0'; c++) {
   printf("%c", *c);
}


Exercise 9: Sum an array of ints72/78

Write a function

int sumOf(int *a, int n)  { ... }

to sum the elements of array a[] containing n values.

Implement it two ways:


Function Pointers73/78

In C you may point to anything in memory.

Function pointers ...


... Function Pointers74/78

Syntax of declaring a function pointer:

return_t (*var) (arg_t, ...)

Examples of declaring a function pointer:

// variable fp is a pointer to a function with
// one int parameter and an int return value
int (*fp) (int);

// variable fp2 is a pointer to a function with 
// a char and an int parameters and a void return value
void (*fp2) (char, int);


... Function Pointers75/78

Examples of use:

int square (int x) { return x*x; }
int timesTwo (int x) { return x*2; }

int (*fp) (int);
//Point to the square function and use it
fp = &square;
int n = (*fp)(10);

//It also works without the '&'
fp = timesTwo;
n = (*fp)(2);

//Normal function notation also works
n = fp(2);


... Function Pointers76/78

Can traverse a collection such as an array, applying the function to all values

void traverse(int len, int a[], int (*f)(int)){
    for(int i = 0; i < len; i++){
        a[i] = f(a[i]);
    }
}

int main(void){
    int a[3] = {1,2,3};
    traverse(3,a,square);
    traverse(3,a,timesTwo);
    return 0;
}


Exercise 10: Understanding Function Pointers77/78

What will the following code do?

int mystery(int a, int b, int (*fn)(int,int)) {
    return (fn(a,b)); 
}
int gcd(int a, int b) {
  int c;
  while ( a != 0 ) {
     c = a; 
     a = b%a;  
     b = c;
  }
  return b;
}
int sumofsquares(int x, int y) { 
    return (x*x + y*y);
}
int sum(int x, int y) { 
    return (x + y);
}
int main(){
    int n = mystery(8,12,sum);
    printf("%d \n", n);
    printf("%d \n", mystery(8,12,gcd));
    printf("%d \n", mystery(8,12,sumofsquares));
    return 0;
} 


Exercise 11: Using Function Pointers78/78

Write a function that:

Use the functions:


Produced: 20 Aug 2019