Skip to content

[RFC] psl1ght "v3" #67

Open
Open

Description

@xerpi

In order to modernize ps3toolchain and psl1ght, and thanks to the lessons learnt in https://github.com/vitasdk, I propose the following changes to psl1ght:

  • The latest versions of newlib include all the necessary C headers (socket.h, etc) so we should remove them from psl1ght (they generate conflicts...), and the implementation of those functions should go to newlib.

  • Add a NID database (like this one) and use it to generate the *_stub.a with a tool/script

  • Make the function prototypes/enums/structs consistent: if the header is for an import named cell*, all the symbols in such header should begin with cell for functions, Cell for structs / enums, and CELL_ for constants (e.g., netCtlInit should be named cellNetCtlInitand the struct net_ctl_nat_infoshould be typedef struct CellNetCtlNatInfo { ... } CellNetCtlNatInfo;.

  • All the syscalls should be in lowercase snake_case with the sys_ prefix.

As a PoC, I've already written a python script (I can port it to C if necessary) that generates an assembly file that gets compiled into the *_stub.a given a yml database. For example, given this input, it generates this output, which is easily compilable with ppu-as -mregnames -c cellCamera.s -o libcellCamera_stub.o.

This script can be useful to dump NIDs and libraries/modules information from an ELF file.

Activity

  1. zeldin commented on Dec 2, 2017

    @zeldin
    Member

    Sounds nice.

    I guess the renaming of typedefs and constants will break API compatibility; should we provide a backwards compat header to add the old names back as aliases? I'm guessing it's not that important and that we should not mess up the new code because of it.

  2. xerpi commented on Dec 2, 2017

    @xerpi
    Author

    Well, my idea was that old homebrews can continue using the old version while new ones (or if they want to port) can use the newer version. Both versions could co-exist on the same system by changing the PSL1GHT environment variable when compiling.
    Another important feature that we should target is the ability to generate PRXes.

    EDIT: After thinking a bit more about PRXes:
    A PRX needs to have:

    • ELF's e_entry = 0 (or any value?, it isn't used)
    • The first LOAD segment contains the sys_prx_module_info_t struct
    • A PRXRELOC segment

    So the options for the base ELF are:

    1. Generate a PIE executable (DYN ELF).
    2. Generate a regular executable ELF with the linker option -q(--emit-relocs). ← This is what VitaSDK does.

    Then run a tool, let's call it psl1ght-prx-gen, that given the ELF and a list of exports, it walks the symtable, creates the sys_prx_module_info_tand converts the standard ELF relocations to the PRXRELOC segment.

    For the imports, simply by linking with lib*_stub.a would add a .lib.stub section, then psl1ght-prx-gen will make the sys_prx_module_info_t::imports_start point to them.
    Another utility of psl1ght-prx-gen (or psl1ght-libs-gen) would be to generate the .yml file of the exports, so other .sprx/.self can import those exports.

    • psl1ght-prx-gen -> .yml -> psl1ght-libs-gen -> .a
    • {.elf + exports.yml} -> psl1ght-prx-gen -> .sprx
  3. xerpi commented on Dec 4, 2017

    @xerpi
    Author

    A lot of the explained ideas are inspired by: https://wiki.henkaku.xyz/vita/images/a/a2/Vita_SDK_specifications.pdf.

  4. grepwood commented on Jun 16, 2020

    @grepwood

    3 cents anyone? Proper network stack support. I'm currently breaking my back porting github.com/ec-/Quake3e.

  5. miigotu commented on Jun 16, 2020

    @miigotu
    Member

    @grepwood what do you need from us? Ill help if I can.

  6. grepwood commented on Jun 17, 2020

    @grepwood

    @miigotu https://github.com/ec-/Quake3e/issues/55 we are missing a lot of headers normally found on Linux and BSD:

    • net/if.h
    • sys/ioctl.h
    • ifaddrs.h
    • sys/ipc.h
    • sys/shm.h
    • sys/mman.h (available in SPU part of the toolchain)
    • dlfcn.h
    • termios.h (includes wrong file from ps3dev, even if corrected it is massively underdeveloped)
  7. xerpi commented on Jun 17, 2020

    @xerpi
    Author

    @grepwood I think those headers should be installed by newlib and not provided by this PSL1GHT. Check the first bullet of the first comment.

  8. grepwood commented on Jun 17, 2020

    @grepwood

    @xerpi Right. I'll recompile ps3toolchain then. Is https://github.com/ps3dev/ps3toolchain this the correct repo?

  9. xerpi commented on Jun 17, 2020

    @xerpi
    Author

    @grepwood I mean if we implement what I propose on this ticket, then those headers would be in newlib. Actually your comment at #67 (comment) started a totally off-topic discussion.

  10. miigotu commented on Jun 17, 2020

    @miigotu
    Member

    @xerpi I'm with you all the way except the db/stub. How are those addresses generated?

  11. xerpi commented on Jun 18, 2020

    @xerpi
    Author

    There's a list of NIDs here: https://www.psdevwiki.com/ps3/VSH_Exports

  12. bucanero commented on Jun 18, 2020

    @bucanero

    I'm really happy to see that this RFC is being discussed again 👍

    getting PSL1GHT to build .sprx binaries would be a dream, providing a full open-source solution for PS3 development. 😄

    I'm not the most senior developer in these kind of topics and a lot of stuff might be way over my head, but I'll be happy to help. Even with just basic stuff like building the NID database, by going to the psdevwiki and copying all the stuff to the db.yml file.

  13. crystalct commented on Jun 19, 2020

    @crystalct

    I'm new in PS3 homebrew development.. but i'm here.

  14. SuperDre commented on Jun 19, 2020

    @SuperDre

    Biggest problem I always have is setting up the whole enviroment, I'm from the kind of developer that just installs the IDE and starts developing. I once started with PS3 dev through a virtual machine, but after a couple of upgrades of Linux and every single time something was broken, I just gave up, also tried through the one on windows but that also went fubar after I had to reinstall windows, never got around of reinstalling it again.
    I was working on a Tiny Tower port for the PS3 (didn't get really far yet as at that time an linux upgrade fubarred the whole setup).

  15. grepwood commented on Jun 19, 2020

    @grepwood

    @xerpi I hate to rain on your parade but the headers I'm looking for to realize the Quake 3 port are still available only in the phoenix, rtems and Linux targets of newlib. Which one is psl1ght using?

  16. miigotu commented on Jun 19, 2020

    @miigotu
    Member

    @xerpi I hate to rain on your parade but the headers I'm looking for to realize the Quake 3 port are still available only in the phoenix, rtems and Linux targets of newlib. Which one is psl1ght using?

    Linux ppc64 - we would patch it to target the ppc64 arch if it wasn't supported, on a different branch. Then we would check out that branch for the submodule.

  17. dee12452 commented on Jul 1, 2020

    @dee12452

    Sorry to "bump" the thread, especially since I'm brand new to the scene, but I'd be more than happy to help make this happen. I was planning on working on porting/moving the net code over to newlib myself as a start (and to add some missing stubs in net code I need), but maybe having the NID DB and generating the .a's would be a better place to start.

  18. miigotu commented on Jul 1, 2020

    @miigotu
    Member

    @dee12452 absolutely. Since we will have several things going on at the same time, just make the PRs to the develop branch.

  19. grepwood commented on Jul 11, 2020

    @grepwood

    Before you start using newlib-3.3.0 you might want to see how every version of newlib since 2.5.0.20170519 is broken for the spu target https://bugs.gentoo.org/732206

  20. xerpi commented on Sep 10, 2020

    @xerpi
    Author

    I've managed to get from my old laptop the folder containing the v3 experiments I was doing regarding stub generation. I have re-uploaded the files that had broken links (now those files should be permanent, I'm using gist.github):

    For example, given this input, it generates this output, which is easily compilable with ppu-as -mregnames -c cellCamera.s -o libcellCamera_stub.o.

    I have also uploaded a tool that can be helpful to examine the NIDs and libraries/modules of ELF files: nidreader.py.

  21. Fancy2209 commented on Jul 18, 2025

    @Fancy2209
    Member

    Is there still interest in this?
    By modifying the python script xerpii posted above and pairing it with the nids.txt file from PS3GhidraScripts I was able to make a complete db.yml of all the prx in /dev_flash/sys/external, although some functions are unfortunately unnamed (but should be possible to brute force them)

  22. Fancy2209 commented on Jul 18, 2025

    @Fancy2209
    Member

    Here's the DB for External and Internal PRX Exports:

    db_external.yml.txt
    db_internal.yml.txt

    Here's the modified script:

    #!/usr/bin/env python3
    
    import sys
    import os
    import csv
    
    from collections import namedtuple
    from elftools.elf.elffile import ELFFile
    from elftools.elf.relocation import RelocationSection
    
    from construct import Struct, Int8ub, Int16ub, Int32ub, PaddedString, CString, Array
    
    
    ModuleImports = namedtuple("ModuleImports", "name nids")
    ModuleExports = namedtuple("ModuleExports", "name nids")
    ModuleInfo = namedtuple("ModuleNids", "name imports exports")
    NIDNames = dict()
    PrintedModules = False
    UnnamedNIDS = []
    
    #ELFOSABI_CELL_LV2 = 0x66
    ELFOSABI_CELL_LV2 = "ELFOSABI_CELL_LV2"
    ET_SCE_PPURELEXEC = 0xFFA4
    PT_PRX_PARAM = 0x60000002
    
    sys_prx_module_info_t = Struct(
        "attributes" / Int16ub,
        "version" / Int16ub,
        "name" / PaddedString(28, "ascii"),
        "toc" / Int32ub,
        "exports_start" / Int32ub,
        "exports_end" / Int32ub,
        "imports_start" / Int32ub,
        "imports_end" / Int32ub,
    )
    
    sys_prx_module_exports_t = Struct(
        "size" / Int8ub,
        "unk0" / Int8ub,
        "version" / Int16ub,
        "attributes" / Int16ub,
        "num_func" / Int16ub,
        "num_var" / Int16ub,
        "num_tlsvar" / Int16ub,
        "info_hash" / Int8ub,
        "info_tlshash" / Int8ub,
        "unk1" / Int16ub,
        "name_addr" / Int32ub,
        "fnid_addr" / Int32ub,
        "fstub_addr" / Int32ub
    )
    
    sys_prx_module_imports_t = Struct(
        "size" / Int8ub,
        "unk0" / Int8ub,
        "version" / Int16ub,
        "attributes" / Int16ub,
        "num_func" / Int16ub,
        "num_var" / Int16ub,
        "num_tlsvar" / Int16ub,
        "info_hash" / Int8ub,
        "info_tlshash" / Int8ub,
        "unk1" / Int16ub,
        "name_addr" / Int32ub,
        "fnid_addr" / Int32ub,
        "fstub_addr" / Int32ub,
        "var_nid_table" / Int32ub,
        "var_entry_table" / Int32ub,
        "tls_nid_table" / Int32ub,
        "tls_entry_table" / Int32ub
    )
    
    sys_process_prx_param_t = Struct(
        "size" / Int32ub,
        "magic" / Int32ub,
        "version" / Int32ub,
        "unk0" / Int32ub,
        "libent_start" / Int32ub,
        "libent_end" / Int32ub,
        "libstub_start" / Int32ub,
        "libstub_end" / Int32ub,
        "ver" / Int16ub,
        "unk1" / Int16ub,
        "unk2" / Int32ub,
    )
    
    def usage():
        print("ps3nidreader by xerpi")
        print("Usage:\n\t" + sys.argv[0] + " file.elf")
    
    def read_nids_ps3_prx(f, elffile):
        module_info_found = False
    
        # First LOAD-type segment p_paddr points to the module info
        for segment in elffile.iter_segments():
            if segment.header.p_type == 'PT_LOAD':
                p_offset = segment["p_offset"]
                f.seek(segment["p_paddr"])
                module_info = sys_prx_module_info_t.parse_stream(f)
                module_info_found = True
                break
    
        if not module_info_found:
            print("Error: can't find the module info", file=sys.stderr)
            exit(1)
    
        #modinfo = ModuleInfo(module_info["name"].decode('ascii'), [], [])
        modinfo = ModuleInfo(module_info["name"], [], [])
    
        exp_addr = p_offset + module_info["exports_start"]
        while exp_addr < p_offset + module_info["exports_end"]:
            f.seek(exp_addr)
            exports = sys_prx_module_exports_t.parse_stream(f)
    
            name = ""
            if exports["name_addr"]:
                f.seek(p_offset + exports["name_addr"])
                name = CString('ascii').parse_stream(f)
    
            f.seek(p_offset + exports["fnid_addr"])
            nids = Array(exports["num_func"], Int32ub).parse_stream(f)
    
            modimp = ModuleExports(name, nids)
            modinfo.exports.append(modimp)
    
            exp_addr += exports["size"]
    
        imp_addr = p_offset + module_info["imports_start"]
        while imp_addr < p_offset + module_info["imports_end"]:
            f.seek(imp_addr)
            imports = sys_prx_module_imports_t.parse_stream(f)
    
            f.seek(p_offset + imports["name_addr"])
            name = CString('ascii').parse_stream(f)
    
            f.seek(p_offset + imports["fnid_addr"])
            nids = Array(imports["num_func"], Int32ub).parse_stream(f)
    
            modimp = ModuleImports(name, nids)
            modinfo.imports.append(modimp)
    
            imp_addr += imports["size"]
    
        return modinfo
    
    def read_nids_ps3_elf_bruteforce(f, elffile):
        modinfo = ModuleInfo("", [], [])
    
        # Find the exports section
        exports_idx = -1
        for idx, section in enumerate(elffile.iter_sections()):
            if section["sh_size"] > 0 and section["sh_size"] % 0x1C == 0:
                is_exports = True
                offset = 0
                while offset < section["sh_size"]:
                    f.seek(section["sh_offset"] + offset)
                    if Int8ub.parse_stream(f) != 0x1C:
                        is_exports = False
                        break
                    offset += 0x1C
    
                if is_exports:
                    exports_idx = idx
                    break;
    
        if exports_idx == -1:
            print("Error: can't find the imports", file=sys.stderr)
            exit(1)
    
        # Find the imports section
        imports_idx = -1
        for idx, section in enumerate(elffile.iter_sections()):
            if section["sh_size"] > 0 and section["sh_size"] % 0x2C == 0:
                is_imports = True
                offset = 0
                while offset < section["sh_size"]:
                    f.seek(section["sh_offset"] + offset)
                    if Int8ub.parse_stream(f) != 0x2C:
                        is_imports = False
                        break
                    offset += 0x2C
    
                if is_imports:
                    imports_idx = idx
                    break;
    
        if imports_idx == -1:
            print("Error: can't find the imports", file=sys.stderr)
            exit(1)
    
        exp_section = elffile.get_section(exports_idx)
        exp_sh_offset = exp_section["sh_offset"]
        exp_sh_addr = exp_section["sh_addr"]
        exp_offset = 0
        while exp_offset < exp_section["sh_size"]:
            f.seek(exp_sh_offset + exp_offset)
            exports = sys_prx_module_exports_t.parse_stream(f)
            name = ""
            if exports["name_addr"]:
                f.seek(exports["name_addr"] + (exp_sh_offset - exp_sh_addr))
                name = CString("ascii").parse_stream(f)
    
            f.seek(exports["fnid_addr"] + (exp_sh_offset - exp_sh_addr))
            nids = Array(exports["num_func"], Int32ub).parse_stream(f)
    
            modexp = ModuleExports(name, nids)
            modinfo.exports.append(modexp)
    
            exp_offset += exports["size"]
    
        imp_section = elffile.get_section(imports_idx)
        imp_sh_offset = imp_section["sh_offset"]
        imp_sh_addr = imp_section["sh_addr"]
        imp_offset = 0
        while imp_offset < imp_section["sh_size"]:
            f.seek(imp_sh_offset + imp_offset)
            imports = sys_prx_module_imports_t.parse_stream(f)
            name = ""
            if imports["name_addr"]:
                f.seek(imports["name_addr"] + (imp_sh_offset - imp_sh_addr))
                name = CString("ascii").parse_stream(f)
    
            f.seek(imports["fnid_addr"] + (imp_sh_offset - imp_sh_addr))
            nids = Array(imports["num_func"], Int32ub).parse_stream(f)
    
            modimp = ModuleImports(name, nids)
            modinfo.imports.append(modimp)
    
            imp_offset += imports["size"]
    
        return modinfo
    
    def read_nids_ps3_elf(f, elffile):
        prx_param_found = False
    
        # PT_PRX_PARAM segment has the process PRX param
        for segment in elffile.iter_segments():
            if segment.header.p_type == PT_PRX_PARAM:
                p_offset = segment["p_offset"]
                p_paddr = segment["p_paddr"]
                if segment["p_offset"] == 0:
                    return read_nids_ps3_elf_bruteforce(f, elffile)
                f.seek(segment["p_offset"])
                prx_param = sys_process_prx_param_t.parse_stream(f)
                prx_param_found = True
                break
    
        if not prx_param_found:
            print("Error: can't find the PRX param segment", file=sys.stderr)
            exit(1)
    
        modinfo = ModuleInfo("", [], [])
    
        exp_addr = p_offset + (prx_param["libent_start"] - p_paddr)
        while exp_addr < p_offset + (prx_param["libent_end"] - p_paddr):
            f.seek(exp_addr)
            exports = sys_prx_module_exports_t.parse_stream(f)
    
            name = ""
            if exports["name_addr"]:
                f.seek(p_offset + (exports["name_addr"] - p_paddr))
                name = CString("ascii").parse_stream(f)
    
            f.seek(p_offset + (exports["fnid_addr"] - p_paddr))
            nids = Array(exports["num_func"], Int32ub).parse_stream(f)
    
            modexp = ModuleExports(name, nids)
            modinfo.exports.append(modexp)
    
            exp_addr += exports["size"]
    
        imp_addr = p_offset + (prx_param["libstub_start"] - p_paddr)
        while imp_addr < p_offset + (prx_param["libstub_end"] - p_paddr):
            f.seek(imp_addr)
            imports = sys_prx_module_imports_t.parse_stream(f)
    
            f.seek(p_offset + (imports["name_addr"] - p_paddr))
            name = CString("ascii").parse_stream(f)
    
            f.seek(p_offset + (imports["fnid_addr"] - p_paddr))
            nids = Array(imports["num_func"], Int32ub).parse_stream(f)
    
            modimp = ModuleImports(name, nids)
            modinfo.imports.append(modimp)
    
            imp_addr += imports["size"]
    
        return modinfo
    
    def print_nids(modinfo):
        print("Module name: " + modinfo.name)
    
        print("  Exports:")
    
        for exp in modinfo.exports:
            if exp.name:
                print("    " + exp.name)
            else:
                print("    <no name>")
            for nid in exp.nids:
                nid_formatted = "0x{:08X}".format(nid)
                if(nid_formatted in NIDNames):
                    print("      " + nid_formatted + " " + NIDNames[nid_formatted])
                else:
                    print("      " + nid_formatted + " ")
    
    
        #print("  Imports:")
    
        #for imp in modinfo.imports:
        #    print("    " + imp.name)
        #    for nid in imp.nids:
        #        print("      " + "0x{:08X}".format(nid))
    
    def print_nids_yaml(modinfo):
        # We only care about exports
        global PrintedModules
        if len(modinfo.exports) == 0:
            return
        if(not PrintedModules):
            print("modules:")
            PrintedModules = True
        print("  " + modinfo.name + ":")
        print("    libraries:")
    
        for exp in modinfo.exports:
            if not exp.name:
                continue
    
            print("      " + exp.name + ":")
            print("        functions:")
            for nid in exp.nids:
                nid_formatted = "0x{:08X}".format(nid)
                if(nid_formatted in NIDNames):
                    print("          " + NIDNames[nid_formatted] + ": " + nid_formatted)
                else:
                    UnnamedNIDS.append(modinfo.name + " : " + nid_formatted + "\n")
                    print("          " + exp.name + "_" + nid_formatted + ": " + nid_formatted)
    
    def process_file(filename):
        with open(filename, 'rb') as f:
            elffile = ELFFile(f)
    
            if elffile.header.e_ident["EI_OSABI"] == ELFOSABI_CELL_LV2:
                if elffile.header.e_type == ET_SCE_PPURELEXEC:
                    modinfo = read_nids_ps3_prx(f, elffile)
                elif elffile.header.e_type == "ET_EXEC":
                    modinfo = read_nids_ps3_elf(f, elffile)
    
                #print_nids(modinfo)
                print_nids_yaml(modinfo)
            else:
                print("Error: not a PS3 PPU ELF", file=sys.stderr)
                exit(1)
    
    def parse_nid_names(filename):
        with open(filename, 'rt') as f:
            nidnamereader = csv.reader(f, delimiter=" ")
            for row in nidnamereader:
                NIDNames[row[0]] = row[1]
    
    if __name__ == '__main__':
        #if len(sys.argv) < 2:
        #	usage()
        #else:
        #	process_file(sys.argv[1])
        parse_nid_names("nids.txt")
        for subdir, dirs, files in os.walk(sys.argv[1]):
            for file in sorted(files):
                #print(file, file=sys.stderr)
                filepath = subdir + os.sep + file
                process_file(filepath)
                unnamed_nids_file = open("nids_without_name.txt", "wt")
                unnamed_nids_file.writelines(UnnamedNIDS)
                unnamed_nids_file.close()
  23. Fancy2209 commented on Aug 20, 2025

    @Fancy2209
    Member

    I have made a database of all SPRX (and some vsh exports)
    https://github.com/Fancy2209/Cell-Headers/tree/master/db
    now we just need to update the headers based on the real func names and make ones for all the previously missing functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions