/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */
#include <stdio.h>
#include <stdlib.h>

typedef unsigned int u32;
typedef signed int s32;
typedef s32 IOSMessage;

typedef struct IOSContext {
    u32 cpsr;
    u32 r[13];
    u32 sp;
    u32 lr;
    u32 pc;
} IOSContext;

typedef struct IOSThread {
    IOSContext context;
    struct IOSThread *next;
    s32 priority;
    u32 state;
    u32 pid;
    u32 attribute;
    void *val;
    struct IOSThread *joinQueue;
    struct IOSThread **queue;
    IOSContext extra;
#ifdef IOS_STACK_CHECK
    u32 stackBottom;
#endif
} IOSThread;
#define IOS_MESSAGE_QUEUE_MAX 64
typedef struct {
    IOSThread *emptyQ;
    IOSThread *fullQ;
    u32 owner;
    s32 count;
    s32 rptr;
    s32 size;
    IOSMessage *buffer;
} IOSMessageQueue;
#define IOS_PATH_MAX 63

#define IOS_NUM_RESOURCES    24
typedef struct IOSResource {
    char path[IOS_PATH_MAX+1];
    u32 pathLen;
    IOSMessageQueue *mq;
    u32 owner;
} IOSResource;
static IOSResource __resources[IOS_NUM_RESOURCES];
char *__processes[] = {
    "kernel", "eticket", "fs", "di", "oh0", "oh1", "sdi", "usbeth", "net", "kd", "wd", "wl", "kd", "ncd", "stm", "ppcboot"
};
u32 nqueues;

int
initResources(FILE *fp)
{
  nqueues = fread(__resources, sizeof(IOSResource), IOS_NUM_RESOURCES, fp); 
 if (nqueues <= 0) {
     printf("Did not find any resources in the file\n");
     return -1;
 }

 /* Convert from be to le */
 {
     int i;
     u32 *tmp = (u32 *) __resources;
     for ( i = 0; i < sizeof(__resources)/sizeof(u32); ++i) {
         *tmp =  (((*tmp) & 0xff)    << 24) |
             (((*tmp) & 0xff00)  << 8)  |
             (((*tmp) & 0xff0000) >> 8) |
             (((*tmp) & 0xff000000) >> 24);
         tmp = ((u32 *)__resources) + i;
     }
 }
 return 0;
}

void
__iosGetResourceUsage(int i)
{
    IOSResource *r = __resources + i;
    printf("Resource %d : (%s)\n", i, r->path);
    if (!*r->path) return;
    printf("  owner: %d (%s), mq: %p\n", r->owner, __processes[r->owner], r->mq);
}

void
__iosGetResourcesUsage(void)
{
    int i;

    for (i = 0; i < IOS_NUM_RESOURCES; ++i) {
        __iosGetResourceUsage(i);
    }
    printf("\n");
}

int
main(int argc, char *argv[])
{
    FILE *fp;
    if (argc < 2) {
        printf("Usage: %s <file>\n", argv[0]);
        printf("Total size for resource area= %u bytes\n", IOS_NUM_RESOURCES*sizeof(IOSResource));
        goto done;
    }
    fp = fopen(argv[1],"r");

    if (initResources(fp) < 0) goto done;
    __iosGetResourcesUsage();
done:
    return 0;
}
